diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/bin/app-tauri b/target/release/bundle/appimage/IdeA.AppDir/usr/bin/app-tauri deleted file mode 100755 index 2271593..0000000 Binary files a/target/release/bundle/appimage/IdeA.AppDir/usr/bin/app-tauri and /dev/null differ diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index--__WoY0J.js b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index--__WoY0J.js deleted file mode 100644 index 5a793da..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index--__WoY0J.js +++ /dev/null @@ -1,128 +0,0 @@ -var p0=Object.defineProperty;var m0=(e,t,n)=>t in e?p0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var X=(e,t,n)=>m0(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var _a=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function nf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var e_={exports:{}},lc={},t_={exports:{}},Se={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ql=Symbol.for("react.element"),g0=Symbol.for("react.portal"),x0=Symbol.for("react.fragment"),v0=Symbol.for("react.strict_mode"),_0=Symbol.for("react.profiler"),y0=Symbol.for("react.provider"),b0=Symbol.for("react.context"),w0=Symbol.for("react.forward_ref"),S0=Symbol.for("react.suspense"),k0=Symbol.for("react.memo"),C0=Symbol.for("react.lazy"),Up=Symbol.iterator;function j0(e){return e===null||typeof e!="object"?null:(e=Up&&e[Up]||e["@@iterator"],typeof e=="function"?e:null)}var n_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},r_=Object.assign,s_={};function yi(e,t,n){this.props=e,this.context=t,this.refs=s_,this.updater=n||n_}yi.prototype.isReactComponent={};yi.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};yi.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function i_(){}i_.prototype=yi.prototype;function rf(e,t,n){this.props=e,this.context=t,this.refs=s_,this.updater=n||n_}var sf=rf.prototype=new i_;sf.constructor=rf;r_(sf,yi.prototype);sf.isPureReactComponent=!0;var qp=Array.isArray,l_=Object.prototype.hasOwnProperty,lf={current:null},o_={key:!0,ref:!0,__self:!0,__source:!0};function a_(e,t,n){var r,s={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)l_.call(t,r)&&!o_.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,q=P[se];if(0>>1;ses(ee,j))Qs(V,ee)?(P[se]=V,P[Q]=j,se=Q):(P[se]=ee,P[re]=j,se=re);else if(Qs(V,j))P[se]=V,P[Q]=j,se=Q;else break e}}return z}function s(P,z){var j=P.sortIndex-z.sortIndex;return j!==0?j:P.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,a=l.now();e.unstable_now=function(){return l.now()-a}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,x=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(P){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=P)r(u),z.sortIndex=z.expirationTime,t(c,z);else break;z=n(u)}}function b(P){if(x=!1,y(P),!m)if(n(c)!==null)m=!0,W(C);else{var z=n(u);z!==null&&G(b,z.startTime-P)}}function C(P,z){m=!1,x&&(x=!1,v(L),L=-1),p=!0;var j=f;try{for(y(z),d=n(c);d!==null&&(!(d.expirationTime>z)||P&&!D());){var se=d.callback;if(typeof se=="function"){d.callback=null,f=d.priorityLevel;var q=se(d.expirationTime<=z);z=e.unstable_now(),typeof q=="function"?d.callback=q:d===n(c)&&r(c),y(z)}else r(c);d=n(c)}if(d!==null)var T=!0;else{var re=n(u);re!==null&&G(b,re.startTime-z),T=!1}return T}finally{d=null,f=j,p=!1}}var S=!1,N=null,L=-1,A=5,k=-1;function D(){return!(e.unstable_now()-kP||125se?(P.sortIndex=j,t(u,P),n(c)===null&&P===n(u)&&(x?(v(L),L=-1):x=!0,G(b,j-se))):(P.sortIndex=q,t(c,P),m||p||(m=!0,W(C))),P},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(P){var z=f;return function(){var j=f;f=z;try{return P.apply(this,arguments)}finally{f=j}}}})(f_);h_.exports=f_;var B0=h_.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var z0=g,an=B0;function J(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),id=Object.prototype.hasOwnProperty,F0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Kp={},Gp={};function $0(e){return id.call(Gp,e)?!0:id.call(Kp,e)?!1:F0.test(e)?Gp[e]=!0:(Kp[e]=!0,!1)}function W0(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function H0(e,t,n,r){if(t===null||typeof t>"u"||W0(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function zt(e,t,n,r,s,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var wt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wt[e]=new zt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wt[t]=new zt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wt[e]=new zt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wt[e]=new zt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){wt[e]=new zt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wt[e]=new zt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wt[e]=new zt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wt[e]=new zt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wt[e]=new zt(e,5,!1,e.toLowerCase(),null,!1,!1)});var af=/[\-:]([a-z])/g;function cf(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(af,cf);wt[t]=new zt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(af,cf);wt[t]=new zt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(af,cf);wt[t]=new zt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wt[e]=new zt(e,1,!1,e.toLowerCase(),null,!1,!1)});wt.xlinkHref=new zt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wt[e]=new zt(e,1,!1,e.toLowerCase(),null,!0,!0)});function uf(e,t,n,r){var s=wt.hasOwnProperty(t)?wt[t]:null;(s!==null?s.type!==0:r||!(2a||s[l]!==i[a]){var c=` -`+s[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=a);break}}}finally{Bc=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?el(e):""}function U0(e){switch(e.tag){case 5:return el(e.type);case 16:return el("Lazy");case 13:return el("Suspense");case 19:return el("SuspenseList");case 0:case 2:case 15:return e=zc(e.type,!1),e;case 11:return e=zc(e.type.render,!1),e;case 1:return e=zc(e.type,!0),e;default:return""}}function cd(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case qs:return"Fragment";case Us:return"Portal";case ld:return"Profiler";case df:return"StrictMode";case od:return"Suspense";case ad:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case g_:return(e.displayName||"Context")+".Consumer";case m_:return(e._context.displayName||"Context")+".Provider";case hf:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ff:return t=e.displayName||null,t!==null?t:cd(e.type)||"Memo";case kr:t=e._payload,e=e._init;try{return cd(e(t))}catch{}}return null}function q0(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return cd(t);case 8:return t===df?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Hr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function v_(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function V0(e){var t=v_(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function co(e){e._valueTracker||(e._valueTracker=V0(e))}function __(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=v_(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ya(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function ud(e,t){var n=t.checked;return Ke({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xp(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Hr(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function y_(e,t){t=t.checked,t!=null&&uf(e,"checked",t,!1)}function dd(e,t){y_(e,t);var n=Hr(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?hd(e,t.type,n):t.hasOwnProperty("defaultValue")&&hd(e,t.type,Hr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Qp(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function hd(e,t,n){(t!=="number"||ya(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var tl=Array.isArray;function ri(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=uo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sl(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var cl={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},K0=["Webkit","ms","Moz","O"];Object.keys(cl).forEach(function(e){K0.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),cl[t]=cl[e]})});function k_(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||cl.hasOwnProperty(e)&&cl[e]?(""+t).trim():t+"px"}function C_(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=k_(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var G0=Ke({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function md(e,t){if(t){if(G0[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(J(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(J(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(J(61))}if(t.style!=null&&typeof t.style!="object")throw Error(J(62))}}function gd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var xd=null;function pf(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var vd=null,si=null,ii=null;function em(e){if(e=Gl(e)){if(typeof vd!="function")throw Error(J(280));var t=e.stateNode;t&&(t=dc(t),vd(e.stateNode,e.type,t))}}function j_(e){si?ii?ii.push(e):ii=[e]:si=e}function N_(){if(si){var e=si,t=ii;if(ii=si=null,em(e),t)for(e=0;e>>=0,e===0?32:31-(ik(e)/lk|0)|0}var ho=64,fo=4194304;function nl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ka(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,l=n&268435455;if(l!==0){var a=l&~s;a!==0?r=nl(a):(i&=l,i!==0&&(r=nl(i)))}else l=n&~s,l!==0?r=nl(l):i!==0&&(r=nl(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Vl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Pn(t),e[t]=n}function uk(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=dl),cm=" ",um=!1;function K_(e,t){switch(e){case"keyup":return Bk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function G_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Vs=!1;function Fk(e,t){switch(e){case"compositionend":return G_(t);case"keypress":return t.which!==32?null:(um=!0,cm);case"textInput":return e=t.data,e===cm&&um?null:e;default:return null}}function $k(e,t){if(Vs)return e==="compositionend"||!wf&&K_(e,t)?(e=q_(),Zo=_f=Tr=null,Vs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=pm(n)}}function J_(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?J_(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Z_(){for(var e=window,t=ya();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ya(e.document)}return t}function Sf(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Xk(e){var t=Z_(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&J_(n.ownerDocument.documentElement,n)){if(r!==null&&Sf(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=mm(n,i);var l=mm(n,r);s&&l&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Ks=null,kd=null,fl=null,Cd=!1;function gm(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Cd||Ks==null||Ks!==ya(r)||(r=Ks,"selectionStart"in r&&Sf(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),fl&&Pl(fl,r)||(fl=r,r=Na(kd,"onSelect"),0Xs||(e.current=Td[Xs],Td[Xs]=null,Xs--)}function Ie(e,t){Xs++,Td[Xs]=e.current,e.current=t}var Ur={},Tt=Vr(Ur),Gt=Vr(!1),xs=Ur;function di(e,t){var n=e.type.contextTypes;if(!n)return Ur;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Yt(e){return e=e.childContextTypes,e!=null}function Pa(){ze(Gt),ze(Tt)}function Sm(e,t,n){if(Tt.current!==Ur)throw Error(J(168));Ie(Tt,t),Ie(Gt,n)}function ay(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(J(108,q0(e)||"Unknown",s));return Ke({},n,r)}function Aa(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ur,xs=Tt.current,Ie(Tt,e),Ie(Gt,Gt.current),!0}function km(e,t,n){var r=e.stateNode;if(!r)throw Error(J(169));n?(e=ay(e,t,xs),r.__reactInternalMemoizedMergedChildContext=e,ze(Gt),ze(Tt),Ie(Tt,e)):ze(Gt),Ie(Gt,n)}var rr=null,hc=!1,Zc=!1;function cy(e){rr===null?rr=[e]:rr.push(e)}function a1(e){hc=!0,cy(e)}function Kr(){if(!Zc&&rr!==null){Zc=!0;var e=0,t=Ae;try{var n=rr;for(Ae=1;e>=l,s-=l,ir=1<<32-Pn(t)+s|n<L?(A=N,N=null):A=N.sibling;var k=f(v,N,y[L],b);if(k===null){N===null&&(N=A);break}e&&N&&k.alternate===null&&t(v,N),_=i(k,_,L),S===null?C=k:S.sibling=k,S=k,N=A}if(L===y.length)return n(v,N),Fe&&ns(v,L),C;if(N===null){for(;LL?(A=N,N=null):A=N.sibling;var D=f(v,N,k.value,b);if(D===null){N===null&&(N=A);break}e&&N&&D.alternate===null&&t(v,N),_=i(D,_,L),S===null?C=D:S.sibling=D,S=D,N=A}if(k.done)return n(v,N),Fe&&ns(v,L),C;if(N===null){for(;!k.done;L++,k=y.next())k=d(v,k.value,b),k!==null&&(_=i(k,_,L),S===null?C=k:S.sibling=k,S=k);return Fe&&ns(v,L),C}for(N=r(v,N);!k.done;L++,k=y.next())k=p(N,v,L,k.value,b),k!==null&&(e&&k.alternate!==null&&N.delete(k.key===null?L:k.key),_=i(k,_,L),S===null?C=k:S.sibling=k,S=k);return e&&N.forEach(function(R){return t(v,R)}),Fe&&ns(v,L),C}function w(v,_,y,b){if(typeof y=="object"&&y!==null&&y.type===qs&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case ao:e:{for(var C=y.key,S=_;S!==null;){if(S.key===C){if(C=y.type,C===qs){if(S.tag===7){n(v,S.sibling),_=s(S,y.props.children),_.return=v,v=_;break e}}else if(S.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===kr&&Nm(C)===S.type){n(v,S.sibling),_=s(S,y.props),_.ref=Mi(v,S,y),_.return=v,v=_;break e}n(v,S);break}else t(v,S);S=S.sibling}y.type===qs?(_=fs(y.props.children,v.mode,b,y.key),_.return=v,v=_):(b=oa(y.type,y.key,y.props,null,v.mode,b),b.ref=Mi(v,_,y),b.return=v,v=b)}return l(v);case Us:e:{for(S=y.key;_!==null;){if(_.key===S)if(_.tag===4&&_.stateNode.containerInfo===y.containerInfo&&_.stateNode.implementation===y.implementation){n(v,_.sibling),_=s(_,y.children||[]),_.return=v,v=_;break e}else{n(v,_);break}else t(v,_);_=_.sibling}_=ou(y,v.mode,b),_.return=v,v=_}return l(v);case kr:return S=y._init,w(v,_,S(y._payload),b)}if(tl(y))return m(v,_,y,b);if(Ai(y))return x(v,_,y,b);yo(v,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,_!==null&&_.tag===6?(n(v,_.sibling),_=s(_,y),_.return=v,v=_):(n(v,_),_=lu(y,v.mode,b),_.return=v,v=_),l(v)):n(v,_)}return w}var fi=fy(!0),py=fy(!1),Da=Vr(null),Ra=null,Zs=null,Nf=null;function Ef(){Nf=Zs=Ra=null}function Pf(e){var t=Da.current;ze(Da),e._currentValue=t}function Rd(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function oi(e,t){Ra=e,Nf=Zs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Kt=!0),e.firstContext=null)}function bn(e){var t=e._currentValue;if(Nf!==e)if(e={context:e,memoizedValue:t,next:null},Zs===null){if(Ra===null)throw Error(J(308));Zs=e,Ra.dependencies={lanes:0,firstContext:e}}else Zs=Zs.next=e;return t}var cs=null;function Af(e){cs===null?cs=[e]:cs.push(e)}function my(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Af(t)):(n.next=s.next,s.next=n),t.interleaved=n,hr(e,r)}function hr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Cr=!1;function Tf(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function gy(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ar(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Br(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ne&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,hr(e,n)}return s=r.interleaved,s===null?(t.next=t,Af(r)):(t.next=s.next,s.next=t),r.interleaved=t,hr(e,n)}function ta(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,gf(e,n)}}function Em(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ma(e,t,n,r){var s=e.updateQueue;Cr=!1;var i=s.firstBaseUpdate,l=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var c=a,u=c.next;c.next=null,l===null?i=u:l.next=u,l=c;var h=e.alternate;h!==null&&(h=h.updateQueue,a=h.lastBaseUpdate,a!==l&&(a===null?h.firstBaseUpdate=u:a.next=u,h.lastBaseUpdate=c))}if(i!==null){var d=s.baseState;l=0,h=u=c=null,a=i;do{var f=a.lane,p=a.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=e,x=a;switch(f=t,p=n,x.tag){case 1:if(m=x.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=x.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Ke({},d,f);break e;case 2:Cr=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},h===null?(u=h=p,c=d):h=h.next=p,l|=f;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;f=a,a=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(h===null&&(c=d),s.baseState=c,s.firstBaseUpdate=u,s.lastBaseUpdate=h,t=s.shared.interleaved,t!==null){s=t;do l|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);ys|=l,e.lanes=l,e.memoizedState=d}}function Pm(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=tu.transition;tu.transition={};try{e(!1),t()}finally{Ae=n,tu.transition=r}}function Dy(){return wn().memoizedState}function h1(e,t,n){var r=Fr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ry(e))My(t,n);else if(n=my(e,t,n,r),n!==null){var s=Ot();An(n,e,r,s),Iy(n,t,r)}}function f1(e,t,n){var r=Fr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ry(e))My(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,a=i(l,n);if(s.hasEagerState=!0,s.eagerState=a,Dn(a,l)){var c=t.interleaved;c===null?(s.next=s,Af(t)):(s.next=c.next,c.next=s),t.interleaved=s;return}}catch{}finally{}n=my(e,t,s,r),n!==null&&(s=Ot(),An(n,e,r,s),Iy(n,t,r))}}function Ry(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function My(e,t){pl=Oa=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Iy(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,gf(e,n)}}var Ba={readContext:bn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},p1={readContext:bn,useCallback:function(e,t){return Fn().memoizedState=[e,t===void 0?null:t],e},useContext:bn,useEffect:Tm,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ra(4194308,4,Ey.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ra(4194308,4,e,t)},useInsertionEffect:function(e,t){return ra(4,2,e,t)},useMemo:function(e,t){var n=Fn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=h1.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Fn();return e={current:e},t.memoizedState=e},useState:Am,useDebugValue:zf,useDeferredValue:function(e){return Fn().memoizedState=e},useTransition:function(){var e=Am(!1),t=e[0];return e=d1.bind(null,e[1]),Fn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,s=Fn();if(Fe){if(n===void 0)throw Error(J(407));n=n()}else{if(n=t(),xt===null)throw Error(J(349));_s&30||yy(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Tm(wy.bind(null,r,i,e),[e]),r.flags|=2048,Ol(9,by.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Fn(),t=xt.identifierPrefix;if(Fe){var n=lr,r=ir;n=(r&~(1<<32-Pn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ml++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[Wn]=t,e[Ll]=r,Vy(e,t,!1,!1),t.stateNode=e;e:{switch(l=gd(n,r),n){case"dialog":Oe("cancel",e),Oe("close",e),s=r;break;case"iframe":case"object":case"embed":Oe("load",e),s=r;break;case"video":case"audio":for(s=0;sgi&&(t.flags|=128,r=!0,Ii(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ia(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ii(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Fe)return Ct(t),null}else 2*et()-i.renderingStartTime>gi&&n!==1073741824&&(t.flags|=128,r=!0,Ii(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=et(),t.sibling=null,n=Ue.current,Ie(Ue,r?n&1|2:n&1),t):(Ct(t),null);case 22:case 23:return qf(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?rn&1073741824&&(Ct(t),t.subtreeFlags&6&&(t.flags|=8192)):Ct(t),null;case 24:return null;case 25:return null}throw Error(J(156,t.tag))}function w1(e,t){switch(Cf(t),t.tag){case 1:return Yt(t.type)&&Pa(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return pi(),ze(Gt),ze(Tt),Rf(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Df(t),null;case 13:if(ze(Ue),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(J(340));hi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ze(Ue),null;case 4:return pi(),null;case 10:return Pf(t.type._context),null;case 22:case 23:return qf(),null;case 24:return null;default:return null}}var wo=!1,Pt=!1,S1=typeof WeakSet=="function"?WeakSet:Set,ae=null;function ei(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ye(e,t,r)}else n.current=null}function Hd(e,t,n){try{n()}catch(r){Ye(e,t,r)}}var Wm=!1;function k1(e,t){if(jd=Ca,e=Z_(),Sf(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,a=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||s!==0&&d.nodeType!==3||(a=l+s),d!==i||r!==0&&d.nodeType!==3||(c=l+r),d.nodeType===3&&(l+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===s&&(a=l),f===i&&++h===r&&(c=l),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=a===-1||c===-1?null:{start:a,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Nd={focusedElem:e,selectionRange:n},Ca=!1,ae=t;ae!==null;)if(t=ae,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ae=e;else for(;ae!==null;){t=ae;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var x=m.memoizedProps,w=m.memoizedState,v=t.stateNode,_=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:jn(t.type,x),w);v.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(J(163))}}catch(b){Ye(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,ae=e;break}ae=t.return}return m=Wm,Wm=!1,m}function ml(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Hd(t,n,i)}s=s.next}while(s!==r)}}function mc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ud(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Yy(e){var t=e.alternate;t!==null&&(e.alternate=null,Yy(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Wn],delete t[Ll],delete t[Ad],delete t[l1],delete t[o1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xy(e){return e.tag===5||e.tag===3||e.tag===4}function Hm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xy(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function qd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ea));else if(r!==4&&(e=e.child,e!==null))for(qd(e,t,n),e=e.sibling;e!==null;)qd(e,t,n),e=e.sibling}function Vd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Vd(e,t,n),e=e.sibling;e!==null;)Vd(e,t,n),e=e.sibling}var _t=null,Nn=!1;function vr(e,t,n){for(n=n.child;n!==null;)Qy(e,t,n),n=n.sibling}function Qy(e,t,n){if(qn&&typeof qn.onCommitFiberUnmount=="function")try{qn.onCommitFiberUnmount(oc,n)}catch{}switch(n.tag){case 5:Pt||ei(n,t);case 6:var r=_t,s=Nn;_t=null,vr(e,t,n),_t=r,Nn=s,_t!==null&&(Nn?(e=_t,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):_t.removeChild(n.stateNode));break;case 18:_t!==null&&(Nn?(e=_t,n=n.stateNode,e.nodeType===8?Jc(e.parentNode,n):e.nodeType===1&&Jc(e,n),Nl(e)):Jc(_t,n.stateNode));break;case 4:r=_t,s=Nn,_t=n.stateNode.containerInfo,Nn=!0,vr(e,t,n),_t=r,Nn=s;break;case 0:case 11:case 14:case 15:if(!Pt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&Hd(n,t,l),s=s.next}while(s!==r)}vr(e,t,n);break;case 1:if(!Pt&&(ei(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Ye(n,t,a)}vr(e,t,n);break;case 21:vr(e,t,n);break;case 22:n.mode&1?(Pt=(r=Pt)||n.memoizedState!==null,vr(e,t,n),Pt=r):vr(e,t,n);break;default:vr(e,t,n)}}function Um(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new S1),t.forEach(function(r){var s=D1.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Cn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=l),r&=~i}if(r=s,r=et()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*j1(r/1960))-r,10e?16:e,Lr===null)var r=!1;else{if(e=Lr,Lr=null,$a=0,Ne&6)throw Error(J(331));var s=Ne;for(Ne|=4,ae=e.current;ae!==null;){var i=ae,l=i.child;if(ae.flags&16){var a=i.deletions;if(a!==null){for(var c=0;cet()-Hf?hs(e,0):Wf|=n),Xt(e,t)}function ib(e,t){t===0&&(e.mode&1?(t=fo,fo<<=1,!(fo&130023424)&&(fo=4194304)):t=1);var n=Ot();e=hr(e,t),e!==null&&(Vl(e,t,n),Xt(e,n))}function L1(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ib(e,n)}function D1(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(J(314))}r!==null&&r.delete(t),ib(e,n)}var lb;lb=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Gt.current)Kt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Kt=!1,y1(e,t,n);Kt=!!(e.flags&131072)}else Kt=!1,Fe&&t.flags&1048576&&uy(t,La,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;sa(e,t),e=t.pendingProps;var s=di(t,Tt.current);oi(t,n),s=If(null,t,r,e,s,n);var i=Of();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Yt(r)?(i=!0,Aa(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Tf(t),s.updater=pc,t.stateNode=s,s._reactInternals=t,Id(t,r,e,n),t=zd(null,t,r,!0,i,n)):(t.tag=0,Fe&&i&&kf(t),Mt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(sa(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=M1(r),e=jn(r,e),s){case 0:t=Bd(null,t,r,e,n);break e;case 1:t=zm(null,t,r,e,n);break e;case 11:t=Om(null,t,r,e,n);break e;case 14:t=Bm(null,t,r,jn(r.type,e),n);break e}throw Error(J(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),Bd(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),zm(e,t,r,s,n);case 3:e:{if(Hy(t),e===null)throw Error(J(387));r=t.pendingProps,i=t.memoizedState,s=i.element,gy(e,t),Ma(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=mi(Error(J(423)),t),t=Fm(e,t,r,n,s);break e}else if(r!==s){s=mi(Error(J(424)),t),t=Fm(e,t,r,n,s);break e}else for(sn=Or(t.stateNode.containerInfo.firstChild),ln=t,Fe=!0,En=null,n=py(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(hi(),r===s){t=fr(e,t,n);break e}Mt(e,t,r,n)}t=t.child}return t;case 5:return xy(t),e===null&&Dd(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,l=s.children,Ed(r,s)?l=null:i!==null&&Ed(r,i)&&(t.flags|=32),Wy(e,t),Mt(e,t,l,n),t.child;case 6:return e===null&&Dd(t),null;case 13:return Uy(e,t,n);case 4:return Lf(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=fi(t,null,r,n):Mt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),Om(e,t,r,s,n);case 7:return Mt(e,t,t.pendingProps,n),t.child;case 8:return Mt(e,t,t.pendingProps.children,n),t.child;case 12:return Mt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,l=s.value,Ie(Da,r._currentValue),r._currentValue=l,i!==null)if(Dn(i.value,l)){if(i.children===s.children&&!Gt.current){t=fr(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){l=i.child;for(var c=a.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=ar(-1,n&-n),c.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Rd(i.return,n,t),a.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(J(341));l.lanes|=n,a=l.alternate,a!==null&&(a.lanes|=n),Rd(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Mt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,oi(t,n),s=bn(s),r=r(s),t.flags|=1,Mt(e,t,r,n),t.child;case 14:return r=t.type,s=jn(r,t.pendingProps),s=jn(r.type,s),Bm(e,t,r,s,n);case 15:return Fy(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),sa(e,t),t.tag=1,Yt(r)?(e=!0,Aa(t)):e=!1,oi(t,n),Oy(t,r,s),Id(t,r,s,n),zd(null,t,r,!0,e,n);case 19:return qy(e,t,n);case 22:return $y(e,t,n)}throw Error(J(156,t.tag))};function ob(e,t){return R_(e,t)}function R1(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vn(e,t,n,r){return new R1(e,t,n,r)}function Kf(e){return e=e.prototype,!(!e||!e.isReactComponent)}function M1(e){if(typeof e=="function")return Kf(e)?1:0;if(e!=null){if(e=e.$$typeof,e===hf)return 11;if(e===ff)return 14}return 2}function $r(e,t){var n=e.alternate;return n===null?(n=vn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function oa(e,t,n,r,s,i){var l=2;if(r=e,typeof e=="function")Kf(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case qs:return fs(n.children,s,i,t);case df:l=8,s|=8;break;case ld:return e=vn(12,n,t,s|2),e.elementType=ld,e.lanes=i,e;case od:return e=vn(13,n,t,s),e.elementType=od,e.lanes=i,e;case ad:return e=vn(19,n,t,s),e.elementType=ad,e.lanes=i,e;case x_:return xc(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case m_:l=10;break e;case g_:l=9;break e;case hf:l=11;break e;case ff:l=14;break e;case kr:l=16,r=null;break e}throw Error(J(130,e==null?e:typeof e,""))}return t=vn(l,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function fs(e,t,n,r){return e=vn(7,e,r,t),e.lanes=n,e}function xc(e,t,n,r){return e=vn(22,e,r,t),e.elementType=x_,e.lanes=n,e.stateNode={isHidden:!1},e}function lu(e,t,n){return e=vn(6,e,null,t),e.lanes=n,e}function ou(e,t,n){return t=vn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function I1(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=$c(0),this.expirationTimes=$c(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=$c(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Gf(e,t,n,r,s,i,l,a,c){return e=new I1(e,t,n,a,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=vn(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tf(i),e}function O1(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(db)}catch(e){console.error(e)}}db(),d_.exports=cn;var W1=d_.exports,Jm=W1;sd.createRoot=Jm.createRoot,sd.hydrateRoot=Jm.hydrateRoot;/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var hb=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,U1=(e,t)=>{for(var n in t)hb(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,r)=>{for(var s=r>1?void 0:r?H1(t,n):t,i=e.length-1,l;i>=0;i--)(l=e[i])&&(s=(r?l(t,n,s):l(s))||s);return r&&s&&hb(t,n,s),s},ie=(e,t)=>(n,r)=>t(n,r,e),Zm="Terminal input",Qd={get:()=>Zm,set:e=>Zm=e},eg="Too much output to announce, navigate to rows manually to read",Jd={get:()=>eg,set:e=>eg=e};function q1(e){return e.replace(/\r?\n/g,"\r")}function V1(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function K1(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function G1(e,t,n,r){if(e.stopPropagation(),e.clipboardData){let s=e.clipboardData.getData("text/plain");fb(s,t,n,r)}}function fb(e,t,n,r){e=q1(e),e=V1(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function pb(e,t,n){let r=n.getBoundingClientRect(),s=e.clientX-r.left-10,i=e.clientY-r.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${s}px`,t.style.top=`${i}px`,t.style.zIndex="1000",t.focus()}function tg(e,t,n,r,s){pb(e,t,n),s&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function jr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function wc(e,t=0,n=e.length){let r="";for(let s=t;s65535?(i-=65536,r+=String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):r+=String.fromCharCode(i)}return r}var Y1=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,s=0;if(this._interim){let i=e.charCodeAt(s++);56320<=i&&i<=57343?t[r++]=(this._interim-55296)*1024+i-56320+65536:(t[r++]=this._interim,t[r++]=i),this._interim=0}for(let i=s;i=n)return this._interim=l,r;let a=e.charCodeAt(i);56320<=a&&a<=57343?t[r++]=(l-55296)*1024+a-56320+65536:(t[r++]=l,t[r++]=a);continue}l!==65279&&(t[r++]=l)}return r}},X1=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,s,i,l,a,c=0,u=0;if(this.interim[0]){let f=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,x;for(;(x=this.interim[++m]&63)&&m<4;)p<<=6,p|=x;let w=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,v=w-m;for(;u=n)return 0;if(x=e[u++],(x&192)!==128){u--,f=!0;break}else this.interim[m++]=x,p<<=6,p|=x&63}f||(w===2?p<128?u--:t[r++]=p:w===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let h=n-4,d=u;for(;d=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(c=(s&31)<<6|i&63,c<128){d--;continue}t[r++]=c}else if((s&240)===224){if(d>=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,r;if(l=e[d++],(l&192)!==128){d--;continue}if(c=(s&15)<<12|(i&63)<<6|l&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((s&248)===240){if(d>=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,r;if(l=e[d++],(l&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,this.interim[2]=l,r;if(a=e[d++],(a&192)!==128){d--;continue}if(c=(s&7)<<18|(i&63)<<12|(l&63)<<6|a&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},mb="",Dr=" ",Xl=class gb{constructor(){this.fg=0,this.bg=0,this.extended=new Ua}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new gb;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Ua=class xb{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new xb(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},yn=class vb extends Xl{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Ua,this.combinedData=""}static fromCharData(t){let n=new vb;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?jr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let s=t[1].charCodeAt(1);56320<=s&&s<=57343?this.content=(r-55296)*1024+s-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ng="di$target",Zd="di$dependencies",au=new Map;function Q1(e){return e[Zd]||[]}function vt(e){if(au.has(e))return au.get(e);let t=function(n,r,s){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");J1(t,n,s)};return t._id=e,au.set(e,t),t}function J1(e,t,n){t[ng]===t?t[Zd].push({id:e,index:n}):(t[Zd]=[{id:e,index:n}],t[ng]=t)}var Ft=vt("BufferService"),_b=vt("CoreMouseService"),Ns=vt("CoreService"),Z1=vt("CharsetService"),Jf=vt("InstantiationService"),yb=vt("LogService"),$t=vt("OptionsService"),bb=vt("OscLinkService"),eC=vt("UnicodeService"),Ql=vt("DecorationService"),eh=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],s=this._optionsService.rawOptions.linkHandler,i=new yn,l=n.getTrimmedLength(),a=-1,c=-1,u=!1;for(let h=0;hs?s.activate(m,x,f):tC(m,x),hover:(m,x)=>s?.hover?.(m,x,f),leave:(m,x)=>s?.leave?.(m,x,f)})}u=!1,i.hasExtendedAttrs()&&i.extended.urlId?(c=h,a=i.extended.urlId):(c=-1,a=-1)}}t(r)}};eh=Qe([ie(0,Ft),ie(1,$t),ie(2,bb)],eh);function tC(e,t){if(confirm(`Do you want to navigate to ${t}? - -WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Sc=vt("CharSizeService"),mr=vt("CoreBrowserService"),Zf=vt("MouseService"),gr=vt("RenderService"),nC=vt("SelectionService"),wb=vt("CharacterJoinerService"),Si=vt("ThemeService"),Sb=vt("LinkProviderService"),rC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?rg.isErrorNoTelemetry(e)?new rg(e.message+` - -`+e.stack):new Error(e.message+` - -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},sC=new rC;function aa(e){iC(e)||sC.onUnexpectedError(e)}var th="Canceled";function iC(e){return e instanceof lC?!0:e instanceof Error&&e.name===th&&e.message===th}var lC=class extends Error{constructor(){super(th),this.name=this.message}};function oC(e){return new Error(`Illegal argument: ${e}`)}var rg=class nh extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof nh)return t;let n=new nh;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},rh=class kb extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,kb.prototype)}};function Zt(e,t=0){return e[e.length-(1+t)]}var aC;(e=>{function t(i){return i<0}e.isLessThan=t;function n(i){return i<=0}e.isLessThanOrEqual=n;function r(i){return i>0}e.isGreaterThan=r;function s(i){return i===0}e.isNeitherLessOrGreaterThan=s,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(aC||={});function cC(e,t){let n=this,r=!1,s;return function(){return r||(r=!0,t||(s=e.apply(n,arguments))),s}}var Cb;(e=>{function t(b){return b&&typeof b=="object"&&typeof b[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*s(b){yield b}e.single=s;function i(b){return t(b)?b:s(b)}e.wrap=i;function l(b){return b||n}e.from=l;function*a(b){for(let C=b.length-1;C>=0;C--)yield b[C]}e.reverse=a;function c(b){return!b||b[Symbol.iterator]().next().done===!0}e.isEmpty=c;function u(b){return b[Symbol.iterator]().next().value}e.first=u;function h(b,C){let S=0;for(let N of b)if(C(N,S++))return!0;return!1}e.some=h;function d(b,C){for(let S of b)if(C(S))return S}e.find=d;function*f(b,C){for(let S of b)C(S)&&(yield S)}e.filter=f;function*p(b,C){let S=0;for(let N of b)yield C(N,S++)}e.map=p;function*m(b,C){let S=0;for(let N of b)yield*C(N,S++)}e.flatMap=m;function*x(...b){for(let C of b)yield*C}e.concat=x;function w(b,C,S){let N=S;for(let L of b)N=C(N,L);return N}e.reduce=w;function*v(b,C,S=b.length){for(C<0&&(C+=b.length),S<0?S+=b.length:S>b.length&&(S=b.length);C1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function uC(...e){return $e(()=>ws(e))}function $e(e){return{dispose:cC(()=>{e()})}}var jb=class Nb{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ws(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Nb.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};jb.DISABLE_DISPOSED_WARNING=!1;var Wr=jb,be=class{constructor(){this._store=new Wr,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};be.None=Object.freeze({dispose(){}});var xi=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},or=typeof window=="object"?window:globalThis,sh=class ih{constructor(t){this.element=t,this.next=ih.Undefined,this.prev=ih.Undefined}};sh.Undefined=new sh(void 0);var We=sh,sg=class{constructor(){this._first=We.Undefined,this._last=We.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===We.Undefined}clear(){let e=this._first;for(;e!==We.Undefined;){let t=e.next;e.prev=We.Undefined,e.next=We.Undefined,e=t}this._first=We.Undefined,this._last=We.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new We(e);if(this._first===We.Undefined)this._first=n,this._last=n;else if(t){let s=this._last;this._last=n,n.prev=s,s.next=n}else{let s=this._first;this._first=n,n.next=s,s.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==We.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==We.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==We.Undefined&&e.next!==We.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===We.Undefined&&e.next===We.Undefined?(this._first=We.Undefined,this._last=We.Undefined):e.next===We.Undefined?(this._last=this._last.prev,this._last.next=We.Undefined):e.prev===We.Undefined&&(this._first=this._first.next,this._first.prev=We.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==We.Undefined;)yield e.element,e=e.next}},dC=globalThis.performance&&typeof globalThis.performance.now=="function",hC=class Eb{static create(t){return new Eb(t)}constructor(t){this._now=dC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},yt;(e=>{e.None=()=>be.None;function t(R,E){return d(R,()=>{},0,void 0,!0,void 0,E)}e.defer=t;function n(R){return(E,O=null,I)=>{let W=!1,G;return G=R(P=>{if(!W)return G?G.dispose():W=!0,E.call(O,P)},null,I),W&&G.dispose(),G}}e.once=n;function r(R,E,O){return u((I,W=null,G)=>R(P=>I.call(W,E(P)),null,G),O)}e.map=r;function s(R,E,O){return u((I,W=null,G)=>R(P=>{E(P),I.call(W,P)},null,G),O)}e.forEach=s;function i(R,E,O){return u((I,W=null,G)=>R(P=>E(P)&&I.call(W,P),null,G),O)}e.filter=i;function l(R){return R}e.signal=l;function a(...R){return(E,O=null,I)=>{let W=uC(...R.map(G=>G(P=>E.call(O,P))));return h(W,I)}}e.any=a;function c(R,E,O,I){let W=O;return r(R,G=>(W=E(W,G),W),I)}e.reduce=c;function u(R,E){let O,I={onWillAddFirstListener(){O=R(W.fire,W)},onDidRemoveLastListener(){O?.dispose()}},W=new ne(I);return E?.add(W),W.event}function h(R,E){return E instanceof Array?E.push(R):E&&E.add(R),R}function d(R,E,O=100,I=!1,W=!1,G,P){let z,j,se,q=0,T,re={leakWarningThreshold:G,onWillAddFirstListener(){z=R(Q=>{q++,j=E(j,Q),I&&!se&&(ee.fire(j),j=void 0),T=()=>{let V=j;j=void 0,se=void 0,(!I||q>1)&&ee.fire(V),q=0},typeof O=="number"?(clearTimeout(se),se=setTimeout(T,O)):se===void 0&&(se=0,queueMicrotask(T))})},onWillRemoveListener(){W&&q>0&&T?.()},onDidRemoveLastListener(){T=void 0,z.dispose()}},ee=new ne(re);return P?.add(ee),ee.event}e.debounce=d;function f(R,E=0,O){return e.debounce(R,(I,W)=>I?(I.push(W),I):[W],E,void 0,!0,void 0,O)}e.accumulate=f;function p(R,E=(I,W)=>I===W,O){let I=!0,W;return i(R,G=>{let P=I||!E(G,W);return I=!1,W=G,P},O)}e.latch=p;function m(R,E,O){return[e.filter(R,E,O),e.filter(R,I=>!E(I),O)]}e.split=m;function x(R,E=!1,O=[],I){let W=O.slice(),G=R(j=>{W?W.push(j):z.fire(j)});I&&I.add(G);let P=()=>{W?.forEach(j=>z.fire(j)),W=null},z=new ne({onWillAddFirstListener(){G||(G=R(j=>z.fire(j)),I&&I.add(G))},onDidAddFirstListener(){W&&(E?setTimeout(P):P())},onDidRemoveLastListener(){G&&G.dispose(),G=null}});return I&&I.add(z),z.event}e.buffer=x;function w(R,E){return(O,I,W)=>{let G=E(new _);return R(function(P){let z=G.evaluate(P);z!==v&&O.call(I,z)},void 0,W)}}e.chain=w;let v=Symbol("HaltChainable");class _{constructor(){this.steps=[]}map(E){return this.steps.push(E),this}forEach(E){return this.steps.push(O=>(E(O),O)),this}filter(E){return this.steps.push(O=>E(O)?O:v),this}reduce(E,O){let I=O;return this.steps.push(W=>(I=E(I,W),I)),this}latch(E=(O,I)=>O===I){let O=!0,I;return this.steps.push(W=>{let G=O||!E(W,I);return O=!1,I=W,G?W:v}),this}evaluate(E){for(let O of this.steps)if(E=O(E),E===v)break;return E}}function y(R,E,O=I=>I){let I=(...z)=>P.fire(O(...z)),W=()=>R.on(E,I),G=()=>R.removeListener(E,I),P=new ne({onWillAddFirstListener:W,onDidRemoveLastListener:G});return P.event}e.fromNodeEventEmitter=y;function b(R,E,O=I=>I){let I=(...z)=>P.fire(O(...z)),W=()=>R.addEventListener(E,I),G=()=>R.removeEventListener(E,I),P=new ne({onWillAddFirstListener:W,onDidRemoveLastListener:G});return P.event}e.fromDOMEventEmitter=b;function C(R){return new Promise(E=>n(R)(E))}e.toPromise=C;function S(R){let E=new ne;return R.then(O=>{E.fire(O)},()=>{E.fire(void 0)}).finally(()=>{E.dispose()}),E.event}e.fromPromise=S;function N(R,E){return R(O=>E.fire(O))}e.forward=N;function L(R,E,O){return E(O),R(I=>E(I))}e.runAndSubscribe=L;class A{constructor(E,O){this._observable=E,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{E.addObserver(this)},onDidRemoveLastListener:()=>{E.removeObserver(this)}};this.emitter=new ne(I),O&&O.add(this.emitter)}beginUpdate(E){this._counter++}handlePossibleChange(E){}handleChange(E,O){this._hasChanged=!0}endUpdate(E){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function k(R,E){return new A(R,E).emitter.event}e.fromObservable=k;function D(R){return(E,O,I)=>{let W=0,G=!1,P={beginUpdate(){W++},endUpdate(){W--,W===0&&(R.reportChanges(),G&&(G=!1,E.call(O)))},handlePossibleChange(){},handleChange(){G=!0}};R.addObserver(P),R.reportChanges();let z={dispose(){R.removeObserver(P)}};return I instanceof Wr?I.add(z):Array.isArray(I)&&I.push(z),z}}e.fromObservableLight=D})(yt||={});var lh=class oh{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${oh._idPool++}`,oh.all.add(this)}start(t){this._stopWatch=new hC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};lh.all=new Set,lh._idPool=0;var fC=lh,pC=-1,Pb=class Ab{constructor(t,n,r=(Ab._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,n){let r=this.threshold;if(r<=0||n{let i=this._stacks.get(t.value)||0;this._stacks.set(t.value,i-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[r,s]of this._stacks)(!t||n{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let a=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new vC(`${l}. HINT: Stack shows most frequent listener (${a[1]}-times)`,a[0]);return(this._options?.onListenerError||aa)(c),be.None}if(this._disposed)return be.None;t&&(e=e.bind(t));let r=new cu(e),s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=gC.create(),s=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof cu?(this._deliveryQueue??=new wC,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let i=$e(()=>{s?.(),this._removeListener(r)});return n instanceof Wr?n.add(i):Array.isArray(n)&&n.push(i),i},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*yC<=t.length){let s=0;for(let i=0;i0}},wC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},ah=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ne,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ne,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(r,t),this._onDidChangeZoomLevel.fire(r)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToFullScreen.set(r,t),this._onDidChangeFullscreen.fire(r)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};ah.INSTANCE=new ah;var ep=ah;function SC(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}ep.INSTANCE.onDidChangeZoomLevel;function kC(e){return ep.INSTANCE.getZoomFactor(e)}ep.INSTANCE.onDidChangeFullscreen;var ki=typeof navigator=="object"?navigator.userAgent:"",ch=ki.indexOf("Firefox")>=0,CC=ki.indexOf("AppleWebKit")>=0,tp=ki.indexOf("Chrome")>=0,jC=!tp&&ki.indexOf("Safari")>=0;ki.indexOf("Electron/")>=0;ki.indexOf("Android")>=0;var uu=!1;if(typeof or.matchMedia=="function"){let e=or.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=or.matchMedia("(display-mode: fullscreen)");uu=e.matches,SC(or,e,({matches:n})=>{uu&&t.matches||(uu=n)})}var ni="en",uh=!1,dh=!1,ca=!1,Lb=!1,Co,ua=ni,ig=ni,NC,tr,ps=globalThis,nn;typeof ps.vscode<"u"&&typeof ps.vscode.process<"u"?nn=ps.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(nn=process);var EC=typeof nn?.versions?.electron=="string",PC=EC&&nn?.type==="renderer";if(typeof nn=="object"){uh=nn.platform==="win32",dh=nn.platform==="darwin",ca=nn.platform==="linux",ca&&nn.env.SNAP&&nn.env.SNAP_REVISION,nn.env.CI||nn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Co=ni,ua=ni;let e=nn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Co=t.userLocale,ig=t.osLocale,ua=t.resolvedLanguage||ni,NC=t.languagePack?.translationsConfigFile}catch{}Lb=!0}else typeof navigator=="object"&&!PC?(tr=navigator.userAgent,uh=tr.indexOf("Windows")>=0,dh=tr.indexOf("Macintosh")>=0,(tr.indexOf("Macintosh")>=0||tr.indexOf("iPad")>=0||tr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ca=tr.indexOf("Linux")>=0,tr?.indexOf("Mobi")>=0,ua=globalThis._VSCODE_NLS_LANGUAGE||ni,Co=navigator.language.toLowerCase(),ig=Co):console.error("Unable to resolve platform.");var Db=uh,Kn=dh,AC=ca,lg=Lb,Gn=tr,_r=ua,TC;(e=>{function t(){return _r}e.value=t;function n(){return _r.length===2?_r==="en":_r.length>=3?_r[0]==="e"&&_r[1]==="n"&&_r[2]==="-":!1}e.isDefaultVariant=n;function r(){return _r==="en"}e.isDefault=r})(TC||={});var LC=typeof ps.postMessage=="function"&&!ps.importScripts;(()=>{if(LC){let e=[];ps.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let r=0,s=e.length;r{let r=++t;e.push({id:r,callback:n}),ps.postMessage({vscodeScheduleAsyncWork:r},"*")}}return e=>setTimeout(e)})();var DC=!!(Gn&&Gn.indexOf("Chrome")>=0);Gn&&Gn.indexOf("Firefox")>=0;!DC&&Gn&&Gn.indexOf("Safari")>=0;Gn&&Gn.indexOf("Edg/")>=0;Gn&&Gn.indexOf("Android")>=0;var Ls=typeof navigator=="object"?navigator:{};lg||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ls&&Ls.clipboard&&Ls.clipboard.writeText,lg||Ls&&Ls.clipboard&&Ls.clipboard.readText;var np=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},du=new np,og=new np,ag=new np,RC=new Array(230),Rb;(e=>{function t(a){return du.keyCodeToStr(a)}e.toString=t;function n(a){return du.strToKeyCode(a)}e.fromString=n;function r(a){return og.keyCodeToStr(a)}e.toUserSettingsUS=r;function s(a){return ag.keyCodeToStr(a)}e.toUserSettingsGeneral=s;function i(a){return og.strToKeyCode(a)||ag.strToKeyCode(a)}e.fromUserSettings=i;function l(a){if(a>=98&&a<=113)return null;switch(a){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return du.keyCodeToStr(a)}e.toElectronAccelerator=l})(Rb||={});var MC=class Mb{constructor(t,n,r,s,i){this.ctrlKey=t,this.shiftKey=n,this.altKey=r,this.metaKey=s,this.keyCode=i}equals(t){return t instanceof Mb&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",r=this.altKey?"1":"0",s=this.metaKey?"1":"0";return`K${t}${n}${r}${s}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new IC([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},IC=class{constructor(e){if(e.length===0)throw oC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t{function t(n){return n===e.None||n===e.Cancelled||n instanceof qC?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:yt.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Ib})})(UC||={});var qC=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Ib:(this._emitter||(this._emitter=new ne),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},rp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new rh("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new rh("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},VC=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new rh("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=$e(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},KC;(e=>{async function t(r){let s,i=await Promise.all(r.map(l=>l.then(a=>a,a=>{s||(s=a)})));if(typeof s<"u")throw s;return i}e.settled=t;function n(r){return new Promise(async(s,i)=>{try{await r(s,i)}catch(l){i(l)}})}e.withAsyncBody=n})(KC||={});var hg=class fn{static fromArray(t){return new fn(n=>{n.emitMany(t)})}static fromPromise(t){return new fn(async n=>{n.emitMany(await t)})}static fromPromises(t){return new fn(async n=>{await Promise.all(t.map(async r=>n.emitOne(await r)))})}static merge(t){return new fn(async n=>{await Promise.all(t.map(async r=>{for await(let s of r)n.emitOne(s)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new ne,queueMicrotask(async()=>{let r={emitOne:s=>this.emitOne(s),emitMany:s=>this.emitMany(s),reject:s=>this.reject(s)};try{await Promise.resolve(t(r)),this.resolve()}catch(s){this.reject(s)}finally{r.emitOne=void 0,r.emitMany=void 0,r.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new fn(async r=>{for await(let s of t)r.emitOne(n(s))})}map(t){return fn.map(this,t)}static filter(t,n){return new fn(async r=>{for await(let s of t)n(s)&&r.emitOne(s)})}filter(t){return fn.filter(this,t)}static coalesce(t){return fn.filter(t,n=>!!n)}coalesce(){return fn.coalesce(this)}static async toPromise(t){let n=[];for await(let r of t)n.push(r);return n}toPromise(){return fn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};hg.EMPTY=hg.fromArray([]);var{getWindow:Un,getWindowId:GC,onDidRegisterWindow:YC}=function(){let e=new Map,t={window:or,disposables:new Wr};e.set(or.vscodeWindowId,t);let n=new ne,r=new ne,s=new ne;function i(l,a){return(typeof l=="number"?e.get(l):void 0)??(a?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:s.event,onDidUnregisterWindow:r.event,registerWindow(l){if(e.has(l.vscodeWindowId))return be.None;let a=new Wr,c={window:l,disposables:a.add(new Wr)};return e.set(l.vscodeWindowId,c),a.add($e(()=>{e.delete(l.vscodeWindowId),r.fire(l)})),a.add(me(l,ht.BEFORE_UNLOAD,()=>{s.fire(l)})),n.fire(c),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(l){return l.vscodeWindowId},hasWindow(l){return e.has(l)},getWindowById:i,getWindow(l){let a=l;if(a?.ownerDocument?.defaultView)return a.ownerDocument.defaultView.window;let c=l;return c?.view?c.view.window:or},getDocument(l){return Un(l).document}}}(),XC=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function me(e,t,n,r){return new XC(e,t,n,r)}var fg=function(e,t,n,r){return me(e,t,n,r)},sp,QC=class extends VC{constructor(e){super(),this.defaultTarget=e&&Un(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},pg=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){aa(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,s=i=>{n.set(i,!1);let l=e.get(i)??[];for(t.set(i,l),e.set(i,[]),r.set(i,!0);l.length>0;)l.sort(pg.sort),l.shift().execute();r.set(i,!1)};sp=(i,l,a=0)=>{let c=GC(i),u=new pg(l,a),h=e.get(c);return h||(h=[],e.set(c,h)),h.push(u),n.get(c)||(n.set(c,!0),i.requestAnimationFrame(()=>s(c))),u}})();function JC(e){let t=e.getBoundingClientRect(),n=Un(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var ht={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},ZC=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Wt(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Wt(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Wt(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Wt(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Wt(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Wt(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Wt(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Wt(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Wt(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Wt(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Wt(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Wt(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Wt(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Wt(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Wt(e){return typeof e=="number"?`${e}px`:e}function vl(e){return new ZC(e)}var Ob=class{constructor(){this._hooks=new Wr,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=s;let i=e;try{e.setPointerCapture(t),this._hooks.add($e(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{i=Un(e)}this._hooks.add(me(i,ht.POINTER_MOVE,l=>{if(l.buttons!==n){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(me(i,ht.POINTER_UP,l=>this.stopMonitoring(!0)))}};function ej(e,t,n){let r=null,s=null;if(typeof n.value=="function"?(r="value",s=n.value,s.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(r="get",s=n.get),!s)throw new Error("not supported");let i=`$memoize$${t}`;n[r]=function(...l){return this.hasOwnProperty(i)||Object.defineProperty(this,i,{configurable:!1,enumerable:!1,writable:!1,value:s.apply(this,l)}),this[i]}}var zn;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(zn||={});var sl=class Nt extends be{constructor(){super(),this.dispatched=!1,this.targets=new sg,this.ignoreTargets=new sg,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(yt.runAndSubscribe(YC,({window:t,disposables:n})=>{n.add(me(t.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),n.add(me(t.document,"touchend",r=>this.onTouchEnd(t,r))),n.add(me(t.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:or,disposables:this._store}))}static addTarget(t){if(!Nt.isTouchDevice())return be.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.targets.push(t);return $e(n)}static ignoreTarget(t){if(!Nt.isTouchDevice())return be.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.ignoreTargets.push(t);return $e(n)}static isTouchDevice(){return"ontouchstart"in or||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,s=t.targetTouches.length;r=Nt.HOLD_DELAY&&Math.abs(c.initialPageX-Zt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Zt(c.rollingPageY))<30){let h=this.newGestureEvent(zn.Contextmenu,c.initialTarget);h.pageX=Zt(c.rollingPageX),h.pageY=Zt(c.rollingPageY),this.dispatchEvent(h)}else if(s===1){let h=Zt(c.rollingPageX),d=Zt(c.rollingPageY),f=Zt(c.rollingTimestamps)-c.rollingTimestamps[0],p=h-c.rollingPageX[0],m=d-c.rollingPageY[0],x=[...this.targets].filter(w=>c.initialTarget instanceof Node&&w.contains(c.initialTarget));this.inertia(t,x,r,Math.abs(p)/f,p>0?1:-1,h,Math.abs(m)/f,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(zn.End,c.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let r=document.createEvent("CustomEvent");return r.initEvent(t,!1,!0),r.initialTarget=n,r.tapCount=0,r}dispatchEvent(t){if(t.type===zn.Tap){let n=new Date().getTime(),r=0;n-this._lastSetTapCountTime>Nt.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===zn.Change||t.type===zn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(t.initialTarget))return;let n=[];for(let r of this.targets)if(r.contains(t.initialTarget)){let s=0,i=t.initialTarget;for(;i&&i!==r;)s++,i=i.parentElement;n.push([s,r])}n.sort((r,s)=>r[0]-s[0]);for(let[r,s]of n)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,s,i,l,a,c,u){this.handle=sp(t,()=>{let h=Date.now(),d=h-r,f=0,p=0,m=!0;s+=Nt.SCROLL_FRICTION*d,a+=Nt.SCROLL_FRICTION*d,s>0&&(m=!1,f=i*s*d),a>0&&(m=!1,p=c*a*d);let x=this.newGestureEvent(zn.Change);x.translationX=f,x.translationY=p,n.forEach(w=>w.dispatchEvent(x)),m||this.inertia(t,n,h,s,i,l+f,a,c,u+p)})}onTouchMove(t){let n=Date.now();for(let r=0,s=t.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(i.pageX),l.rollingPageY.push(i.pageY),l.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};sl.SCROLL_FRICTION=-.005,sl.HOLD_DELAY=700,sl.CLEAR_TAP_COUNT_TIME=400,Qe([ej],sl,"isTouchDevice",1);var tj=sl,ip=class extends be{onclick(e,t){this._register(me(e,ht.CLICK,n=>t(new jo(Un(e),n))))}onmousedown(e,t){this._register(me(e,ht.MOUSE_DOWN,n=>t(new jo(Un(e),n))))}onmouseover(e,t){this._register(me(e,ht.MOUSE_OVER,n=>t(new jo(Un(e),n))))}onmouseleave(e,t){this._register(me(e,ht.MOUSE_LEAVE,n=>t(new jo(Un(e),n))))}onkeydown(e,t){this._register(me(e,ht.KEY_DOWN,n=>t(new cg(n))))}onkeyup(e,t){this._register(me(e,ht.KEY_UP,n=>t(new cg(n))))}oninput(e,t){this._register(me(e,ht.INPUT,t))}onblur(e,t){this._register(me(e,ht.BLUR,t))}onfocus(e,t){this._register(me(e,ht.FOCUS,t))}onchange(e,t){this._register(me(e,ht.CHANGE,t))}ignoreGesture(e){return tj.ignoreTarget(e)}},mg=11,nj=class extends ip{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=mg+"px",this.domNode.style.height=mg+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Ob),this._register(fg(this.bgDomNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(fg(this.domNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new QC),this._pointerdownScheduleRepeatTimer=this._register(new rp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Un(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},rj=class hh{constructor(t,n,r,s,i,l,a){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,r=r|0,s=s|0,i=i|0,l=l|0,a=a|0),this.rawScrollLeft=s,this.rawScrollTop=a,n<0&&(n=0),s+n>r&&(s=r-n),s<0&&(s=0),i<0&&(i=0),a+i>l&&(a=l-i),a<0&&(a=0),this.width=n,this.scrollWidth=r,this.scrollLeft=s,this.height=i,this.scrollHeight=l,this.scrollTop=a}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new hh(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new hh(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let r=this.width!==t.width,s=this.scrollWidth!==t.scrollWidth,i=this.scrollLeft!==t.scrollLeft,l=this.height!==t.height,a=this.scrollHeight!==t.scrollHeight,c=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:r,scrollWidthChanged:s,scrollLeftChanged:i,heightChanged:l,scrollHeightChanged:a,scrollTopChanged:c}}},sj=class extends be{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new rj(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;t?r=new xg(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):r=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=xg.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},gg=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function hu(e,t){let n=t-e;return function(r){return e+n*oj(r)}}function ij(e,t,n){return function(r){return r2.5*r){let s,i;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},cj=140,Bb=class extends ip{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new aj(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Ob),this._shouldRender=!0,this.domNode=vl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(me(this.domNode.domNode,ht.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new nj(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=vl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof n=="number"&&this.slider.setWidth(n),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(me(this.slider.domNode,ht.POINTER_DOWN,s=>{s.button===0&&(s.preventDefault(),this._sliderPointerDown(s))})),this.onclick(this.slider.domNode,s=>{s.leftButton&&s.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),s=this._sliderPointerPosition(e);n<=s&&s<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,n=e.offsetY;else{let s=JC(this.domNode.domNode);t=e.pageX-s.left,n=e.pageY-s.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,s=>{let i=this._sliderOrthogonalPointerPosition(s),l=Math.abs(i-n);if(Db&&l>cj){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let a=this._sliderPointerPosition(s)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},zb=class ph{constructor(t,n,r,s,i,l){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(r),this._arrowSize=Math.round(t),this._visibleSize=s,this._scrollSize=i,this._scrollPosition=l,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ph(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,r,s,i){let l=Math.max(0,r-t),a=Math.max(0,l-2*n),c=s>0&&s>r;if(!c)return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(r*a/s))),h=(a-u)/(s-r),d=i*h;return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=ph._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,r=this._scrollPosition;return n0&&Math.abs(t.deltaY)>0)return 1;let r=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(r+=.25),n){let s=Math.abs(t.deltaX),i=Math.abs(t.deltaY),l=Math.abs(n.deltaX),a=Math.abs(n.deltaY),c=Math.max(Math.min(s,l),1),u=Math.max(Math.min(i,a),1),h=Math.max(s,l),d=Math.max(i,a);h%c===0&&d%u===0&&(r-=.5)}return Math.min(Math.max(r,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};mh.INSTANCE=new mh;var pj=mh,mj=class extends ip{constructor(e,t,n){super(),this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ne),this.onWillScroll=this._onWillScroll.event,this._options=xj(t),this._scrollable=n,this._register(this._scrollable.onScroll(s=>{this._onWillScroll.fire(s),this._onDidScroll(s),this._onScroll.fire(s)}));let r={onMouseWheel:s=>this._onMouseWheel(s),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new dj(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new uj(this._scrollable,this._options,r)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=vl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=vl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=vl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,s=>this._onMouseOver(s)),this.onmouseleave(this._listenOnDomNode,s=>this._onMouseLeave(s)),this._hideTimeout=this._register(new rp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ws(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Kn&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new dg(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ws(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new dg(n))};this._mouseWheelToDispose.push(me(this._listenOnDomNode,ht.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=pj.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let s=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+s===0?i=s=0:Math.abs(s)>=Math.abs(i)?i=0:s=0),this._options.flipAxes&&([s,i]=[i,s]);let l=!Kn&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||l)&&!i&&(i=s,s=0),e.browserEvent&&e.browserEvent.altKey&&(i=i*this._options.fastScrollSensitivity,s=s*this._options.fastScrollSensitivity);let a=this._scrollable.getFutureScrollPosition(),c={};if(s){let u=vg*s,h=a.scrollTop-(u<0?Math.floor(u):Math.ceil(u));this._verticalScrollbar.writeScrollPosition(c,h)}if(i){let u=vg*i,h=a.scrollLeft-(u<0?Math.floor(u):Math.ceil(u));this._horizontalScrollbar.writeScrollPosition(c,h)}c=this._scrollable.validateScrollPosition(c),(a.scrollLeft!==c.scrollLeft||a.scrollTop!==c.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(c):this._scrollable.setScrollPositionNow(c),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?" left":"",s=t?" top":"",i=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${s}`),this._topLeftShadowDomNode.setClassName(`shadow${i}${s}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),hj)}},gj=class extends mj{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function xj(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Kn&&(t.className+=" mac"),t}var gh=class extends be{constructor(e,t,n,r,s,i,l,a){super(),this._bufferService=n,this._optionsService=l,this._renderService=a,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new sj({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:u=>sp(r.window,u)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new gj(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(s.onProtocolChange(u=>{this._scrollableElement.updateOptions({handleMouseWheel:!(u&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(yt.runAndSubscribe(i.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=i.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register($e(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register($e(()=>this._styleElement.remove())),this._register(yt.runAndSubscribe(i.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${i.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${i.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${i.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(u=>this._handleScroll(u)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};gh=Qe([ie(2,Ft),ie(3,mr),ie(4,_b),ie(5,Si),ie(6,$t),ie(7,gr)],gh);var xh=class extends be{constructor(e,t,n,r,s){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=s,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(i=>this._removeDecoration(i))),this._register($e(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};xh=Qe([ie(1,Ft),ie(2,mr),ie(3,Ql),ie(4,gr)],xh);var vj=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||"full"]&&t<=e.endBufferLine+this._linePadding[n||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},In={full:0,left:0,center:0,right:0},yr={full:0,left:0,center:0,right:0},Bi={full:0,left:0,center:0,right:0},qa=class extends be{constructor(e,t,n,r,s,i,l,a){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=s,this._optionsService=i,this._themeService=l,this._coreBrowserService=a,this._colorZoneStore=new vj,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register($e(()=>this._canvas?.remove()));let c=this._canvas.getContext("2d");if(c)this._ctx=c;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);yr.full=this._canvas.width,yr.left=e,yr.center=t,yr.right=e,this._refreshDrawHeightConstants(),Bi.full=1,Bi.left=1,Bi.center=1+yr.left,Bi.right=1+yr.left+yr.center}_refreshDrawHeightConstants(){In.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);In.left=t,In.center=t,In.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Bi[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-In[e.position||"full"]/2),yr[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+In[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};qa=Qe([ie(2,Ft),ie(3,Ql),ie(4,gr),ie(5,$t),ie(6,Si),ie(7,mr)],qa);var K;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(K||={});var da;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(da||={});var Fb;(e=>e.ST=`${K.ESC}\\`)(Fb||={});var vh=class{constructor(e,t,n,r,s,i){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=s,this._renderService=i,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let n;t.start+=this._dataAlreadySent.length,this._isComposing?n=this._textarea.value.substring(t.start,this._compositionPosition.start):n=this._textarea.value.substring(t.start),n.length>0&&this._coreService.triggerDataEvent(n,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,"");this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};vh=Qe([ie(2,Ft),ie(3,$t),ie(4,Ns),ie(5,gr)],vh);var pt=0,mt=0,gt=0,Ge=0,_g={css:"#00000000",rgba:0},rt;(e=>{function t(s,i,l,a){return a!==void 0?`#${Qr(s)}${Qr(i)}${Qr(l)}${Qr(a)}`:`#${Qr(s)}${Qr(i)}${Qr(l)}`}e.toCss=t;function n(s,i,l,a=255){return(s<<24|i<<16|l<<8|a)>>>0}e.toRgba=n;function r(s,i,l,a){return{css:e.toCss(s,i,l,a),rgba:e.toRgba(s,i,l,a)}}e.toColor=r})(rt||={});var Be;(e=>{function t(c,u){if(Ge=(u.rgba&255)/255,Ge===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,d=u.rgba>>16&255,f=u.rgba>>8&255,p=c.rgba>>24&255,m=c.rgba>>16&255,x=c.rgba>>8&255;pt=p+Math.round((h-p)*Ge),mt=m+Math.round((d-m)*Ge),gt=x+Math.round((f-x)*Ge);let w=rt.toCss(pt,mt,gt),v=rt.toRgba(pt,mt,gt);return{css:w,rgba:v}}e.blend=t;function n(c){return(c.rgba&255)===255}e.isOpaque=n;function r(c,u,h){let d=ha.ensureContrastRatio(c.rgba,u.rgba,h);if(d)return rt.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=r;function s(c){let u=(c.rgba|255)>>>0;return[pt,mt,gt]=ha.toChannels(u),{css:rt.toCss(pt,mt,gt),rgba:u}}e.opaque=s;function i(c,u){return Ge=Math.round(u*255),[pt,mt,gt]=ha.toChannels(c.rgba),{css:rt.toCss(pt,mt,gt,Ge),rgba:rt.toRgba(pt,mt,gt,Ge)}}e.opacity=i;function l(c,u){return Ge=c.rgba&255,i(c,Ge*u/255)}e.multiplyOpacity=l;function a(c){return[c.rgba>>24&255,c.rgba>>16&255,c.rgba>>8&255]}e.toColorRGB=a})(Be||={});var He;(e=>{let t,n;try{let s=document.createElement("canvas");s.width=1,s.height=1;let i=s.getContext("2d",{willReadFrequently:!0});i&&(t=i,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function r(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return pt=parseInt(s.slice(1,2).repeat(2),16),mt=parseInt(s.slice(2,3).repeat(2),16),gt=parseInt(s.slice(3,4).repeat(2),16),rt.toColor(pt,mt,gt);case 5:return pt=parseInt(s.slice(1,2).repeat(2),16),mt=parseInt(s.slice(2,3).repeat(2),16),gt=parseInt(s.slice(3,4).repeat(2),16),Ge=parseInt(s.slice(4,5).repeat(2),16),rt.toColor(pt,mt,gt,Ge);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let i=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(i)return pt=parseInt(i[1]),mt=parseInt(i[2]),gt=parseInt(i[3]),Ge=Math.round((i[5]===void 0?1:parseFloat(i[5]))*255),rt.toColor(pt,mt,gt,Ge);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=s,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[pt,mt,gt,Ge]=t.getImageData(0,0,1,1).data,Ge!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rt.toRgba(pt,mt,gt,Ge),css:s}}e.toColor=r})(He||={});var Rt;(e=>{function t(r){return n(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=t;function n(r,s,i){let l=r/255,a=s/255,c=i/255,u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),h=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);return u*.2126+h*.7152+d*.0722}e.relativeLuminance2=n})(Rt||={});var ha;(e=>{function t(l,a){if(Ge=(a&255)/255,Ge===1)return a;let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=l>>24&255,f=l>>16&255,p=l>>8&255;return pt=d+Math.round((c-d)*Ge),mt=f+Math.round((u-f)*Ge),gt=p+Math.round((h-p)*Ge),rt.toRgba(pt,mt,gt)}e.blend=t;function n(l,a,c){let u=Rt.relativeLuminance(l>>8),h=Rt.relativeLuminance(a>>8);if(Zn(u,h)>8));if(m>8));return m>w?p:x}return p}let d=s(l,a,c),f=Zn(u,Rt.relativeLuminance(d>>8));if(f>8));return f>m?d:p}return d}}e.ensureContrastRatio=n;function r(l,a,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=a>>24&255,p=a>>16&255,m=a>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x0||p>0||m>0);)f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),m-=Math.max(0,Math.ceil(m*.1)),x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));return(f<<24|p<<16|m<<8|255)>>>0}e.reduceLuminance=r;function s(l,a,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=a>>24&255,p=a>>16&255,m=a>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x>>0}e.increaseLuminance=s;function i(l){return[l>>24&255,l>>16&255,l>>8&255,l&255]}e.toChannels=i})(ha||={});function Qr(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Zn(e,t){return e1){let h=this._getJoinedRanges(r,l,i,t,s);for(let d=0;d1){let u=this._getJoinedRanges(r,l,i,t,s);for(let h=0;h=k,G=E,P=this._workCell;if(f.length>0&&E===f[0][0]&&W){let B=f.shift(),he=this._isCellInSelection(B[0],t);for(_=B[0]+1;_=B[1],W?(I=!0,P=new _j(this._workCell,e.translateToString(!0,B[0],B[1]),B[1]-B[0]),G=B[1]-1,O=P.getWidth()):k=B[1]}let z=this._isCellInSelection(E,t),j=n&&E===i,se=R&&E>=u&&E<=h,q=!1;this._decorationService.forEachDecorationAtCell(E,t,void 0,B=>{q=!0});let T=P.getChars()||Dr;if(T===" "&&(P.isUnderline()||P.isOverline())&&(T=" "),A=O*a-c.get(T,P.isBold(),P.isItalic()),!x)x=this._document.createElement("span");else if(w&&(z&&L||!z&&!L&&P.bg===y)&&(z&&L&&p.selectionForeground||P.fg===b)&&P.extended.ext===C&&se===S&&A===N&&!j&&!I&&!q&&W){P.isInvisible()?v+=Dr:v+=T,w++;continue}else w&&(x.textContent=v),x=this._document.createElement("span"),w=0,v="";if(y=P.bg,b=P.fg,C=P.extended.ext,S=se,N=A,L=z,I&&i>=E&&i<=G&&(i=E),!this._coreService.isCursorHidden&&j&&this._coreService.isCursorInitialized){if(D.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&D.push("xterm-cursor-blink"),D.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(s)switch(s){case"outline":D.push("xterm-cursor-outline");break;case"block":D.push("xterm-cursor-block");break;case"bar":D.push("xterm-cursor-bar");break;case"underline":D.push("xterm-cursor-underline");break}}if(P.isBold()&&D.push("xterm-bold"),P.isItalic()&&D.push("xterm-italic"),P.isDim()&&D.push("xterm-dim"),P.isInvisible()?v=Dr:v=P.getChars()||Dr,P.isUnderline()&&(D.push(`xterm-underline-${P.extended.underlineStyle}`),v===" "&&(v=" "),!P.isUnderlineColorDefault()))if(P.isUnderlineColorRGB())x.style.textDecorationColor=`rgb(${Xl.toColorRGB(P.getUnderlineColor()).join(",")})`;else{let B=P.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&P.isBold()&&B<8&&(B+=8),x.style.textDecorationColor=p.ansi[B].css}P.isOverline()&&(D.push("xterm-overline"),v===" "&&(v=" ")),P.isStrikethrough()&&D.push("xterm-strikethrough"),se&&(x.style.textDecoration="underline");let re=P.getFgColor(),ee=P.getFgColorMode(),Q=P.getBgColor(),V=P.getBgColorMode(),Y=!!P.isInverse();if(Y){let B=re;re=Q,Q=B;let he=ee;ee=V,V=he}let oe,pe,Pe=!1;this._decorationService.forEachDecorationAtCell(E,t,void 0,B=>{B.options.layer!=="top"&&Pe||(B.backgroundColorRGB&&(V=50331648,Q=B.backgroundColorRGB.rgba>>8&16777215,oe=B.backgroundColorRGB),B.foregroundColorRGB&&(ee=50331648,re=B.foregroundColorRGB.rgba>>8&16777215,pe=B.foregroundColorRGB),Pe=B.options.layer==="top")}),!Pe&&z&&(oe=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,Q=oe.rgba>>8&16777215,V=50331648,Pe=!0,p.selectionForeground&&(ee=50331648,re=p.selectionForeground.rgba>>8&16777215,pe=p.selectionForeground)),Pe&&D.push("xterm-decoration-top");let $;switch(V){case 16777216:case 33554432:$=p.ansi[Q],D.push(`xterm-bg-${Q}`);break;case 50331648:$=rt.toColor(Q>>16,Q>>8&255,Q&255),this._addStyle(x,`background-color:#${yg((Q>>>0).toString(16),"0",6)}`);break;case 0:default:Y?($=p.foreground,D.push("xterm-bg-257")):$=p.background}switch(oe||P.isDim()&&(oe=Be.multiplyOpacity($,.5)),ee){case 16777216:case 33554432:P.isBold()&&re<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(re+=8),this._applyMinimumContrast(x,$,p.ansi[re],P,oe,void 0)||D.push(`xterm-fg-${re}`);break;case 50331648:let B=rt.toColor(re>>16&255,re>>8&255,re&255);this._applyMinimumContrast(x,$,B,P,oe,pe)||this._addStyle(x,`color:#${yg(re.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(x,$,p.foreground,P,oe,pe)||Y&&D.push("xterm-fg-257")}D.length&&(x.className=D.join(" "),D.length=0),!j&&!I&&!q&&W?w++:x.textContent=v,A!==this.defaultSpacing&&(x.style.letterSpacing=`${A}px`),d.push(x),E=G}return x&&w&&(x.textContent=v),d}_applyMinimumContrast(e,t,n,r,s,i){if(this._optionsService.rawOptions.minimumContrastRatio===1||wj(r.getCode()))return!1;let l=this._getContrastCache(r),a;if(!s&&!i&&(a=l.getColor(t.rgba,n.rgba)),a===void 0){let c=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);a=Be.ensureContrastRatio(s||t,i||n,c),l.setColor((s||t).rgba,(i||n).rgba,a??null)}return a?(this._addStyle(e,`color:${a.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};_h=Qe([ie(1,wb),ie(2,$t),ie(3,mr),ie(4,Ns),ie(5,Ql),ie(6,Si)],_h);function yg(e,t,n){for(;e.length0&&(this._flat[r]=l),l}let s=e;t&&(s+="B"),n&&(s+="I");let i=this._holey.get(s);if(i===void 0){let l=0;t&&(l|=1),n&&(l|=2),i=this._measure(e,l),i>0&&this._holey.set(s,i)}return i}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Cj=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let s=e.buffers.active.ydisp,i=t[1]-s,l=n[1]-s,a=Math.max(i,0),c=Math.min(l,e.rows-1);if(a>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=i,this.viewportEndRow=l,this.viewportCappedStartRow=a,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function jj(){return new Cj}var fu="xterm-dom-renderer-owner-",dn="xterm-rows",Eo="xterm-fg-",bg="xterm-bg-",zi="xterm-focus",Po="xterm-selection",Nj=1,yh=class extends be{constructor(e,t,n,r,s,i,l,a,c,u,h,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=s,this._helperContainer=i,this._linkifier2=l,this._charSizeService=c,this._optionsService=u,this._bufferService=h,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Nj++,this._rowElements=[],this._selectionRenderModel=jj(),this.onRequestRedraw=this._register(new ne).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(dn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Po),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=Sj(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(m=>this._injectCss(m))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(_h,document),this._element.classList.add(fu+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(m=>this._handleLinkHover(m))),this._register(this._linkifier2.onHideLinkUnderline(m=>this._handleLinkLeave(m))),this._register($e(()=>{this._element.classList.remove(fu+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new kj(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let n of this._rowElements)n.style.width=`${this.dimensions.css.canvas.width}px`,n.style.height=`${this.dimensions.css.cell.height}px`,n.style.lineHeight=`${this.dimensions.css.cell.height}px`,n.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${dn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${dn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${dn} .xterm-dim { color: ${Be.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,s=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${s} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Po} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Po} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Po} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[i,l]of e.ansi.entries())t+=`${this._terminalSelector} .${Eo}${i} { color: ${l.css}; }${this._terminalSelector} .${Eo}${i}.xterm-dim { color: ${Be.multiplyOpacity(l,.5).css}; }${this._terminalSelector} .${bg}${i} { background-color: ${l.css}; }`;t+=`${this._terminalSelector} .${Eo}257 { color: ${Be.opaque(e.background).css}; }${this._terminalSelector} .${Eo}257.xterm-dim { color: ${Be.multiplyOpacity(Be.opaque(e.background),.5).css}; }${this._terminalSelector} .${bg}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let n=this._rowElements.length;n<=t;n++){let r=this._document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(zi),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(zi),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,s=this._selectionRenderModel.viewportEndRow,i=this._selectionRenderModel.viewportCappedStartRow,l=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(n){let c=e[0]>t[0];a.appendChild(this._createSelectionElement(i,c?t[0]:e[0],c?e[0]:t[0],l-i+1))}else{let c=r===i?e[0]:0,u=i===s?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(i,c,u));let h=l-i-1;if(a.appendChild(this._createSelectionElement(i+1,0,this._bufferService.cols,h)),i!==l){let d=s===l?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(l,0,d))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,n,r=1){let s=this._document.createElement("div"),i=t*this.dimensions.css.cell.width,l=this.dimensions.css.cell.width*(n-t);return i+l>this.dimensions.css.canvas.width&&(l=this.dimensions.css.canvas.width-i),s.style.height=`${r*this.dimensions.css.cell.height}px`,s.style.top=`${e*this.dimensions.css.cell.height}px`,s.style.left=`${i}px`,s.style.width=`${l}px`,s}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,s=Math.min(n.x,this._bufferService.cols-1),i=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,l=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let u=c+n.ydisp,h=this._rowElements[c],d=n.lines.get(u);if(!h||!d)break;h.replaceChildren(...this._rowFactory.createRow(d,u,u===r,l,a,s,i,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${fu}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,s,i){n<0&&(e=0),r<0&&(t=0);let l=this._bufferService.rows-1;n=Math.max(Math.min(n,l),0),r=Math.max(Math.min(r,l),0),s=Math.min(s,this._bufferService.cols);let a=this._bufferService.buffer,c=a.ybase+a.y,u=Math.min(a.x,s-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=n;p<=r;++p){let m=p+a.ydisp,x=this._rowElements[p],w=a.lines.get(m);if(!x||!w)break;x.replaceChildren(...this._rowFactory.createRow(w,m,m===c,d,f,u,h,this.dimensions.css.cell.width,this._widthCache,i?p===n?e:0:-1,i?(p===r?t:s)-1:-1))}}};yh=Qe([ie(7,Jf),ie(8,Sc),ie(9,$t),ie(10,Ft),ie(11,Ns),ie(12,mr),ie(13,Si)],yh);var bh=class extends be{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ne),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Pj(this._optionsService))}catch{this._measureStrategy=this._register(new Ej(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};bh=Qe([ie(2,$t)],bh);var $b=class extends be{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},Ej=class extends $b{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Pj=class extends $b{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Aj=class extends be{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Tj(this._window)),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ne),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(r=>this._screenDprMonitor.setWindow(r))),this._register(yt.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(me(this._textarea,"focus",()=>this._isFocused=!0)),this._register(me(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Tj=class extends be{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new xi),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register($e(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=me(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Lj=class extends be{constructor(){super(),this.linkProviders=[],this._register($e(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function lp(e,t,n){let r=n.getBoundingClientRect(),s=e.getComputedStyle(n),i=parseInt(s.getPropertyValue("padding-left")),l=parseInt(s.getPropertyValue("padding-top"));return[t.clientX-r.left-i,t.clientY-r.top-l]}function Dj(e,t,n,r,s,i,l,a,c){if(!i)return;let u=lp(e,t,n);if(u)return u[0]=Math.ceil((u[0]+(c?l/2:0))/l),u[1]=Math.ceil(u[1]/a),u[0]=Math.min(Math.max(u[0],1),r+(c?1:0)),u[1]=Math.min(Math.max(u[1],1),s),u}var wh=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,s){return Dj(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(e,t){let n=lp(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};wh=Qe([ie(0,gr),ie(1,Sc)],wh);var Rj=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Wb={};U1(Wb,{getSafariVersion:()=>Ij,isChromeOS:()=>Vb,isFirefox:()=>Hb,isIpad:()=>Oj,isIphone:()=>Bj,isLegacyEdge:()=>Mj,isLinux:()=>op,isMac:()=>Ka,isNode:()=>kc,isSafari:()=>Ub,isWindows:()=>qb});var kc=typeof process<"u"&&"title"in process,Jl=kc?"node":navigator.userAgent,Zl=kc?"node":navigator.platform,Hb=Jl.includes("Firefox"),Mj=Jl.includes("Edge"),Ub=/^((?!chrome|android).)*safari/i.test(Jl);function Ij(){if(!Ub)return 0;let e=Jl.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Ka=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zl),Oj=Zl==="iPad",Bj=Zl==="iPhone",qb=["Windows","Win16","Win32","WinCE"].includes(Zl),op=Zl.indexOf("Linux")>=0,Vb=/\bCrOS\b/.test(Jl),Kb=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._is){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=s}this.clear()}},zj=class extends Kb{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Fj=class extends Kb{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ga=!kc&&"requestIdleCallback"in window?Fj:zj,$j=class{constructor(){this._queue=new Ga}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Sh=class extends be{constructor(e,t,n,r,s,i,l,a,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=s,this._coreBrowserService=a,this._renderer=this._register(new xi),this._pausedResizeTask=new $j,this._observerDisposable=this._register(new xi),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ne),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ne),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ne),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Rj((u,h)=>this._renderRows(u,h),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Wj(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register($e(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(l.onResize(()=>this._fullRefresh())),this._register(l.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(i.onDecorationRegistered(()=>this._fullRefresh())),this._register(i.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(l.cols,l.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(l.buffer.y,l.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(u=>this._registerIntersectionObserver(u,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let n=new e.IntersectionObserver(r=>this._handleIntersectionChange(r[r.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=$e(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Sh=Qe([ie(2,$t),ie(3,Sc),ie(4,Ns),ie(5,Ql),ie(6,Ft),ie(7,mr),ie(8,Si)],Sh);var Wj=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Hj(e,t,n,r){let s=n.buffer.x,i=n.buffer.y;if(!n.buffer.hasScrollback)return Vj(s,i,e,t,n,r)+Cc(i,t,n,r)+Kj(s,i,e,t,n,r);let l;if(i===t)return l=s>e?"D":"C",Fl(Math.abs(s-e),zl(l,r));l=i>t?"D":"C";let a=Math.abs(i-t),c=qj(i>t?e:s,n)+(a-1)*n.cols+1+Uj(i>t?s:e);return Fl(c,zl(l,r))}function Uj(e,t){return e-1}function qj(e,t){return t.cols-e}function Vj(e,t,n,r,s,i){return Cc(t,r,s,i).length===0?"":Fl(Yb(e,t,e,t-Ss(t,s),!1,s).length,zl("D",i))}function Cc(e,t,n,r){let s=e-Ss(e,n),i=t-Ss(t,n),l=Math.abs(s-i)-Gj(e,t,n);return Fl(l,zl(Gb(e,t),r))}function Kj(e,t,n,r,s,i){let l;Cc(t,r,s,i).length>0?l=r-Ss(r,s):l=t;let a=r,c=Yj(e,t,n,r,s,i);return Fl(Yb(e,l,n,a,c==="C",s).length,zl(c,i))}function Gj(e,t,n){let r=0,s=e-Ss(e,n),i=t-Ss(t,n);for(let l=0;l=0&&e0?l=r-Ss(r,s):l=t,e=n&&lt?"A":"B"}function Yb(e,t,n,r,s,i){let l=e,a=t,c="";for(;(l!==n||a!==r)&&a>=0&&ai.cols-1?(c+=i.buffer.translateBufferLineToString(a,!1,e,l),l=0,e=0,a++):!s&&l<0&&(c+=i.buffer.translateBufferLineToString(a,!1,0,e+1),l=i.cols-1,e=l,a--);return c+i.buffer.translateBufferLineToString(a,!1,e,l)}function zl(e,t){let n=t?"O":"[";return K.ESC+n+e}function Fl(e,t){e=Math.floor(e);let n="";for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function wg(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var pu=50,Qj=15,Jj=50,Zj=500,eN=" ",tN=new RegExp(eN,"g"),kh=class extends be{constructor(e,t,n,r,s,i,l,a,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=s,this._mouseService=i,this._optionsService=l,this._renderService=a,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new yn,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ne),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ne),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=u=>this._handleMouseMove(u),this._mouseUpListener=u=>this._handleMouseUp(u),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(u=>this._handleTrim(u)),this._register(this._bufferService.buffers.onBufferActivate(u=>this._handleBufferActivate(u))),this.enable(),this._model=new Xj(this._bufferService),this._activeSelectionMode=0,this._register($e(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(u=>{u.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let s=e[0]s.replace(tN," ")).join(qb?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),op&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=wg(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=lp(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-pu),pu),t/=pu,t/Math.abs(t)+Math.round(t*(Qj-1)))}shouldForceSelection(e){return Ka?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Jj)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Ka&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let s=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:s>1&&t!==r&&(n+=s-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let s=this._bufferService.buffer,i=s.lines.get(e[1]);if(!i)return;let l=s.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(i,e[0]),c=a,u=e[0]-a,h=0,d=0,f=0,p=0;if(l.charAt(a)===" "){for(;a>0&&l.charAt(a-1)===" ";)a--;for(;c1&&(p+=_-1,c+=_-1);w>0&&a>0&&!this._isCharWordSeparator(i.loadCell(w-1,this._workCell));){i.loadCell(w-1,this._workCell);let y=this._workCell.getChars().length;this._workCell.getWidth()===0?(h++,w--):y>1&&(f+=y-1,a-=y-1),a--,w--}for(;v1&&(p+=y-1,c+=y-1),c++,v++}}c++;let m=a+u-h+f,x=Math.min(this._bufferService.cols,c-a+h+d-f-p);if(!(!t&&l.slice(a,c).trim()==="")){if(n&&m===0&&i.getCodePoint(0)!==32){let w=s.lines.get(e[1]-1);if(w&&i.isWrapped&&w.getCodePoint(this._bufferService.cols-1)!==32){let v=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(v){let _=this._bufferService.cols-v.start;m-=_,x+=_}}}if(r&&m+x===this._bufferService.cols&&i.getCodePoint(this._bufferService.cols-1)!==32){let w=s.lines.get(e[1]+1);if(w?.isWrapped&&w.getCodePoint(0)!==32){let v=this._getWordAt([0,e[1]+1],!1,!1,!0);v&&(x+=v.length)}}return{start:m,length:x}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=wg(n,this._bufferService.cols)}};kh=Qe([ie(3,Ft),ie(4,Ns),ie(5,Zf),ie(6,$t),ie(7,gr),ie(8,mr)],kh);var Sg=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},kg=class{constructor(){this._color=new Sg,this._css=new Sg}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},it=Object.freeze((()=>{let e=[He.toColor("#2e3436"),He.toColor("#cc0000"),He.toColor("#4e9a06"),He.toColor("#c4a000"),He.toColor("#3465a4"),He.toColor("#75507b"),He.toColor("#06989a"),He.toColor("#d3d7cf"),He.toColor("#555753"),He.toColor("#ef2929"),He.toColor("#8ae234"),He.toColor("#fce94f"),He.toColor("#729fcf"),He.toColor("#ad7fa8"),He.toColor("#34e2e2"),He.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],s=t[n/6%6|0],i=t[n%6];e.push({css:rt.toCss(r,s,i),rgba:rt.toRgba(r,s,i)})}for(let n=0;n<24;n++){let r=8+n*10;e.push({css:rt.toCss(r,r,r),rgba:rt.toRgba(r,r,r)})}return e})()),ss=He.toColor("#ffffff"),il=He.toColor("#000000"),Cg=He.toColor("#ffffff"),jg=il,Fi={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},nN=ss,Ch=class extends be{constructor(e){super(),this._optionsService=e,this._contrastCache=new kg,this._halfContrastCache=new kg,this._onChangeColors=this._register(new ne),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ss,background:il,cursor:Cg,cursorAccent:jg,selectionForeground:void 0,selectionBackgroundTransparent:Fi,selectionBackgroundOpaque:Be.blend(il,Fi),selectionInactiveBackgroundTransparent:Fi,selectionInactiveBackgroundOpaque:Be.blend(il,Fi),scrollbarSliderBackground:Be.opacity(ss,.2),scrollbarSliderHoverBackground:Be.opacity(ss,.4),scrollbarSliderActiveBackground:Be.opacity(ss,.5),overviewRulerBorder:ss,ansi:it.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Te(e.foreground,ss),t.background=Te(e.background,il),t.cursor=Be.blend(t.background,Te(e.cursor,Cg)),t.cursorAccent=Be.blend(t.background,Te(e.cursorAccent,jg)),t.selectionBackgroundTransparent=Te(e.selectionBackground,Fi),t.selectionBackgroundOpaque=Be.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Te(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Be.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Te(e.selectionForeground,_g):void 0,t.selectionForeground===_g&&(t.selectionForeground=void 0),Be.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Be.opacity(t.selectionBackgroundTransparent,.3)),Be.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Be.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Te(e.scrollbarSliderBackground,Be.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Te(e.scrollbarSliderHoverBackground,Be.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Te(e.scrollbarSliderActiveBackground,Be.opacity(t.foreground,.5)),t.overviewRulerBorder=Te(e.overviewRulerBorder,nN),t.ansi=it.slice(),t.ansi[0]=Te(e.black,it[0]),t.ansi[1]=Te(e.red,it[1]),t.ansi[2]=Te(e.green,it[2]),t.ansi[3]=Te(e.yellow,it[3]),t.ansi[4]=Te(e.blue,it[4]),t.ansi[5]=Te(e.magenta,it[5]),t.ansi[6]=Te(e.cyan,it[6]),t.ansi[7]=Te(e.white,it[7]),t.ansi[8]=Te(e.brightBlack,it[8]),t.ansi[9]=Te(e.brightRed,it[9]),t.ansi[10]=Te(e.brightGreen,it[10]),t.ansi[11]=Te(e.brightYellow,it[11]),t.ansi[12]=Te(e.brightBlue,it[12]),t.ansi[13]=Te(e.brightMagenta,it[13]),t.ansi[14]=Te(e.brightCyan,it[14]),t.ansi[15]=Te(e.brightWhite,it[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;ri.index-l.index),r=[];for(let i of n){let l=this._services.get(i.id);if(!l)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${i.id._id}.`);r.push(l)}let s=n.length>0?n[0].index:t.length;if(t.length!==s)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${s+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},iN={trace:0,debug:1,info:2,warn:3,error:4,off:5},lN="xterm.js: ",jh=class extends be{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=iN[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;r--)this._array[this._getCyclicIndex(r+n.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;rthis._maxLength){let r=this._length+n.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+n<0)throw new Error("Cannot shift elements in list beyond index 0");if(n>0){for(let s=t-1;s>=0;s--)this.set(e+s+n,this.get(e+s));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r]}set(t,n){this._data[t*ye+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*ye+0]=t|2097152|n[2]<<22):this._data[t*ye+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*ye+0]>>22}hasWidth(t){return this._data[t*ye+0]&12582912}getFg(t){return this._data[t*ye+1]}getBg(t){return this._data[t*ye+2]}hasContent(t){return this._data[t*ye+0]&4194303}getCodePoint(t){let n=this._data[t*ye+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*ye+0]&2097152}getString(t){let n=this._data[t*ye+0];return n&2097152?this._combined[t]:n&2097151?jr(n&2097151):""}isProtected(t){return this._data[t*ye+2]&536870912}loadCell(t,n){return Ao=t*ye,n.content=this._data[Ao+0],n.fg=this._data[Ao+1],n.bg=this._data[Ao+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*ye+0]=n.content,this._data[t*ye+1]=n.fg,this._data[t*ye+2]=n.bg}setCellFromCodepoint(t,n,r,s){s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*ye+0]=n|r<<22,this._data[t*ye+1]=s.fg,this._data[t*ye+2]=s.bg}addCodepointToCell(t,n,r){let s=this._data[t*ye+0];s&2097152?this._combined[t]+=jr(n):s&2097151?(this._combined[t]=jr(s&2097151)+jr(n),s&=-2097152,s|=2097152):s=n|1<<22,r&&(s&=-12582913,s|=r<<22),this._data[t*ye+0]=s}insertCells(t,n,r){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,r),n=0;--i)this.setCell(t+n+i,this.loadCell(t+i,s));for(let i=0;ithis.length){if(this._data.buffer.byteLength>=r*4)this._data=new Uint32Array(this._data.buffer,0,r);else{let s=new Uint32Array(r);s.set(this._data),this._data=s}for(let s=this.length;s=t&&delete this._combined[a]}let i=Object.keys(this._extendedAttrs);for(let l=0;l=t&&delete this._extendedAttrs[a]}}return this.length=t,r*4*mu=0;--t)if(this._data[t*ye+0]&4194303)return t+(this._data[t*ye+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ye+0]&4194303||this._data[t*ye+2]&50331648)return t+(this._data[t*ye+0]>>22);return 0}copyCellsFrom(t,n,r,s,i){let l=t._data;if(i)for(let c=s-1;c>=0;c--){for(let u=0;u=n&&(this._combined[u-n+r]=t._combined[u])}}translateToString(t,n,r,s){n=n??0,r=r??this.length,t&&(r=Math.min(r,this.getTrimmedLength())),s&&(s.length=0);let i="";for(;n>22||1}return s&&s.push(n),i}};function oN(e,t,n,r,s,i){let l=[];for(let a=0;a=a&&r0&&(w>d||h[w].getTrimmedLength()===0);w--)x++;x>0&&(l.push(a+h.length-x),l.push(x)),a+=h.length-1}return l}function aN(e,t){let n=[],r=0,s=t[r],i=0;for(let l=0;l$l(e,u,t)).reduce((c,u)=>c+u),i=0,l=0,a=0;for(;ac&&(i-=c,l++);let u=e[l].getWidth(i-1)===2;u&&i--;let h=u?n-1:n;r.push(h),a+=h}return r}function $l(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,s=e[t+1].getWidth(0)===2;return r&&s?n-1:n}var Qb=class Jb{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Jb._nextId++,this._onDispose=this.register(new ne),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ws(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Qb._nextId=1;var dN=Qb,ut={},is=ut.B;ut[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ut.A={"#":"£"};ut.B=void 0;ut[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ut.C=ut[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ut.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ut.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ut.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ut.E=ut[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ut.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ut.H=ut[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Eg=4294967295,Pg=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=nt.clone(),this.savedCharset=is,this.markers=[],this._nullCell=yn.fromCharData([0,mb,1,0]),this._whitespaceCell=yn.fromCharData([0,Dr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ga,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Ng(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Ua),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Ua),this._whitespaceCell}getBlankLine(e,t){return new ll(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eEg?Eg:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=nt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Ng(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(nt),r=0,s=this._getCorrectBufferLength(t);if(s>this.lines.maxLength&&(this.lines.maxLength=s),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+i+1?(this.ybase--,i++,this.ydisp>0&&this.ydisp--):this.lines.push(new ll(e,n)));else for(let l=this._rows;l>t;l--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(s0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=s}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),i&&(this.y+=i),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let i=0;i.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=oN(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(nt),n);if(r.length>0){let s=aN(this.lines,r);cN(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(nt),s=n;for(;s-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let a=this.lines.get(l);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let c=[a];for(;a.isWrapped&&l>0;)a=this.lines.get(--l),c.unshift(a);if(!n){let y=this.ybase+this.y;if(y>=l&&y0&&(s.push({start:l+c.length+i,newLines:p}),i+=p.length),c.push(...p);let m=h.length-1,x=h[m];x===0&&(m--,x=h[m]);let w=c.length-d-1,v=u;for(;w>=0;){let y=Math.min(v,x);if(c[m]===void 0)break;if(c[m].copyCellsFrom(c[w],v-y,x-y,y,!0),x-=y,x===0&&(m--,x=h[m]),v-=y,v===0){w--;let b=Math.max(w,0);v=$l(c,b,this._cols)}}for(let y=0;y0;)this.ybase===0?this.y0){let l=[],a=[];for(let x=0;x=0;x--)if(d&&d.start>u+f){for(let w=d.newLines.length-1;w>=0;w--)this.lines.set(x--,d.newLines[w]);x++,l.push({index:u+1,amount:d.newLines.length}),f+=d.newLines.length,d=s[++h]}else this.lines.set(x,a[u--]);let p=0;for(let x=l.length-1;x>=0;x--)l[x].index+=p,this.lines.onInsertEmitter.fire(l[x]),p+=l[x].amount;let m=Math.max(0,c+i-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(e,t,n=0,r){let s=this.lines.get(e);return s?s.translateToString(t,n,r):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.linen.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},hN=class extends be{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ne),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Pg(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Pg(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Zb=2,ew=1,Nh=class extends be{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Zb),this.rows=Math.max(e.rawOptions.rows||0,ew),this.buffers=this._register(new hN(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let s=n.ybase+n.scrollTop,i=n.ybase+n.scrollBottom;if(n.scrollTop===0){let l=n.lines.isFull;i===n.lines.length-1?l?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(i+1,0,r.clone()),l?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let l=i-s+1;n.lines.shiftElements(s+1,l-1,-1),n.lines.set(i,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Nh=Qe([ie(0,$t)],Nh);var Ds={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Ka,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},fN=["normal","bold","100","200","300","400","500","600","700","800","900"],pN=class extends be{constructor(e){super(),this._onOptionChange=this._register(new ne),this.onOptionChange=this._onOptionChange.event;let t={...Ds};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(r){console.error(r)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register($e(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=n=>{if(!(n in Ds))throw new Error(`No option with key "${n}"`);return this.rawOptions[n]},t=(n,r)=>{if(!(n in Ds))throw new Error(`No option with key "${n}"`);r=this._sanitizeAndValidateOption(n,r),this.rawOptions[n]!==r&&(this.rawOptions[n]=r,this._onOptionChange.fire(n))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ds[e]),!mN(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ds[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=fN.includes(t)?t:Ds[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function mN(e){return e==="block"||e==="underline"||e==="bar"}function ol(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&ol(e[r],t-1);return n}var Ag=Object.freeze({insertMode:!1}),Tg=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Eh=class extends be{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ne),this.onData=this._onData.event,this._onUserInput=this._register(new ne),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ne),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=ol(Ag),this.decPrivateModes=ol(Tg)}reset(){this.modes=ol(Ag),this.decPrivateModes=ol(Tg)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(r=>r.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};Eh=Qe([ie(0,Ft),ie(1,yb),ie(2,$t)],Eh);var Lg={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function gu(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var xu=String.fromCharCode,Dg={DEFAULT:e=>{let t=[gu(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${xu(t[0])}${xu(t[1])}${xu(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${gu(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${gu(e,!0)};${e.x};${e.y}${t}`}},Ph=class extends be{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ne),this.onProtocolChange=this._onProtocolChange.event;for(let r of Object.keys(Lg))this.addProtocol(r,Lg[r]);for(let r of Object.keys(Dg))this.addEncoding(r,Dg[r]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,s=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(s/=r+0,Math.abs(e.deltaY)<50&&(s*=.3),this._wheelPartialScroll+=s,s=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(s*=this._bufferService.rows),s}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Ph=Qe([ie(0,Ft),ie(1,Ns),ie(2,$t)],Ph);var vu=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],gN=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],lt;function xN(e,t){let n=0,r=t.length-1,s;if(et[r][1])return!1;for(;r>=n;)if(s=n+r>>1,e>t[s][1])n=s+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let s=ds.extractWidth(t);s===0?r=!1:s>n&&(n=s)}return ds.createPropertyValue(0,n,r)}},ds=class fa{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ne,this.onChange=this._onChange.event;let t=new vN;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,r=!1){return(t&16777215)<<3|(n&3)<<1|(r?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,r=0,s=t.length;for(let i=0;i=s)return n+this.wcwidth(l);let u=t.charCodeAt(i);56320<=u&&u<=57343?l=(l-55296)*1024+u-56320+65536:n+=this.wcwidth(u)}let a=this.charProperties(l,r),c=fa.extractWidth(a);fa.extractShouldJoin(a)&&(c-=fa.extractWidth(r)),n+=c,r=a}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},_N=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Rg(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var $i=2147483647,yN=256,tw=class Ah{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>yN)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new Ah;if(!t.length)return n;for(let r=Array.isArray(t[0])?1:0;r>8,s=this._subParamsIdx[n]&255;s-r>0&&t.push(Array.prototype.slice.call(this._subParams,r,s))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>$i?$i:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>$i?$i:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;return r-n>0?this._subParams.subarray(n,r):null}getSubParamsAll(){let t={};for(let n=0;n>8,s=this._subParamsIdx[n]&255;s-r>0&&(t[n]=this._subParams.slice(r,s))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,s=r[n-1];r[n-1]=~s?Math.min(s*10+t,$i):t}},Wi=[],bN=class{constructor(){this._state=0,this._active=Wi,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Wi}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Wi,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Wi,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,"PUT",wc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let n=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Wi,this._id=-1,this._state=0}}},en=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=wc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(n=>(this._data="",this._hitLimit=!1,n));return this._data="",this._hitLimit=!1,t}},Hi=[],wN=class{constructor(){this._handlers=Object.create(null),this._active=Hi,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Hi}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Hi,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Hi,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let n=this._active.length-1;n>=0;n--)this._active[n].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,"PUT",wc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let n=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Hi,this._ident=0}},al=new tw;al.addParam(0);var Mg=class{constructor(e){this._handler=e,this._data="",this._params=al,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():al,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=wc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=al,this._data="",this._hitLimit=!1,n));return this._params=al,this._data="",this._hitLimit=!1,t}},SN=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let s=0;sc),n=(a,c)=>t.slice(a,c),r=n(32,127),s=n(0,24);s.push(25),s.push.apply(s,n(28,32));let i=n(0,14),l;e.setDefault(1,0),e.addMany(r,0,2,0);for(l in i)e.addMany([24,26,153,154],l,3,0),e.addMany(n(128,144),l,3,0),e.addMany(n(144,152),l,3,0),e.add(156,l,0,0),e.add(27,l,11,1),e.add(157,l,4,8),e.addMany([152,158,159],l,0,7),e.add(155,l,11,3),e.add(144,l,11,9);return e.addMany(s,0,3,0),e.addMany(s,1,3,1),e.add(127,1,0,1),e.addMany(s,8,0,8),e.addMany(s,3,3,3),e.add(127,3,0,3),e.addMany(s,4,3,4),e.add(127,4,0,4),e.addMany(s,6,3,6),e.addMany(s,5,3,5),e.add(127,5,0,5),e.addMany(s,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(s,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(s,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(s,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(s,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(s,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(s,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(pn,0,2,0),e.add(pn,8,5,8),e.add(pn,6,0,6),e.add(pn,11,0,11),e.add(pn,13,13,13),e}(),CN=class extends be{constructor(e=kN){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new tw,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,n,r)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,n)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register($e(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new bN),this._dcsParser=this._register(new wN),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let s=0;si||i>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");n<<=8,n|=i}}if(e.final.length!==1)throw new Error("final must be a single byte");let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,s){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=s}parse(e,t,n){let r=0,s=0,i=0,l;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,i=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let a=this._parseStack.handlers,c=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&c>-1){for(;c>=0&&(l=a[c](this._params),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 4:if(n===!1&&c>-1){for(;c>=0&&(l=a[c](),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],l=this._dcsParser.unhook(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],l=this._oscParser.end(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,i=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=i;a>4){case 2:for(let f=a+1;;++f){if(f>=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=0&&(l=c[u](this._params),l!==!0);u--)if(l instanceof Promise)return this._preserveStack(3,c,u,s,a),l;u<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++a47&&r<60);a--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let h=this._escHandlers[this._collect<<8|r],d=h?h.length-1:-1;for(;d>=0&&(l=h[d](),l!==!0);d--)if(l instanceof Promise)return this._preserveStack(4,h,d,s,a),l;d<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let f=a+1;;++f)if(f>=t||(r=e[f])===24||r===26||r===27||r>127&&r=t||(r=e[f])<32||r>127&&r>4:i>>8}return r}}function _u(e,t){let n=e.toString(16),r=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function EN(e,t=16){let[n,r,s]=e;return`rgb:${_u(n,t)}/${_u(r,t)}/${_u(s,t)}`}var PN={"(":0,")":1,"*":2,"+":3,"-":1,".":2},br=131072,Og=10;function Bg(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var zg=5e3,Fg=0,AN=class extends be{constructor(e,t,n,r,s,i,l,a,c=new CN){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=s,this._oscLinkService=i,this._coreMouseService=l,this._unicodeService=a,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Y1,this._utf8Decoder=new X1,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone(),this._onRequestBell=this._register(new ne),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ne),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ne),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ne),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ne),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ne),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ne),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ne),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ne),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Th(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,h)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:h.toArray()})}),this._parser.setEscHandlerFallback(u=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(u)})}),this._parser.setExecuteHandlerFallback(u=>{this._logService.debug("Unknown EXECUTE code: ",{code:u})}),this._parser.setOscHandlerFallback((u,h,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:h,data:d})}),this._parser.setDcsHandlerFallback((u,h,d)=>{h==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:h,payload:d})}),this._parser.setPrintHandler((u,h,d)=>this.print(u,h,d)),this._parser.registerCsiHandler({final:"@"},u=>this.insertChars(u)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},u=>this.scrollLeft(u)),this._parser.registerCsiHandler({final:"A"},u=>this.cursorUp(u)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},u=>this.scrollRight(u)),this._parser.registerCsiHandler({final:"B"},u=>this.cursorDown(u)),this._parser.registerCsiHandler({final:"C"},u=>this.cursorForward(u)),this._parser.registerCsiHandler({final:"D"},u=>this.cursorBackward(u)),this._parser.registerCsiHandler({final:"E"},u=>this.cursorNextLine(u)),this._parser.registerCsiHandler({final:"F"},u=>this.cursorPrecedingLine(u)),this._parser.registerCsiHandler({final:"G"},u=>this.cursorCharAbsolute(u)),this._parser.registerCsiHandler({final:"H"},u=>this.cursorPosition(u)),this._parser.registerCsiHandler({final:"I"},u=>this.cursorForwardTab(u)),this._parser.registerCsiHandler({final:"J"},u=>this.eraseInDisplay(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},u=>this.eraseInDisplay(u,!0)),this._parser.registerCsiHandler({final:"K"},u=>this.eraseInLine(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},u=>this.eraseInLine(u,!0)),this._parser.registerCsiHandler({final:"L"},u=>this.insertLines(u)),this._parser.registerCsiHandler({final:"M"},u=>this.deleteLines(u)),this._parser.registerCsiHandler({final:"P"},u=>this.deleteChars(u)),this._parser.registerCsiHandler({final:"S"},u=>this.scrollUp(u)),this._parser.registerCsiHandler({final:"T"},u=>this.scrollDown(u)),this._parser.registerCsiHandler({final:"X"},u=>this.eraseChars(u)),this._parser.registerCsiHandler({final:"Z"},u=>this.cursorBackwardTab(u)),this._parser.registerCsiHandler({final:"`"},u=>this.charPosAbsolute(u)),this._parser.registerCsiHandler({final:"a"},u=>this.hPositionRelative(u)),this._parser.registerCsiHandler({final:"b"},u=>this.repeatPrecedingCharacter(u)),this._parser.registerCsiHandler({final:"c"},u=>this.sendDeviceAttributesPrimary(u)),this._parser.registerCsiHandler({prefix:">",final:"c"},u=>this.sendDeviceAttributesSecondary(u)),this._parser.registerCsiHandler({final:"d"},u=>this.linePosAbsolute(u)),this._parser.registerCsiHandler({final:"e"},u=>this.vPositionRelative(u)),this._parser.registerCsiHandler({final:"f"},u=>this.hVPosition(u)),this._parser.registerCsiHandler({final:"g"},u=>this.tabClear(u)),this._parser.registerCsiHandler({final:"h"},u=>this.setMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"h"},u=>this.setModePrivate(u)),this._parser.registerCsiHandler({final:"l"},u=>this.resetMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"l"},u=>this.resetModePrivate(u)),this._parser.registerCsiHandler({final:"m"},u=>this.charAttributes(u)),this._parser.registerCsiHandler({final:"n"},u=>this.deviceStatus(u)),this._parser.registerCsiHandler({prefix:"?",final:"n"},u=>this.deviceStatusPrivate(u)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},u=>this.softReset(u)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},u=>this.setCursorStyle(u)),this._parser.registerCsiHandler({final:"r"},u=>this.setScrollRegion(u)),this._parser.registerCsiHandler({final:"s"},u=>this.saveCursor(u)),this._parser.registerCsiHandler({final:"t"},u=>this.windowOptions(u)),this._parser.registerCsiHandler({final:"u"},u=>this.restoreCursor(u)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},u=>this.insertColumns(u)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},u=>this.deleteColumns(u)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},u=>this.selectProtected(u)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},u=>this.requestMode(u,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},u=>this.requestMode(u,!1)),this._parser.setExecuteHandler(K.BEL,()=>this.bell()),this._parser.setExecuteHandler(K.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(K.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(K.BS,()=>this.backspace()),this._parser.setExecuteHandler(K.HT,()=>this.tab()),this._parser.setExecuteHandler(K.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(K.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(da.IND,()=>this.index()),this._parser.setExecuteHandler(da.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(da.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new en(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new en(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new en(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new en(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new en(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new en(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new en(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new en(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new en(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new en(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new en(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new en(u=>this.restoreCursorColor(u))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let u in ut)this._parser.registerEscHandler({intermediates:"(",final:u},()=>this.selectCharset("("+u)),this._parser.registerEscHandler({intermediates:")",final:u},()=>this.selectCharset(")"+u)),this._parser.registerEscHandler({intermediates:"*",final:u},()=>this.selectCharset("*"+u)),this._parser.registerEscHandler({intermediates:"+",final:u},()=>this.selectCharset("+"+u)),this._parser.registerEscHandler({intermediates:"-",final:u},()=>this.selectCharset("-"+u)),this._parser.registerEscHandler({intermediates:".",final:u},()=>this.selectCharset("."+u)),this._parser.registerEscHandler({intermediates:"/",final:u},()=>this.selectCharset("/"+u));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(u=>(this._logService.error("Parsing error: ",u),u)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Mg((u,h)=>this.requestStatusString(u,h)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),zg))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${zg} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,s=this._activeBuffer.y,i=0,l=this._parseStack.paused;if(l){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,s=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>br&&(i=this._parseStack.position+br)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,u=>String.fromCharCode(u)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(u=>u.charCodeAt(0)):e),this._parseBuffer.lengthbr)for(let u=i;u0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let f=this._parser.precedingJoinState;for(let p=t;pa){if(c){let v=d,_=this._activeBuffer.x-w;for(this._activeBuffer.x=w,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),w>0&&d instanceof ll&&d.copyCellsFrom(v,_,0,w,!1);_=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(u&&(d.insertCells(this._activeBuffer.x,s-w,this._activeBuffer.getNullCell(h)),d.getWidth(a-1)===2&&d.setCellFromCodepoint(a-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,r,s,h),s>0)for(;--s;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>Bg(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Mg(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new en(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,s=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),s),r&&(i.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=a;for(let u=1;u0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(K.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(K.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(K.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(K.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(K.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(x[x.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",x[x.SET=1]="SET",x[x.RESET=2]="RESET",x[x.PERMANENTLY_SET=3]="PERMANENTLY_SET",x[x.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:i}=this._coreMouseService,l=this._coreService,{buffers:a,cols:c}=this._bufferService,{active:u,alt:h}=a,d=this._optionsService.rawOptions,f=(x,w)=>(l.triggerDataEvent(`${K.ESC}[${t?"":"?"}${x};${w}$y`),!0),p=x=>x?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(l.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:c===132?1:0:0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(s==="X10")):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!l.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(s==="VT200")):m===1002?f(m,p(s==="DRAG")):m===1003?f(m,p(s==="ANY")):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(i==="SGR")):m===1015?f(m,4):m===1016?f(m,p(i==="SGR_PIXELS")):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(u===h)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,s){return t===2?(e|=50331648,e&=-16777216,e|=Xl.fromColorRGB([n,r,s])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],s=0,i=0;do{if(r[i+s]=e.params[t+i],e.hasSubParams(t+i)){let l=e.getSubParams(t+i),a=0;do r[1]===5&&(s=1),r[i+a+1+s]=l[a];while(++a=2||r[1]===2&&i+s>=5)break;r[1]&&(s=1)}while(++i+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=nt.fg,e.bg=nt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let s=0;s=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777216|n-90|8):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777216|n-100|8):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(s)?e.getSubParams(s)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=nt.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=nt.bg&16777215):n===38||n===48||n===58?s+=this._extractColor(e,s,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=nt.fg&16777215,r.bg&=-67108864,r.bg|=nt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${K.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[?${t};${n}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=nt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Bg(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${K.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Og&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Og&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let r=n.shift(),s=n.shift();if(/^\d+$/.exec(r)){let i=parseInt(r);if($g(i))if(s==="?")t.push({type:0,index:i});else{let l=Ig(s);l&&t.push({type:1,index:i,color:l})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),r,s=n.findIndex(i=>i.startsWith("id="));return s!==-1&&(r=n[s].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let r=0;r=this._specialColors.length);++r,++t)if(n[r]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let s=Ig(n[r]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let r=0;r=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new yn;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${K.ESC}${l}${K.ESC}\\`),!0),r=this._bufferService.buffer,s=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Th=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Fg=e,e=t,t=Fg),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Th=Qe([ie(0,Ft)],Th);function $g(e){return 0<=e&&e<256}var TN=5e7,Wg=12,LN=50,DN=class extends be{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>TN)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let r=this._writeBuffer[this._bufferOffset],s=this._action(r,t);if(s){let l=a=>performance.now()-n>=Wg?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(n,a);s.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(l);return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-n>=Wg)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>LN&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Lh=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),c={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(c,a)),this._dataByLinkId.set(c.id,c),c.id}let n=e,r=this._getEntryIdKey(n),s=this._entriesWithId.get(r);if(s)return this.addLineToLink(s.id,t.ybase+t.y),s.id;let i=t.addMarker(t.ybase+t.y),l={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(l,i)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(r=>r.line!==t)){let r=this._bufferService.buffer.addMarker(t);n.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(n,r))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Lh=Qe([ie(0,Ft)],Lh);var Hg=!1,RN=class extends be{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new xi),this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onData=this._register(new ne),this.onData=this._onData.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ne),this._instantiationService=new sN,this.optionsService=this._register(new pN(e)),this._instantiationService.setService($t,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Nh)),this._instantiationService.setService(Ft,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(jh)),this._instantiationService.setService(yb,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Eh)),this._instantiationService.setService(Ns,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Ph)),this._instantiationService.setService(_b,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ds)),this._instantiationService.setService(eC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(_N),this._instantiationService.setService(Z1,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Lh),this._instantiationService.setService(bb,this._oscLinkService),this._inputHandler=this._register(new AN(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(yt.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(yt.forward(this._bufferService.onResize,this._onResize)),this._register(yt.forward(this.coreService.onData,this._onData)),this._register(yt.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new DN((t,n)=>this._inputHandler.parse(t,n))),this._register(yt.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ne),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Hg&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Hg=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Zb),t=Math.max(t,ew),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Rg.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Rg(this._bufferService),!1))),this._windowsWrappingHeuristics.value=$e(()=>{for(let t of e)t.dispose()})}}},MN={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function IN(e,t,n,r){let s={type:0,cancel:!1,key:void 0},i=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?s.key=K.ESC+"OA":s.key=K.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?s.key=K.ESC+"OD":s.key=K.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?s.key=K.ESC+"OC":s.key=K.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?s.key=K.ESC+"OB":s.key=K.ESC+"[B");break;case 8:s.key=e.ctrlKey?"\b":K.DEL,e.altKey&&(s.key=K.ESC+s.key);break;case 9:if(e.shiftKey){s.key=K.ESC+"[Z";break}s.key=K.HT,s.cancel=!0;break;case 13:s.key=e.altKey?K.ESC+K.CR:K.CR,s.cancel=!0;break;case 27:s.key=K.ESC,e.altKey&&(s.key=K.ESC+K.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"D":t?s.key=K.ESC+"OD":s.key=K.ESC+"[D";break;case 39:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"C":t?s.key=K.ESC+"OC":s.key=K.ESC+"[C";break;case 38:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"A":t?s.key=K.ESC+"OA":s.key=K.ESC+"[A";break;case 40:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"B":t?s.key=K.ESC+"OB":s.key=K.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(s.key=K.ESC+"[2~");break;case 46:i?s.key=K.ESC+"[3;"+(i+1)+"~":s.key=K.ESC+"[3~";break;case 36:i?s.key=K.ESC+"[1;"+(i+1)+"H":t?s.key=K.ESC+"OH":s.key=K.ESC+"[H";break;case 35:i?s.key=K.ESC+"[1;"+(i+1)+"F":t?s.key=K.ESC+"OF":s.key=K.ESC+"[F";break;case 33:e.shiftKey?s.type=2:e.ctrlKey?s.key=K.ESC+"[5;"+(i+1)+"~":s.key=K.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:e.ctrlKey?s.key=K.ESC+"[6;"+(i+1)+"~":s.key=K.ESC+"[6~";break;case 112:i?s.key=K.ESC+"[1;"+(i+1)+"P":s.key=K.ESC+"OP";break;case 113:i?s.key=K.ESC+"[1;"+(i+1)+"Q":s.key=K.ESC+"OQ";break;case 114:i?s.key=K.ESC+"[1;"+(i+1)+"R":s.key=K.ESC+"OR";break;case 115:i?s.key=K.ESC+"[1;"+(i+1)+"S":s.key=K.ESC+"OS";break;case 116:i?s.key=K.ESC+"[15;"+(i+1)+"~":s.key=K.ESC+"[15~";break;case 117:i?s.key=K.ESC+"[17;"+(i+1)+"~":s.key=K.ESC+"[17~";break;case 118:i?s.key=K.ESC+"[18;"+(i+1)+"~":s.key=K.ESC+"[18~";break;case 119:i?s.key=K.ESC+"[19;"+(i+1)+"~":s.key=K.ESC+"[19~";break;case 120:i?s.key=K.ESC+"[20;"+(i+1)+"~":s.key=K.ESC+"[20~";break;case 121:i?s.key=K.ESC+"[21;"+(i+1)+"~":s.key=K.ESC+"[21~";break;case 122:i?s.key=K.ESC+"[23;"+(i+1)+"~":s.key=K.ESC+"[23~";break;case 123:i?s.key=K.ESC+"[24;"+(i+1)+"~":s.key=K.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?s.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?s.key=K.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?s.key=K.DEL:e.keyCode===219?s.key=K.ESC:e.keyCode===220?s.key=K.FS:e.keyCode===221&&(s.key=K.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let l=MN[e.keyCode]?.[e.shiftKey?1:0];if(l)s.key=K.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){let a=e.ctrlKey?e.keyCode-64:e.keyCode+32,c=String.fromCharCode(a);e.shiftKey&&(c=c.toUpperCase()),s.key=K.ESC+c}else if(e.keyCode===32)s.key=K.ESC+(e.ctrlKey?K.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let a=e.code.slice(3,4);e.shiftKey||(a=a.toLowerCase()),s.key=K.ESC+a,s.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(s.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?s.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(s.key=K.US),e.key==="@"&&(s.key=K.NUL));break}return s}var Je=0,ON=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ga,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ga,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((s,i)=>this._getKey(s)-this._getKey(i)),t=0,n=0,r=new Array(this._array.length+this._insertedValues.length);for(let s=0;s=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[s]=e[t],t++):r[s]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Je=this._search(t),Je===-1)||this._getKey(this._array[Je])!==t)return!1;do if(this._array[Je]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Je),!0;while(++Jes-i),t=0,n=new Array(this._array.length-e.length),r=0;for(let s=0;s0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Je=this._search(e),!(Je<0||Je>=this._array.length)&&this._getKey(this._array[Je])===e))do yield this._array[Je];while(++Je=this._array.length)&&this._getKey(this._array[Je])===e))do t(this._array[Je]);while(++Je=t;){let r=t+n>>1,s=this._getKey(this._array[r]);if(s>e)n=r-1;else if(s0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},yu=0,Ug=0,BN=class extends be{constructor(){super(),this._decorations=new ON(e=>e?.marker.line),this._onDecorationRegistered=this._register(new ne),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ne),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register($e(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new zN(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),r=t.onDispose(()=>{r.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,s=0;for(let i of this._decorations.getKeyIterator(t))r=i.options.x??0,s=r+(i.options.width??1),e>=r&&e{yu=s.options.x??0,Ug=yu+(s.options.width??1),e>=yu&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let s=r-this._lastRefreshMs,i=this._debounceThresholdMS-s;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},i)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},qg=20,Ya=class extends be{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let s=this._coreBrowserService.mainDocument;this._accessibilityContainer=s.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=s.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let i=0;ithis._handleBoundaryFocus(i,0),this._bottomBoundaryFocusListener=i=>this._handleBoundaryFocus(i,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=s.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new $N(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(i=>this._handleResize(i.rows))),this._register(this._terminal.onRender(i=>this._refreshRows(i.start,i.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(i=>this._handleChar(i))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(i=>this._handleTab(i))),this._register(this._terminal.onKey(i=>this._handleKey(i.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(me(s,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register($e(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===qg+1&&(this._liveRegion.textContent+=Jd.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let s=e;s<=t;s++){let i=n.lines.get(n.ydisp+s),l=[],a=i?.translateToString(!0,void 0,void 0,l)||"",c=(n.ydisp+s+1).toString(),u=this._rowElements[s];u&&(a.length===0?(u.textContent=" ",this._rowColumns.set(u,[0,1])):(u.textContent=a,this._rowColumns.set(u,l)),u.setAttribute("aria-posinset",c),u.setAttribute("aria-setsize",r),this._alignRowWidth(u))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],s=n.getAttribute("aria-posinset"),i=t===0?"1":`${this._terminal.buffer.lines.length}`;if(s===i||e.relatedTarget!==r)return;let l,a;if(t===0?(l=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(l=this._rowElements.shift(),a=n,this._rowContainer.removeChild(l)),l.removeEventListener("focus",this._topBoundaryFocusListener),a.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let c=this._createAccessibilityTreeNode();this._rowElements.unshift(c),this._rowContainer.insertAdjacentElement("afterbegin",c)}else{let c=this._createAccessibilityTreeNode();this._rowElements.push(c),this._rowContainer.appendChild(c)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let s=({node:a,offset:c})=>{let u=a instanceof Text?a.parentNode:a,h=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(h))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(u);if(!d)return console.warn("columns is null. Race condition?"),null;let f=c=this._terminal.cols&&(++h,f=0),{row:h,column:f}},i=s(t),l=s(n);if(!(!i||!l)){if(i.row>l.row||i.row===l.row&&i.column>=l.column)throw new Error("invalid range");this._terminal.select(i.column,i.row,(l.row-i.row)*this._terminal.cols-i.column+l.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{ws(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(me(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(me(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(me(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(me(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let r=0;r{r?.forEach(s=>{s.link.dispose&&s.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,s]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):s.provideLinks(e.y,i=>{if(this._isMouseOut)return;let l=i?.map(a=>({link:a}));this._activeProviderReplies?.set(r,l),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:l.link.range.end.x;for(let u=a;u<=c;u++){if(n.has(u)){s.splice(i--,1);break}n.add(u)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),s=!1;for(let i=0;ithis._linkAtPosition(l.link,t));i&&(n=!0,this._handleNewLink(i))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let i=0;ithis._linkAtPosition(a.link,t));if(l){n=!0,this._handleNewLink(l);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&WN(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ws(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let r=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(r,s),this._lastMouseEvent)){let i=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);i&&this._askForLink(i,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,s=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(s)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,s=t.y*this._bufferService.cols+t.x;return n<=s&&s<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,s){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:s}}};Dh=Qe([ie(1,Zf),ie(2,gr),ie(3,Ft),ie(4,Sb)],Dh);function WN(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var HN=class extends RN{constructor(e={}){super(e),this._linkifier=this._register(new xi),this.browser=Wb,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new xi),this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ne),this.onKey=this._onKey.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ne),this.onBell=this._onBell.event,this._onFocus=this._register(new ne),this._onBlur=this._register(new ne),this._onA11yCharEmitter=this._register(new ne),this._onA11yTabEmitter=this._register(new ne),this._onWillOpen=this._register(new ne),this._setup(),this._decorationService=this._instantiationService.createInstance(BN),this._instantiationService.setService(Ql,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Lj),this._instantiationService.setService(Sb,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(eh)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(yt.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(yt.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(yt.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(yt.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register($e(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let n,r="";switch(t.index){case 256:n="foreground",r="10";break;case 257:n="background",r="11";break;case 258:n="cursor",r="12";break;default:n="ansi",r="4;"+t.index}switch(t.type){case 0:let s=Be.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${K.ESC}]${r};${EN(s)}${Fb.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(i=>i.ansi[t.index]=rt.toColor(...t.color));else{let i=n;this._themeService.modifyColors(l=>l[i]=rt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ya,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,s=t.getWidth(n),i=this._renderService.dimensions.css.cell.width*s,l=this.buffer.y*this._renderService.dimensions.css.cell.height,a=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=l+"px",this.textarea.style.width=i+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(me(this.element,"copy",t=>{this.hasSelection()&&K1(t,this._selectionService)}));let e=t=>G1(t,this.textarea,this.coreService,this.optionsService);this._register(me(this.textarea,"paste",e)),this._register(me(this.element,"paste",e)),Hb?this._register(me(this.element,"mousedown",t=>{t.button===2&&tg(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(me(this.element,"contextmenu",t=>{tg(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),op&&this._register(me(this.element,"auxclick",t=>{t.button===1&&pb(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(me(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(me(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(me(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(me(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(me(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(me(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(me(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(me(this.screenElement,"mousemove",s=>this.updateCursorStyle(s))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Qd.get()),Vb||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Aj,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(mr,this._coreBrowserService),this._register(me(this.textarea,"focus",s=>this._handleTextAreaFocus(s))),this._register(me(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(bh,this._document,this._helperContainer),this._instantiationService.setService(Sc,this._charSizeService),this._themeService=this._instantiationService.createInstance(Ch),this._instantiationService.setService(Si,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Va),this._instantiationService.setService(wb,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Sh,this.rows,this.screenElement)),this._instantiationService.setService(gr,this._renderService),this._register(this._renderService.onRenderedViewportChange(s=>this._onRender.fire(s))),this.onResize(s=>this._renderService.resize(s.cols,s.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(vh,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(wh),this._instantiationService.setService(Zf,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Dh,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(gh,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(s=>{super.scrollLines(s,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(kh,this.element,this.screenElement,r)),this._instantiationService.setService(nC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(s=>this.scrollLines(s.amount,s.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(s=>this._renderService.handleSelectionChanged(s.start,s.end,s.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(s=>{this.textarea.value=s,this.textarea.focus(),this.textarea.select()})),this._register(yt.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(xh,this.screenElement)),this._register(me(this.element,"mousedown",s=>this._selectionService.handleMouseDown(s))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ya,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",s=>this._handleScreenReaderModeOptionChange(s))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(qa,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",s=>{!this._overviewRulerRenderer&&s&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(qa,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(yh,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(i){let l=e._mouseService.getMouseReportCoords(i,e.screenElement);if(!l)return!1;let a,c;switch(i.overrideType||i.type){case"mousemove":c=32,i.buttons===void 0?(a=3,i.button!==void 0&&(a=i.button<3?i.button:3)):a=i.buttons&1?0:i.buttons&4?1:i.buttons&2?2:3;break;case"mouseup":c=0,a=i.button<3?i.button:3;break;case"mousedown":c=1,a=i.button<3?i.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(i)===!1)return!1;let u=i.deltaY;if(u===0||e.coreMouseService.consumeWheelEvent(i,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;c=u<0?0:1,a=4;break;default:return!1}return c===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:l.col,row:l.row,x:l.x,y:l.y,button:a,action:c,ctrl:i.ctrlKey,alt:i.altKey,shift:i.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s={mouseup:i=>(n(i),i.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(i)),wheel:i=>(n(i),this.cancel(i,!0)),mousedrag:i=>{i.buttons&&n(i)},mousemove:i=>{i.buttons||n(i)}};this._register(this.coreMouseService.onProtocolChange(i=>{i?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(i)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),i&8?r.mousemove||(t.addEventListener("mousemove",s.mousemove),r.mousemove=s.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),i&16?r.wheel||(t.addEventListener("wheel",s.wheel,{passive:!1}),r.wheel=s.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),i&2?r.mouseup||(r.mouseup=s.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),i&4?r.mousedrag||(r.mousedrag=s.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(me(t,"mousedown",i=>{if(i.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(i)))return n(i),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(i)})),this._register(me(t,"wheel",i=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(i)===!1)return!1;if(!this.buffer.hasScrollback){if(i.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(i,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(i,!0);let l=K.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(i.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(l,!0),this.cancel(i,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){fb(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=IN(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let r=this.rows-1;return this.scrollLines(n.type===2?-r:r),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===K.ETX||n.key===K.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(UN(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new yn)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Vg=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new VN(t)}getNullCell(){return new yn}},KN=class extends be{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ne),this.onBufferChange=this._onBufferChange.event,this._normal=new Vg(this._core.buffers.normal,"normal"),this._alternate=new Vg(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},GN=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,r)=>t(n,r.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},YN=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},XN=["cols","rows"],On=0,QN=class extends be{constructor(e){super(),this._core=this._register(new HN(e)),this._addonManager=this._register(new qN),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],n=(r,s)=>{this._checkReadonlyOptions(r),this._core.options[r]=s};for(let r in this._core.options){let s={get:t.bind(this,r),set:n.bind(this,r)};Object.defineProperty(this._publicOptions,r,s)}}_checkReadonlyOptions(e){if(XN.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new GN(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new YN(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new KN(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Qd.get()},set promptLabel(e){Qd.set(e)},get tooMuchOutput(){return Jd.get()},set tooMuchOutput(e){Jd.set(e)}}}_verifyIntegers(...e){for(On of e)if(On===1/0||isNaN(On)||On%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(On of e)if(On&&(On===1/0||isNaN(On)||On%1!==0||On<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var JN=2,ZN=1,eE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),s=Math.max(0,parseInt(n.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),l={top:parseInt(i.getPropertyValue("padding-top")),bottom:parseInt(i.getPropertyValue("padding-bottom")),right:parseInt(i.getPropertyValue("padding-right")),left:parseInt(i.getPropertyValue("padding-left"))},a=l.top+l.bottom,c=l.right+l.left,u=r-a,h=s-c-t;return{cols:Math.max(JN,Math.floor(h/e.css.cell.width)),rows:Math.max(ZN,Math.floor(u/e.css.cell.height))}}};function jt(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}function Ui(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Jr,hn,Rs,To;const Kg="__TAURI_TO_IPC_KEY__";function nw(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}class Wl{constructor(t){Jr.set(this,void 0),hn.set(this,0),Rs.set(this,[]),To.set(this,void 0),Ui(this,Jr,t||(()=>{})),this.id=nw(n=>{const r=n.index;if("end"in n){r==jt(this,hn,"f")?this.cleanupCallback():Ui(this,To,r);return}const s=n.message;if(r==jt(this,hn,"f")){for(jt(this,Jr,"f").call(this,s),Ui(this,hn,jt(this,hn,"f")+1);jt(this,hn,"f")in jt(this,Rs,"f");){const i=jt(this,Rs,"f")[jt(this,hn,"f")];jt(this,Jr,"f").call(this,i),delete jt(this,Rs,"f")[jt(this,hn,"f")],Ui(this,hn,jt(this,hn,"f")+1)}jt(this,hn,"f")===jt(this,To,"f")&&this.cleanupCallback()}else jt(this,Rs,"f")[r]=s})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(t){Ui(this,Jr,t)}get onmessage(){return jt(this,Jr,"f")}[(Jr=new WeakMap,hn=new WeakMap,Rs=new WeakMap,To=new WeakMap,Kg)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[Kg]()}}async function F(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}var Gg;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_SUSPENDED="tauri://suspended",e.WINDOW_RESUMED="tauri://resumed",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"})(Gg||(Gg={}));async function tE(e,t){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,t),await F("plugin:event|unlisten",{event:e,eventId:t})}async function Xa(e,t,n){var r;const s=(r=void 0)!==null&&r!==void 0?r:{kind:"Any"};return F("plugin:event|listen",{event:e,target:s,handler:nw(t)}).then(i=>async()=>tE(e,i))}async function Yg(e={}){return typeof e=="object"&&Object.freeze(e),await F("plugin:dialog|open",{options:e})}const nE="domain://event",rE="app-exit-work-guard";class sE{async health(t){return F("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await Xa(nE,r=>{t(r.payload)})}async pickFolder(){const t=await Yg({directory:!0,multiple:!1});return t==null?null:typeof t=="string"?t:null}async pickArchiveFile(){const t=await Yg({directory:!1,multiple:!1,filters:[{name:"Plugin archive",extensions:["ideaplug","zip","vsix"]}]});return typeof t=="string"?t:null}async onAppExitWorkGuard(t){return await Xa(rE,r=>{t(r.payload)})}async confirmAppExit(){await F("confirm_app_exit")}}function Qa(e,t){let n=Promise.resolve();return{sessionId:e,write(r){const s=n.then(async()=>{Xg("start",e,r),await F("write_terminal",{request:{sessionId:e,data:Array.from(r)}}),Xg("ok",e,r)});return n=s.catch(()=>{}),s},async resize(r,s){await F("resize_terminal",{request:{sessionId:e,rows:r,cols:s}})},detach(){t.onmessage=()=>{}},async close(){await F("close_terminal",{sessionId:e})}}}function Xg(e,t,n){n.length===1&&n[0]>=32&&n[0]!==127||console.info("[terminal-write]",e,{sessionId:t,bytes:n.length,control:iE(n)})}function iE(e){return e.length===0?"":e.length>16?"":Array.from(e).map(t=>{switch(t){case 13:return"\\r";case 10:return"\\n";case 127:return"\\x7f";default:return t<32?`\\x${t.toString(16).padStart(2,"0")}`:String.fromCharCode(t)}}).join("")}class lE{async openTerminal(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("open_terminal",{request:{cwd:t.cwd,rows:t.rows,cols:t.cols},onOutput:r});return Qa(s.sessionId,r)}async reattach(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Qa(s.sessionId,r),scrollback:Uint8Array.from(s.scrollback)}}async closeTerminal(t){await F("close_terminal",{sessionId:t})}}class oE{listAgents(t){return F("list_agents",{projectId:t})}listLiveAgents(t){return F("list_live_agents",{projectId:t})}listResumableAgents(t){return F("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return F("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return F("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return F("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,s,i){return F("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:s,cols:i}})}readContext(t,n){return F("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await F("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await F("delete_agent",{projectId:t,agentId:n})}async launchAgent(t,n,r,s){const i=new Wl;i.onmessage=c=>s(Uint8Array.from(c));const l=await F("launch_agent",{request:{projectId:t,agentId:n,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,nodeId:r.nodeId??null},onOutput:i});return{...Qa(l.sessionId,i),...l.assignedConversationId?{assignedConversationId:l.assignedConversationId}:{}}}async reattach(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Qa(s.sessionId,r),scrollback:Uint8Array.from(s.scrollback)}}inspectConversation(t,n,r){return F("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}}class aE{async interrupt(t,n){await F("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){console.info("[input-gateway] delegationDelivered:start",{projectId:t,agentId:n,ticket:r}),await F("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}}),console.info("[input-gateway] delegationDelivered:ok",{projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){console.info("[input-gateway] setFrontAttached:start",{agentId:t,attached:n}),await F("set_front_attached",{request:{agentId:t,attached:n}}),console.info("[input-gateway] setFrontAttached:ok",{agentId:t,attached:n})}async cancelResume(t){return F("cancel_resume",{agentId:t})}async setResumeAt(t,n){await F("set_resume_at",{agentId:t,resetsAtMs:n})}}class cE{listProjects(){return F("list_projects")}createProject(t,n){return F("create_project",{request:{name:t,root:n}})}openProject(t){return F("open_project",{projectId:t})}async closeProject(t){await F("close_project",{projectId:t})}readProjectContext(t){return F("read_project_context",{projectId:t})}async updateProjectContext(t,n){await F("update_project_context",{request:{projectId:t,content:n}})}}class uE{loadLayout(t,n){return F("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return F("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return F("list_layouts",{projectId:t})}createLayout(t,n,r){return F("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return F("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return F("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return F("set_active_layout",{request:{projectId:t,layoutId:n}})}}class dE{firstRunState(){return F("first_run_state")}referenceProfiles(){return F("reference_profiles")}detectProfiles(t){return F("detect_profiles",{request:{candidates:t}})}listProfiles(){return F("list_profiles")}saveProfile(t){return F("save_profile",{request:{profile:t}})}async deleteProfile(t){await F("delete_profile",{profileId:t})}configureProfiles(t){return F("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return F("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return F("list_opencode_providers")}saveOpenCodeProviderProfile(t){return F("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class hE{listModelServers(){return F("list_model_servers")}saveModelServer(t){return F("save_model_server",{request:{config:t}})}async deleteModelServer(t){await F("delete_model_server",{serverId:t})}previewModelServerCommand(t){return F("preview_model_server_command",{config:t})}}const fE=2e3;class pE{constructor(t=fE){this.pollMs=t}getExposureSettings(){return F("get_server_exposure_settings")}async saveExposureSettings(t){await F("save_server_exposure_settings",{settings:t})}previewExposure(t){return F("preview_server_exposure_settings",{settings:t})}status(){return F("embedded_server_status")}start(){return F("embedded_server_start")}stop(){return F("embedded_server_stop")}async onStatusChanged(t){let n=!1;const r=setInterval(()=>{this.status().then(s=>{n||t(s)},()=>{})},this.pollMs);return()=>{n=!0,clearInterval(r)}}}class mE{listTemplates(){return F("list_templates")}createTemplate(t){return F("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return F("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await F("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return F("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return F("detect_agent_drift",{projectId:t})}syncAgent(t,n){return F("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class gE{listSkills(t,n){return F("list_skills",{projectId:t,scope:n})}createSkill(t){return F("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,s){return F("update_skill",{request:{projectId:t,scope:n,skillId:r,content:s}})}async deleteSkill(t,n,r){await F("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,s){await F("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:s}})}async unassignSkill(t,n,r){await F("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class xE{listMemories(t){return F("list_memories",{projectId:t})}getMemory(t,n){return F("get_memory",{projectId:t,slug:n})}createMemory(t){return F("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,s,i){return F("update_memory",{request:{projectId:t,slug:n,description:r,type:s,content:i}})}async deleteMemory(t,n){await F("delete_memory",{projectId:t,slug:n})}readIndex(t){return F("read_memory_index",{projectId:t})}resolveLinks(t,n){return F("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return F("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class vE{listEmbedderProfiles(){return F("list_embedder_profiles")}saveEmbedderProfile(t){return F("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await F("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return F("describe_embedder_engines")}}class _E{async listDevices(){return(await F("list_devices")).devices}createPairingCode(){return F("create_pairing_code")}renameDevice(t,n){return F("rename_device",{request:{deviceId:t,name:n}})}revokeDevice(t){return F("revoke_device",{request:{deviceId:t}})}revokeAllDevices(){return F("revoke_all_devices")}}class yE{status(t){return F("git_status",{projectId:t})}async stage(t,n){await F("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await F("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return F("git_commit",{request:{projectId:t,message:n}})}branches(t){return F("git_branches",{projectId:t})}async checkout(t,n){await F("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return F("git_log",{projectId:t,limit:n})}async init(t){await F("git_init",{projectId:t})}graph(t,n){return F("git_graph",{projectId:t,limit:n})}}class bE{getProjectPermissions(t){return F("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return F("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return F("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return F("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getProjectSystemPermissions(t){return F("get_project_system_permissions",{projectId:t})}updateProjectSystemPermissions(t,n){return F("update_project_system_permissions",{request:{projectId:t,permissions:n}})}updateAgentSystemPermissions(t,n,r){return F("update_agent_system_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentSystemPermissions(t,n){return F("resolve_agent_system_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return F("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return F("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return F("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xe(e,t=""){return typeof e=="string"?e:t}function Yn(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function wE(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ms(e){return Array.isArray(e)?e:[]}function Qg(e){return typeof e=="string"?e:void 0}function ci(e){return typeof e=="string"?e:null}function rw(e){return Tn(e)?e.kind==="agent"?{kind:"agent",agentId:Xe(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function SE(e){return e==="inProgress"?"inProgress":"queued"}function kE(e){return Tn(e)&&e.state==="busy"?{state:"busy",ticket:Xe(e.ticket,"unknown"),sinceMs:Yn(e.sinceMs,0)}:{state:"idle"}}function CE(e,t){const n=Tn(e)?e:{},r=Xe(n.taskPreview);return{ticketId:Xe(n.ticketId,`legacy-ticket-${t}`),conversationId:Xe(n.conversationId),position:Yn(n.position,t),status:SE(n.status),source:rw(n.source),requesterLabel:Xe(n.requesterLabel),taskPreview:r,taskLen:Yn(n.taskLen,r.length)}}function jE(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="completed"||t==="success"||t==="succeeded"?"completed":t==="failed"||t==="failure"?"failed":t==="cancelled"||t==="canceled"||t==="expired"?"cancelled":t==="running"||t==="started"?"running":t==="delivered"?"delivered":"pending"}function NE(e,t,n){const r=Tn(e)?e:{};return{taskId:Xe(r.taskId,`legacy-task-${t}`),ownerAgentId:Xe(r.ownerAgentId,n),projectId:Xe(r.projectId),kind:Xe(r.kind,"background"),status:jE(r.status??r.state),exitCode:wE(r.exitCode),summary:ci(r.summary),stdoutTail:ci(r.stdoutTail),stderrTail:ci(r.stderrTail),updatedAtMs:Yn(r.updatedAtMs)}}function sw(e,t,n){const r=Tn(e)?e:{};return{id:Xe(r.id,`legacy-inbox-${t}`),agentId:Xe(r.agentId??r.agent_id,n),source:Xe(r.source,"unknown"),kind:Xe(r.kind,"message"),body:Xe(r.body),createdAtMs:Yn(r.createdAtMs??r.created_at_ms,0),...Qg(r.correlationId??r.correlation_id)?{correlationId:Qg(r.correlationId??r.correlation_id)}:{},priority:Yn(r.priority,0)}}function EE(e,t){const n=Tn(e)?e:{},r=Tn(n.live)&&n.live.kind==="structured"?"structured":"pty",s=Tn(n.live)?{nodeId:Xe(n.live.nodeId),sessionId:Xe(n.live.sessionId),kind:r}:void 0,i=Xe(n.agentId,`legacy-agent-${t}`),l=ms(n.inbox).map((c,u)=>sw(c,u,i)),a=ms(n.backgroundTasks??n.backgroundCompletions).map((c,u)=>NE(c,u,i));return{agentId:i,name:Xe(n.name,"Unnamed agent"),profileId:Xe(n.profileId,"unknown"),...s?{live:s}:{},busy:kE(n.busy),tickets:ms(n.tickets).map(CE),inboxDepth:Yn(n.inboxDepth,l.length),inbox:l,backgroundTasks:a}}function PE(e){return e==="ready"||e==="partial"||e==="unavailable"||e==="missing"?e:"missing"}function AE(e,t){const n=Tn(e)?e:{},r=Xe(n.textPreview);return{role:n.role==="response"||n.role==="toolActivity"?n.role:"prompt",source:rw(n.source),atMs:Yn(n.atMs,t),textPreview:r,textLen:Yn(n.textLen,r.length)}}function TE(e,t){const n=Tn(e)?e:{};return{conversationId:Xe(n.conversationId,`legacy-conversation-${t}`),status:PE(n.status),objectivePreview:ci(n.objectivePreview),summaryPreview:ci(n.summaryPreview),summaryLen:Yn(n.summaryLen,0),upTo:ci(n.upTo),recentTurns:ms(n.recentTurns).map(AE)}}function ap(e){const t=Tn(e)?e:{},n=ms(t.agents).map(EE),r=ms(t.inboxItems).map((s,i)=>sw(s,i,""));for(const s of r){const i=n.find(l=>l.agentId===s.agentId);i&&(i.inbox??=[],i.inboxDepth??=0,i.inbox.some(l=>l.id===s.id)||(i.inbox.push(s),i.inboxDepth=Math.max(i.inboxDepth,i.inbox.length)))}return{agents:n,conversations:ms(t.conversations).map(TE)}}class LE{async getProjectWorkState(t){const n=await F("get_project_work_state",{projectId:t});return ap(n)}async cancelBackgroundTask(t){await F("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await F("retry_background_task",{taskId:t})}}function cp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Rh(e,t=""){return typeof e=="string"?e:t}function Jg(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function DE(e){return Array.isArray(e)?e:[]}function RE(e){return cp(e)?e.kind==="agent"?{kind:"agent",agentId:Rh(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function ME(e){return e==="response"||e==="toolActivity"?e:"prompt"}function IE(e,t){const n=cp(e)?e:{},r=Rh(n.text);return{id:Rh(n.id,`turn-${t}`),atMs:Jg(n.atMs,t),role:ME(n.role),source:RE(n.source),text:r,textLen:Jg(n.textLen,r.length)}}function iw(e){const t=cp(e)?e:{},n=t.nextAnchor;return{turns:DE(t.turns).map(IE),hasMore:t.hasMore===!0,...typeof n=="string"?{nextAnchor:n}:{}}}class OE{async readPage(t,n,r){const s=await F("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return iw(s)}}class BE{async create(t,n){return F("ticket_create",{request:{projectId:t,...n}})}async read(t,n,r=!1){return F("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}async list(t,n){const{statuses:r,priorities:s,...i}=n??{};return F("ticket_list",{request:{projectId:t,statuses:r??[],priorities:s??[],...i}})}async update(t,n,r){return F("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await F("ticket_delete",{request:{projectId:t,ref:n}})}async readCarnet(t,n){return F("ticket_read_carnet",{request:{projectId:t,ref:n}})}async updateCarnet(t,n,r,s){return F("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:s}})}async link(t,n,r,s,i){return F("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:s,expectedVersion:i}})}async unlink(t,n,r,s,i){return F("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:s,kind:i}})}async assign(t,n,r,s,i){return F("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:s,expectedVersion:i}})}async listSprints(t){return(await F("sprint_list",{request:{projectId:t}})).items}async setTicketSprint(t,n,r,s){return r===null?F("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:s}}):F("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:s}})}async createSprint(t,n){return F("sprint_create",{request:{projectId:t,name:n}})}async renameSprint(t,n,r,s){return F("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:s}})}async reorderSprints(t,n){return(await F("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await F("sprint_delete",{request:{projectId:t,sprintId:n}})}async openTicketChat(t,n,r){return F("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await F("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const s=new Wl;s.onmessage=i=>r(i),await F("agent_send",{sessionId:t,prompt:n,onReply:s})}}const zE="view-window://lifecycle";class FE{async openViewWindow(t){await F("open_view_window",{panel:t})}async closeViewWindow(t){await F("close_view_window",{panel:t})}async listOpenViewWindows(){return F("list_open_view_windows")}async onViewWindowClosed(t){return await Xa(zE,r=>{r.payload.kind==="closed"&&t({panel:r.payload.panel})})}}const $E="focused-project://changed";class WE{async setFocusedProject(t){await F("set_focused_project",{project:t})}async getFocusedProject(){return await F("get_focused_project")??null}async onFocusedProjectChanged(t){return await Xa($E,r=>t(r.payload.project??null))}}function bu(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}class lw{read(t){const n=bu();if(!n)return null;let r;try{r=n.getItem(t)}catch{return null}if(r===null)return null;try{return JSON.parse(r)}catch{try{n.removeItem(t)}catch{}return null}}write(t,n){const r=bu();if(r)try{r.setItem(t,JSON.stringify(n))}catch{}}remove(t){const n=bu();if(n)try{n.removeItem(t)}catch{}}}class HE{listPlugins(){return F("plugin_list_plugins")}reviewPackage(t){return F("plugin_review_package",{request:{sourceKind:t.sourceKind,path:t.path}})}installFromArchive(t){return F("plugin_install_from_archive",{path:t})}installFromDirectory(t){return F("plugin_install_from_directory",{path:t})}setEnabled(t,n){return F("plugin_set_enabled",{pluginId:t,enabled:n})}uninstall(t){return F("plugin_uninstall",{pluginId:t})}listRuntimeContributions(){return F("plugin_list_runtime_contributions")}async openPluginsFolder(t){await F("plugin_open_plugins_folder",{pluginId:t??null})}}function UE(e){throw{code:"NOT_IMPLEMENTED",message:`${e} is not implemented yet (pending its lot).`}}class qE{connect(){return UE("RemoteGateway.connect")}}function VE(){return{system:new sE,agent:new oE,input:new aE,terminal:new lE,project:new cE,layout:new uE,git:new yE,remote:new qE,profile:new dE,modelServer:new hE,desktopServer:new pE,template:new mE,skill:new gE,memory:new xE,embedder:new vE,device:new _E,permission:new bE,workState:new LE,conversation:new OE,ticket:new BE,window:new FE,focusedProject:new WE,uiPreferences:new lw,plugin:new HE}}function Mh(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Lo(e=Mh()){return{root:{type:"leaf",node:{id:e,session:null}}}}function Ih(e){if(e.length===0)return[];const t=1e-6,n=e.map(s=>Number.isFinite(s)&&s>0?s:t),r=n.reduce((s,i)=>s+i,0);if(r<=0){const s=100/n.length;return n.map(()=>s)}return n.map(s=>s/r*100)}function Zg(e,t,n){const r=[...e];if(t<0||t+1>=r.length)return r;const s=r.reduce((u,h)=>u+h,0),i=n*s,l=s*.05,a=r[t]+i,c=r[t+1]-i;return a({node:Ut(r.node,t),weight:r.weight}))}};break;case"grid":n={type:"grid",node:{...e.node,cells:e.node.cells.map(r=>({...r,node:Ut(r.node,t)}))}};break}return t(n)}function ex(e,t){let n;return Ut(e,r=>(r.type==="leaf"&&r.node.id===t&&(n=r.node.session??null),r)),n}function KE(e,t){switch(t.type){case"split":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const i={id:t.newLeaf,session:null};return{type:"split",node:{id:t.container,direction:t.direction,children:[{node:s,weight:1},{node:{type:"leaf",node:i},weight:1}]}}}return s});if(!n)throw er(t.target);return{root:r}}case"merge":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="split"&&s.node.id===t.container){const i=s.node.children[t.keepIndex];if(!i)throw Do(`merge keepIndex ${t.keepIndex} out of range`);return n=!0,i.node}return s});if(!n)throw er(t.container);return{root:r}}case"resize":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="split"&&s.node.id===t.container){if(s.node.children.length!==t.weights.length)throw Do("resize weight count mismatch");n=!0;const i=s.node.children.map((l,a)=>({node:l.node,weight:t.weights[a]}));return{type:"split",node:{...s.node,children:i}}}return s});if(!n)throw er(t.container);return{root:r}}case"move":{const n=ex(e.root,t.from);if(n===void 0)throw er(t.from);if(n===null)throw Do("source cell has no session");const r=ex(e.root,t.to);if(r===void 0)throw er(t.to);if(r!==null)throw Do("target cell is occupied");return{root:Ut(e.root,i=>i.type==="leaf"&&i.node.id===t.from?{type:"leaf",node:{...i.node,session:null}}:i.type==="leaf"&&i.node.id===t.to?{type:"leaf",node:{...i.node,session:n}}:i)}}case"setSession":{let n=!1;const r=Ut(e.root,s=>s.type==="leaf"&&s.node.id===t.target?(n=!0,{type:"leaf",node:{...s.node,session:t.session??null}}):s);if(!n)throw er(t.target);return{root:r}}case"setCellAgent":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{agent:i,...l}=s.node;return{type:"leaf",node:t.agent!==null?{...l,agent:t.agent}:l}}return s});if(!n)throw er(t.target);return{root:r}}case"setCellConversation":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{conversationId:i,...l}=s.node;return{type:"leaf",node:t.conversationId!==null?{...l,conversationId:t.conversationId}:l}}return s});if(!n)throw er(t.target);return{root:r}}case"setAgentRunning":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{agentWasRunning:i,...l}=s.node;return{type:"leaf",node:t.running?{...l,agentWasRunning:!0}:l}}return s});if(!n)throw er(t.target);return{root:r}}}}function Ja(e){const t=[];return Ut(e.root,n=>(n.type==="leaf"&&t.push(n.node),n)),t}function GE(e,t,n){return{root:Ut(e.root,r=>r.type==="customPluginLayout"&&r.node.id===t?{type:"customPluginLayout",node:{...r.node,state:n}}:r)}}function YE(e,t){return{root:Ut(e.root,n=>n.type==="customPluginLayout"&&n.node.id===t?{type:"leaf",node:{id:t}}:n)}}function XE(e,t){return{type:"split",target:e,direction:t,newLeaf:Mh(),container:Mh()}}function er(e){return{code:"NOT_FOUND",message:`layout node ${e} not found`}}function Do(e){return{code:"INVALID",message:e}}const tx={low:0,medium:1,high:2,critical:3},nx={open:0,inProgress:1,QA:2,closed:3};function QE(e,t){return e.sort((n,r)=>{let s=0;return t.field==="number"?s=n.number-r.number:t.field==="priority"?s=tx[n.priority]-tx[r.priority]:t.field==="status"?s=nx[n.status]-nx[r.status]:s=n.title.localeCompare(r.title,void 0,{sensitivity:"base"})||n.title.localeCompare(r.title),(t.direction==="desc"?-s:s)||n.number-r.number})}class JE{constructor(){X(this,"listeners",new Set);X(this,"exitGuardListeners",new Set);X(this,"confirmAppExitCallCount",0)}async health(t){const n={version:"0.1.0-mock",alive:!0,timeMillis:Date.now(),correlationId:`mock-${Math.random().toString(36).slice(2,10)}`,note:t??null};return this.emit({type:"projectCreated",projectId:n.correlationId}),n}async onDomainEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(t){for(const n of this.listeners)n(t)}async pickFolder(){return"/home/user/mock-project"}async pickArchiveFile(){return"/home/user/mock-plugin.ideaplug"}async onAppExitWorkGuard(t){return this.exitGuardListeners.add(t),()=>{this.exitGuardListeners.delete(t)}}emitAppExitWorkGuard(t){for(const n of this.exitGuardListeners)n(t)}async confirmAppExit(){this.confirmAppExitCallCount+=1}}function up(e){let t="",n=!1;for(const r of e.trim())/[a-zA-Z0-9]/.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="-",n=!0);return t.replace(/^-+|-+$/g,"")}class Oh{constructor(t,n){X(this,"scrollback",[]);X(this,"sink",null);X(this,"closed",!1);this.sessionId=t,this.sink=n}emit(t){if(!this.closed){for(const n of t)this.scrollback.push(n);this.sink?.(t)}}detach(){this.sink=null}reattach(t){return this.sink=t,Uint8Array.from(this.scrollback)}}class ZE{constructor(){X(this,"agents",new Map);X(this,"contexts",new Map);X(this,"sessionSeq",0);X(this,"sessions",new Map);X(this,"liveByAgent",new Map);X(this,"liveSessionByAgent",new Map);X(this,"resumable",new Map);X(this,"conversationDetails",new Map)}getAgents(t){return this.agents.has(t)||this.agents.set(t,[]),this.agents.get(t)}contextKey(t,n){return`${t}::${n}`}async listAgents(t){return structuredClone(this.getAgents(t))}async listLiveAgents(t){const n=new Set(this.getAgents(t).map(r=>r.id));return[...this.liveByAgent.entries()].filter(([r])=>n.has(r)).map(([r,s])=>({agentId:r,nodeId:s,sessionId:this.liveSessionByAgent.get(r),kind:"pty"}))}_setResumableAgents(t,n){this.resumable.set(t,n)}async listResumableAgents(t){return structuredClone(this.resumable.get(t)??[])}async attachLiveAgent(t,n,r){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const i=this.liveSessionByAgent.get(n);if(!i||!this.sessions.has(i))throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};return this.liveByAgent.set(n,r),{agentId:n,nodeId:r,sessionId:i,kind:"pty"}}async stopLiveAgent(t,n){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const s=this.liveSessionByAgent.get(n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};const i=this.sessions.get(s);return i&&(i.closed=!0),this.sessions.delete(s),this.liveSessionByAgent.delete(n),this.liveByAgent.delete(n),{agentId:n,sessionId:s,kind:"pty"}}async createAgent(t,n){const r=this.getAgents(t),s=up(n.name)||"agent",i=new Set(r.map(u=>u.contextPath));let l=`agents/${s}.md`,a=2;for(;i.has(l);)l=`agents/${s}-${a}.md`,a+=1;const c={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:n.name,contextPath:l,profileId:n.profileId,origin:{type:"scratch"},synchronized:!1,skills:[]};return r.push(c),this.contexts.set(this.contextKey(t,c.id),n.initialContent??""),structuredClone(c)}async readContext(t,n){if(!this.getAgents(t).some(s=>s.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};return this.contexts.get(this.contextKey(t,n))??""}async updateContext(t,n,r){if(!this.getAgents(t).some(i=>i.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.contexts.set(this.contextKey(t,n),r)}async deleteAgent(t,n){const r=this.getAgents(t),s=r.findIndex(i=>i.id===n);if(s===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};r.splice(s,1),this.contexts.delete(this.contextKey(t,n))}async changeAgentProfile(t,n,r,s,i){const l=this.getAgents(t),a=l.findIndex(m=>m.id===n);if(a===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};l[a]={...l[a],profileId:r};const c=structuredClone(l[a]),u=this.liveByAgent.get(n),h=this.liveSessionByAgent.get(n);if(!u||!h)return{agent:c};const d=this.sessions.get(h);d&&(d.closed=!0),this.sessions.delete(h),this.sessionSeq+=1;const f=`mock-agent-session-${this.sessionSeq}`,p=new Oh(f,()=>{});return p.detach(),this.sessions.set(f,p),this.liveSessionByAgent.set(n,f),this.liveByAgent.set(n,u),{agent:c,relaunchedSession:{sessionId:f,cwd:"/home/user/mock-project",rows:s,cols:i}}}_insertAgent(t,n,r){this.getAgents(t).push(n),this.contexts.set(this.contextKey(t,n.id),r)}_updateAgent(t,n,r,s){const i=this.getAgents(t),l=i.findIndex(a=>a.id===n);l!==-1&&(i[l]={...i[l],...r},s!==void 0&&this.contexts.set(this.contextKey(t,n),s))}_rawAgents(t){return this.getAgents(t)}_setSkills(t,n,r){const s=this.getAgents(t),i=s.findIndex(l=>l.id===n);i!==-1&&(s[i]={...s[i],skills:r})}async launchAgent(t,n,r,s){if(!this.getAgents(t).some(p=>p.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const l=this.liveByAgent.get(n);if(l!==void 0&&r.nodeId&&l!==r.nodeId)throw{code:"AGENT_ALREADY_RUNNING",message:`agent ${n} is already running in cell ${l}`};this.sessionSeq+=1;const a=`mock-agent-session-${this.sessionSeq}`,c=r.cwd;r.nodeId&&(this.liveByAgent.set(n,r.nodeId),this.liveSessionByAgent.set(n,a));const u=()=>{this.liveByAgent.get(n)===r.nodeId&&(this.liveByAgent.delete(n),this.liveSessionByAgent.delete(n))},h=new TextEncoder,d=new Oh(a,s);this.sessions.set(a,d),queueMicrotask(()=>d.emit(h.encode(`agent ${n} @ ${c}\r -`)));const f=Za(d,()=>{this.sessions.delete(a),u()});return r.conversationId?f:{...f,assignedConversationId:`mock-conversation-${a}`}}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`agent session ${t} is not alive`};const s=r.reattach(n);return{handle:Za(r,()=>{this.sessions.delete(t);for(const[i,l]of this.liveSessionByAgent)l===t&&(this.liveSessionByAgent.delete(i),this.liveByAgent.delete(i))}),scrollback:s}}_setConversationDetails(t,n){this.conversationDetails.set(t,n)}async inspectConversation(t,n,r){return structuredClone(this.conversationDetails.get(r)??{})}}function Za(e,t){return{sessionId:e.sessionId,async write(n){if(e.closed)return;const r=[];for(const s of n)s===13?r.push(13,10):r.push(s);e.emit(Uint8Array.from(r))},async resize(){},detach(){e.detach()},async close(){e.closed=!0,t()}}}class e2{constructor(){X(this,"seq",0);X(this,"sessions",new Map)}async openTerminal(t,n){this.seq+=1;const r=`mock-session-${this.seq}`,s=new TextEncoder,i=new Oh(r,n);return this.sessions.set(r,i),queueMicrotask(()=>i.emit(s.encode(`mock terminal @ ${t.cwd}\r -`))),Za(i,()=>this.sessions.delete(r))}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`terminal session ${t} is not alive`};const s=r.reattach(n);return{handle:Za(r,()=>this.sessions.delete(t)),scrollback:s}}async closeTerminal(t){const n=this.sessions.get(t);n&&(n.closed=!0,this.sessions.delete(t))}}class t2{constructor(){X(this,"projects",[]);X(this,"contexts",new Map)}async listProjects(){return[...this.projects]}async createProject(t,n){if(this.projects.some(s=>s.root===n))throw{code:"INVALID",message:`a project already exists at ${n} for this remote`};const r={id:`mock-project-${Math.random().toString(36).slice(2,10)}`,name:t,root:n,remote:{kind:"local"},createdAt:Date.now()};return this.projects.push(r),r}async openProject(t){const n=this.projects.find(r=>r.id===t);if(!n)throw{code:"NOT_FOUND",message:`project ${t} not found`};return n}async closeProject(){}async readProjectContext(t){if(!this.projects.some(n=>n.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};return this.contexts.get(t)??""}async updateProjectContext(t,n){if(!this.projects.some(r=>r.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};this.contexts.set(t,n)}}class n2{constructor(){X(this,"store",new Map)}getProjectLayouts(t){if(!this.store.has(t)){const n=`layout-default-${Math.random().toString(36).slice(2,8)}`;this.store.set(t,{activeId:n,layouts:[{id:n,name:"Default",kind:"terminal",tree:Lo()}]})}return this.store.get(t)}getActiveTree(t){const n=this.getProjectLayouts(t),r=n.layouts.find(s=>s.id===n.activeId);return r?r.tree:Lo()}getTree(t,n){if(!n)return this.getActiveTree(t);const s=this.getProjectLayouts(t).layouts.find(i=>i.id===n);return s?s.tree:Lo()}setTree(t,n,r){const s=this.getProjectLayouts(t),i=r??s.activeId,l=s.layouts.find(a=>a.id===i);l&&(l.tree=n)}async loadLayout(t,n){const r=this.getTree(t,n);return structuredClone(r)}async mutateLayout(t,n,r){const s=this.getTree(t,r),i=KE(s,n);return this.setTree(t,i,r),structuredClone(i)}async listLayouts(t){const n=this.getProjectLayouts(t);return{layouts:n.layouts.map(s=>({id:s.id,name:s.name,kind:s.kind})),activeId:n.activeId}}async createLayout(t,n,r="terminal"){const s=this.getProjectLayouts(t),i=`layout-${Math.random().toString(36).slice(2,10)}`;return s.layouts.push({id:i,name:n,kind:r,tree:Lo()}),{layoutId:i}}async renameLayout(t,n,r){const i=this.getProjectLayouts(t).layouts.find(l=>l.id===n);i&&(i.name=r)}async deleteLayout(t,n){const r=this.getProjectLayouts(t),s=r.layouts.findIndex(i=>i.id===n);return s!==-1&&r.layouts.splice(s,1),r.activeId===n&&r.layouts.length>0&&(r.activeId=r.layouts[0].id),{activeId:r.activeId}}async setActiveLayout(t,n){const r=this.getProjectLayouts(t);return r.layouts.some(s=>s.id===n)&&(r.activeId=n),{activeId:r.activeId}}}const r2=[{hash:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",summary:"Merge feature into main",parents:["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","dddddddddddddddddddddddddddddddddddddddd"],refs:["main","HEAD"],author:"Alice",timestamp:17172e5},{hash:"dddddddddddddddddddddddddddddddddddddddd",summary:"Implement feature (step 2)",parents:["cccccccccccccccccccccccccccccccccccccccc"],refs:["feature"],author:"Bob",timestamp:17171e5},{hash:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",summary:"Hotfix on main",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Alice",timestamp:171709e4},{hash:"cccccccccccccccccccccccccccccccccccccccc",summary:"Implement feature (step 1)",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Bob",timestamp:171708e4},{hash:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",summary:"Initial commit",parents:[],refs:["tag: v1.0"],author:"Alice",timestamp:1717e6}];class s2{constructor(){X(this,"projects",new Map)}getState(t){return this.projects.has(t)||this.projects.set(t,this._seedState()),this.projects.get(t)}_seedState(){const t=new Map;return t.set("src/main.rs",!1),t.set("README.md",!1),{files:t,branches:["main"],current:"main",log:[],commitSeq:0}}async init(t){this.projects.has(t)||this.projects.set(t,this._seedState())}async status(t){const n=this.getState(t);return Array.from(n.files.entries()).map(([r,s])=>({path:r,staged:s}))}async stage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!0)}async unstage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!1)}async commit(t,n){const r=this.getState(t);r.commitSeq+=1;const s={hash:`mock-${r.commitSeq}`,summary:n.split(` -`)[0]};for(const[i,l]of Array.from(r.files.entries()))l&&r.files.delete(i);return r.log.unshift(s),s}async branches(t){const n=this.getState(t);return{branches:[...n.branches],current:n.current}}async checkout(t,n){const r=this.getState(t);r.branches.includes(n)||r.branches.push(n),r.current=n}async log(t,n){return this.getState(t).log.slice(0,n)}async graph(t,n){return r2.slice(0,n)}}class i2{async connect(){}}class l2{constructor(){X(this,"open",new Set);X(this,"listeners",new Set)}async openViewWindow(t){this.open.add(t)}async closeViewWindow(t){this.open.delete(t)&&this.emit({panel:t})}async listOpenViewWindows(){return[...this.open].map(t=>({panel:t,label:t,visible:!0}))}async onViewWindowClosed(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}simulateOsClose(t){this.open.delete(t),this.emit({panel:t})}emit(t){for(const n of this.listeners)n(t)}}class o2{constructor(){X(this,"focused",null);X(this,"listeners",new Set)}async setFocusedProject(t){this.focused=t;for(const n of this.listeners)n(t)}async getFocusedProject(){return this.focused}async onFocusedProjectChanged(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}}const wu=[{id:"mock-claude",name:"Claude Code",command:"claude",args:[],contextInjection:{strategy:"conventionFile",target:"CLAUDE.md"},detect:"claude --version",cwdTemplate:"{projectRoot}"},{id:"mock-codex",name:"OpenAI Codex CLI",command:"codex",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"codex --version",cwdTemplate:"{projectRoot}"},{id:"mock-opencode",name:"OpenCode + llama.cpp",command:"opencode",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"opencode --version",cwdTemplate:"{projectRoot}",structuredAdapter:"openCode",opencode:{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}],a2=[{providerId:"anthropic",displayName:"Anthropic",models:["claude-sonnet-5","claude-opus-4-8","claude-haiku-4-5"]},{providerId:"openrouter",displayName:"OpenRouter",models:["openrouter/auto","qwen/qwen3-coder"]}];class c2{constructor(){X(this,"profiles",[]);X(this,"configured",!1);X(this,"cloneCounter",0)}async firstRunState(){return{isFirstRun:!this.configured,referenceProfiles:structuredClone(wu)}}async referenceProfiles(){return structuredClone(wu)}async detectProfiles(t){return t.map(n=>({profile:n,available:n.command==="claude"}))}async listProfiles(){return structuredClone(this.profiles)}async saveProfile(t){const n=this.profiles.findIndex(r=>r.id===t.id);return n>=0?this.profiles[n]=t:this.profiles.push(t),this.configured=!0,structuredClone(t)}async deleteProfile(t){this.profiles=this.profiles.filter(n=>n.id!==t)}async configureProfiles(t){return this.profiles=structuredClone(t),this.configured=!0,structuredClone(t)}async cloneOpenCodeProfileFromSeed(t={}){const n=wu.find(r=>r.structuredAdapter==="openCode");if(!n)throw new Error("no OpenCode seed profile");return this.cloneCounter+=1,structuredClone({...n,id:`mock-opencode-clone-${this.cloneCounter}`,name:t.name??`${n.name} (copy ${this.cloneCounter})`,opencode:t.opencode??n.opencode})}async listOpenCodeProviders(){return structuredClone(a2)}async saveOpenCodeProviderProfile(t){const n={...structuredClone(t.profile),opencode:void 0,opencodeProvider:{providerId:t.providerId,model:t.model,apiKeyRef:`mock-secret-${t.profile.id}`,custom:t.custom}},r=this.profiles.findIndex(s=>s.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}}class u2{constructor(){X(this,"servers",[]);X(this,"inUse",new Set)}async listModelServers(){return structuredClone(this.servers)}async saveModelServer(t){const n=this.servers.findIndex(r=>r.id===t.id);return n>=0?this.servers[n]=structuredClone(t):this.servers.push(structuredClone(t)),structuredClone(t)}async deleteModelServer(t){if(this.inUse.has(t))throw{code:"model_server_in_use",message:"A profile still references this server."};this.servers=this.servers.filter(n=>n.id!==t)}async previewModelServerCommand(t){if(!t.modelSource)throw{code:"INVALID",message:"model.source missing"};const n=t.binaryPath&&t.binaryPath.trim().length>0?t.binaryPath:"llama-server",r=[];t.modelSource.type==="localPath"?r.push("--model",t.modelSource.path):r.push("-hf",t.modelSource.repo),r.push("--port",String(t.port),"--host",t.host),t.gpuLayers!==void 0&&r.push("-ngl",String(t.gpuLayers)),t.contextSize!==void 0&&r.push("-c",String(t.contextSize)),t.jinja&&r.push("--jinja"),r.push(...t.args);const s=[n,...r].map(i=>/\s/.test(i)?`'${i}'`:i).join(" ");return{command:n,args:r,display:s}}markInUse(t){this.inUse.add(t)}}const d2={mode:"localOnly",autoStart:!1,port:17373,trustedProxies:[]},h2=["192.168.1.42","10.0.0.17"];function Ms(e){throw{code:"INVALID",message:e}}class f2{constructor(){X(this,"settings",structuredClone(d2));X(this,"current",{state:"stopped"});X(this,"handlers",new Set)}async getExposureSettings(){return structuredClone(this.settings)}async saveExposureSettings(t){this.validate(t),this.settings=structuredClone(t)}async previewExposure(t){this.validate(t);const n=[];t.mode==="remoteProxyOtherMachine"&&t.trustedProxies.length===0&&n.push({code:"missingTrustedProxy",message:"Add the IP address or CIDR of the reverse proxy that connects to this server."});const r=t.mode==="remoteProxyOtherMachine"?t.lanBindAddress:"127.0.0.1",s=t.mode!=="localOnly"&&r?`http://${r}:${t.port}`:void 0;return{candidateLanAddresses:[...h2],upstreamUrl:s,warnings:n}}async status(){return structuredClone(this.current)}async start(){this.validate(this.settings);const t=await this.previewExposure(this.settings);return this.emit({state:"running",localUrl:`http://127.0.0.1:${this.settings.port}`,publicUrl:this.settings.mode==="localOnly"?void 0:this.settings.publicOrigin,upstreamUrl:t.upstreamUrl}),structuredClone(this.current)}async stop(){return this.emit({state:"stopped"}),structuredClone(this.current)}async onStatusChanged(t){return this.handlers.add(t),()=>this.handlers.delete(t)}setStatus(t){this.emit(t)}emit(t){this.current=t;for(const n of this.handlers)n(structuredClone(t))}validate(t){if(t.mode!=="localOnly"){const n=t.publicOrigin;n||Ms("remote exposure requires publicOrigin"),n.startsWith("https://")||Ms("remote exposure requires publicOrigin to start with https://"),n.includes("*")&&Ms("publicOrigin must be exact, not a wildcard"),n.endsWith("/")&&Ms("publicOrigin must not end with '/'")}t.mode==="remoteProxyOtherMachine"&&(t.lanBindAddress||Ms("remoteProxyOtherMachine requires lanBindAddress"),t.trustedProxies.length===0&&Ms("remoteProxyOtherMachine requires at least one trustedProxies entry"))}}class p2{constructor(t){X(this,"templates",[]);X(this,"seq",0);this.agentGateway=t}async listTemplates(){return structuredClone(this.templates)}async createTemplate(t){this.seq+=1;const n={id:`mock-template-${this.seq}`,name:t.name,contentMd:t.content,version:1,defaultProfileId:t.defaultProfileId};return this.templates.push(n),structuredClone(n)}async updateTemplate(t,n){const r=this.templates.findIndex(s=>s.id===t);if(r===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};return this.templates[r]={...this.templates[r],contentMd:n,version:this.templates[r].version+1},structuredClone(this.templates[r])}async deleteTemplate(t){const n=this.templates.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};this.templates.splice(n,1)}async createAgentFromTemplate(t,n,r){const s=this.templates.find(f=>f.id===n);if(!s)throw{code:"NOT_FOUND",message:`template ${n} not found`};const i=r?.synchronized??!0,l=r?.name??s.name,a=up(l)||"agent",c=new Set(this.agentGateway._rawAgents(t).map(f=>f.contextPath));let u=`agents/${a}.md`,h=2;for(;c.has(u);)u=`agents/${a}-${h}.md`,h+=1;const d={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:l,contextPath:u,profileId:s.defaultProfileId,origin:{type:"fromTemplate",templateId:n,syncedTemplateVersion:s.version},synchronized:i,skills:[]};return this.agentGateway._insertAgent(t,d,s.contentMd),structuredClone(d)}async detectDrift(t){const n=this.agentGateway._rawAgents(t),r=[];for(const s of n){if(!s.synchronized||s.origin.type!=="fromTemplate")continue;const{templateId:i,syncedTemplateVersion:l}=s.origin,a=this.templates.find(c=>c.id===i);a&&a.version>l&&r.push({agentId:s.id,from:l,to:a.version})}return r}async syncAgent(t,n){const s=this.agentGateway._rawAgents(t).find(a=>a.id===n);if(!s||!s.synchronized||s.origin.type!=="fromTemplate")return{synced:!1,version:null};const{templateId:i}=s.origin,l=this.templates.find(a=>a.id===i);return l?(this.agentGateway._updateAgent(t,n,{origin:{type:"fromTemplate",templateId:i,syncedTemplateVersion:l.version}},l.contentMd),{synced:!0,version:l.version}):{synced:!1,version:null}}}class m2{constructor(t){X(this,"global",[]);X(this,"byProject",new Map);X(this,"seq",0);this.agentGateway=t}bucket(t,n){if(n==="global")return this.global;let r=this.byProject.get(t);return r||(r=[],this.byProject.set(t,r)),r}async listSkills(t,n){return structuredClone(this.bucket(t,n))}async createSkill(t){this.seq+=1;const n={id:`mock-skill-${this.seq}`,name:t.name,contentMd:t.content,scope:t.scope};return this.bucket(t.projectId,t.scope).push(n),structuredClone(n)}async updateSkill(t,n,r,s){const i=this.bucket(t,n),l=i.findIndex(a=>a.id===r);if(l===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};return i[l]={...i[l],contentMd:s},structuredClone(i[l])}async deleteSkill(t,n,r){const s=this.bucket(t,n),i=s.findIndex(l=>l.id===r);if(i===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};s.splice(i,1)}async assignSkill(t,n,r,s){const i=this.agentGateway._rawAgents(t).find(l=>l.id===n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};i.skills.some(l=>l.skillId===r)||this.agentGateway._setSkills(t,n,[...i.skills,{skillId:r,scope:s}])}async unassignSkill(t,n,r){const s=this.agentGateway._rawAgents(t).find(i=>i.id===n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.agentGateway._setSkills(t,n,s.skills.filter(i=>i.skillId!==r))}}class g2{constructor(){X(this,"byProject",new Map)}bucket(t){let n=this.byProject.get(t);return n||(n=new Map,this.byProject.set(t,n)),n}notFound(t,n){return{code:"NOT_FOUND",message:`memory ${t} not found in project ${n}`}}async listMemories(t){return structuredClone([...this.bucket(t).values()])}async getMemory(t,n){const r=this.bucket(t).get(n);if(!r)throw this.notFound(n,t);return structuredClone(r)}async createMemory(t){const n={name:t.name,description:t.description,type:t.type,content:t.content};return this.bucket(t.projectId).set(up(t.name),n),structuredClone(n)}async updateMemory(t,n,r,s,i){const l=this.bucket(t),a=l.get(n);if(!a)throw this.notFound(n,t);const c={...a,description:r,type:s,content:i};return l.set(n,c),structuredClone(c)}async deleteMemory(t,n){if(!this.bucket(t).delete(n))throw this.notFound(n,t)}async readIndex(t){return[...this.bucket(t).entries()].map(([n,r])=>({slug:n,title:r.name,hook:r.description,type:r.type}))}async resolveLinks(t,n){const r=this.bucket(t),s=r.get(n);if(!s)throw this.notFound(n,t);const i=new Set;for(const l of s.content.matchAll(/\[\[([^\]]+)\]\]/g)){const a=l[1].trim();a!==n&&r.has(a)&&i.add(a)}return[...i]}async recall(t,n,r){const s=await this.readIndex(t),i=Math.max(0,Math.floor(r/16));return s.slice(0,i)}}class x2{constructor(t,n=[]){X(this,"profiles",new Map);X(this,"engines");this.engines={recommendedOnnx:[{id:"e5-small",displayName:"E5 Small (multilingual)",dimension:384,approxSizeMb:120,recommended:!0},{id:"bge-small",displayName:"BGE Small",dimension:384,approxSizeMb:130,recommended:!1}],ollamaDetected:!1,onnxCachedModels:[],vectorHttpEnabled:!0,vectorOnnxEnabled:!0,...t};for(const r of n)this.profiles.set(r.id,r)}async listEmbedderProfiles(){return structuredClone([...this.profiles.values()])}async saveEmbedderProfile(t){if(!t.id.trim()||!t.name.trim())throw{code:"INVALID",message:"embedder profile id/name must not be empty"};if(t.dimension<=0)throw{code:"INVALID",message:"embedder profile dimension must be > 0"};return this.profiles.set(t.id,structuredClone(t)),structuredClone(t)}async deleteEmbedderProfile(t){this.profiles.delete(t)}async describeEmbedderEngines(){return structuredClone(this.engines)}}class v2{constructor(){X(this,"interrupts",[]);X(this,"delivered",[]);X(this,"frontAttached",[]);X(this,"cancelledResumes",[]);X(this,"resumeArmings",[]);X(this,"cancelResumeResult",!0)}async interrupt(t,n){this.interrupts.push({projectId:t,agentId:n})}async delegationDelivered(t,n,r){this.delivered.push({projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){this.frontAttached.push({agentId:t,attached:n})}async cancelResume(t){return this.cancelledResumes.push(t),this.cancelResumeResult}async setResumeAt(t,n){this.resumeArmings.push({agentId:t,resetsAtMs:n})}}class _2{constructor(){X(this,"devices",[]);X(this,"issued",0);X(this,"_issuedCodes",[])}_setDevices(t){this.devices=structuredClone(t)}async listDevices(){return structuredClone(this.devices)}async createPairingCode(){const t=(268435456+this.issued++).toString(16).toUpperCase().slice(0,8);this._issuedCodes.push(t);const n=600;return{code:t,expiresAtMs:Date.now()+n*1e3,ttlSeconds:n}}async renameDevice(t,n){const r=this.devices.find(s=>s.deviceId===t);if(!r)throw{code:"NOT_FOUND",message:`unknown device ${t}`};r.name=n}async revokeDevice(t){this.devices=this.devices.filter(n=>n.deviceId!==t)}async revokeAllDevices(){this.devices=[]}}class y2{constructor(){X(this,"docs",new Map);X(this,"systemDocs",new Map);X(this,"systemRuntime",new Map);X(this,"mcpCatalogue",{readOnlyTools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read","idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"],writeActionTools:["idea_ask_agent","idea_run_in_background","idea_launch_agent","idea_stop_agent","idea_update_context","idea_context_propose","idea_memory_write","idea_workstate_set","idea_create_skill","idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]});X(this,"mcpDocs",new Map)}doc(t){return this.docs.has(t)||this.docs.set(t,{version:1,agents:[]}),this.docs.get(t)}async getProjectPermissions(t){return structuredClone(this.doc(t))}async updateProjectPermissions(t,n){const r=this.doc(t);return n?r.projectDefaults=structuredClone(n):delete r.projectDefaults,structuredClone(r)}async updateAgentPermissions(t,n,r){const s=this.doc(t),i=(s.agents??[]).filter(l=>l.agentId!==n);return r&&i.push({agentId:n,permissions:structuredClone(r)}),s.agents=i,structuredClone(s)}async resolveAgentPermissions(t,n){const r=this.doc(t),s=r.projectDefaults,i=r.agents?.find(l=>l.agentId===n)?.permissions;return!s&&!i?null:{rules:[...s?.rules??[],...i?.rules??[]],fallback:C2(s?.fallback,i?.fallback)}}systemDoc(t){return this.systemDocs.has(t)||this.systemDocs.set(t,{version:1,agents:[]}),this.systemDocs.get(t)}async getProjectSystemPermissions(t){return structuredClone(this.systemDoc(t))}async updateProjectSystemPermissions(t,n){const r=this.systemDoc(t);return n&&Object.keys(n).length>0?r.projectDefault=structuredClone(n):delete r.projectDefault,structuredClone(r)}async updateAgentSystemPermissions(t,n,r){const s=this.systemDoc(t),i=(s.agents??[]).filter(l=>l.agentId!==n);return r&&Object.keys(r).length>0&&i.push({agentId:n,permissions:structuredClone(r)}),s.agents=i,structuredClone(s)}async resolveAgentSystemPermissions(t,n){const r=this.systemRuntime.get(n);if(r)return structuredClone(r);const s=this.systemDoc(t),i=s.agents?.find(l=>l.agentId===n)?.permissions.network??s.projectDefault?.network??null;return{wanted:i,effective:i??"ask",runtimeLock:{state:"none"},control:{mode:"editable"},runtimeControl:{mode:"readOnly",reason:"No active runtime network permission state is currently observed."}}}setResolvedAgentSystemPermissions(t,n){this.systemRuntime.set(t,structuredClone(n))}mcpDoc(t){return this.mcpDocs.has(t)||this.mcpDocs.set(t,{version:1,catalogue:this.mcpCatalogue,projectDefault:null,agents:[]}),this.mcpDocs.get(t)}async getMcpToolPermissions(t){return structuredClone(this.mcpDoc(t))}async updateProjectMcpToolPermissions(t,n){const r=this.mcpDoc(t);return r.projectDefault=n?structuredClone(n):null,structuredClone(r)}async updateAgentMcpToolPermissions(t,n,r){const s=this.mcpDoc(t);return s.agents=s.agents.filter(i=>i.agentId!==n),r&&s.agents.push({agentId:n,policy:structuredClone(r)}),structuredClone(s)}}class b2{constructor(){X(this,"states",new Map)}_setProjectWorkState(t,n){this.states.set(t,ap(n))}async getProjectWorkState(t){return structuredClone(this.states.get(t)??{agents:[],conversations:[]})}async cancelBackgroundTask(t){}async retryBackgroundTask(t){}}class w2{constructor(){X(this,"threads",new Map)}key(t,n){return`${t}::${n}`}_setTurns(t,n,r){this.threads.set(this.key(t,n),r.map(s=>structuredClone(s)))}async readPage(t,n,r){const s=this.threads.get(this.key(t,n))??[],i=s.length,l=r?.limit,a=Math.min(Math.max(l&&l>0?l:50,1),200),c=r?.direction??"backward",u=r?.anchor;let h,d,f;if(u===void 0)c==="forward"?(h=0,d=Math.min(a,i),f=d0);else{const x=s.findIndex(w=>w.id===u);x===-1?(h=0,d=0,f=!1):c==="forward"?(h=x+1,d=Math.min(h+a,i),f=d0)}const p=s.slice(h,d).map(x=>structuredClone(x)),m=p.at(-1);return{turns:p,hasMore:f,...m?{nextAnchor:m.id}:{}}}}class S2{constructor(t){X(this,"tickets",new Map);X(this,"carnets",new Map);X(this,"counters",new Map);X(this,"sprints",new Map);X(this,"sprintCounters",new Map);X(this,"chatSessions",new Map);X(this,"chatCounter",0);this.system=t}_seedTicket(t,n){const r=structuredClone(n);return r.sprintId===void 0&&(r.sprintId=null),this.projectTickets(t).set(r.ref,r),this.counters.set(t,Math.max(this.counters.get(t)??0,r.number)),structuredClone(r)}_seedSprint(t,n){const r={status:"planned",ticketCount:0,version:1,...n};return this.projectSprints(t).set(r.id,r),structuredClone(r)}projectSprints(t){let n=this.sprints.get(t);return n||(n=new Map,this.sprints.set(t,n)),n}recountSprints(t){const n=this.projectSprints(t),r=new Map;for(const s of this.projectTickets(t).values())s.sprintId&&r.set(s.sprintId,(r.get(s.sprintId)??0)+1);for(const s of n.values())s.ticketCount=r.get(s.id)??0}projectTickets(t){let n=this.tickets.get(t);return n||(n=new Map,this.tickets.set(t,n)),n}projectCarnets(t){let n=this.carnets.get(t);return n||(n=new Map,this.carnets.set(t,n)),n}require(t,n){const r=this.projectTickets(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`ticket ${n} not found`};return r}guard(t,n){if(t.version!==n)throw{code:"INVALID",message:`issue version conflict: expected ${n}, actual ${t.version}`}}async create(t,n){const r=(this.counters.get(t)??0)+1;this.counters.set(t,r);const s=Date.now(),i={id:`mock-ticket-${t}-${r}`,ref:`#${r}`,number:r,title:n.title,description:n.description??"",status:n.status??"open",priority:n.priority??"medium",sprintId:null,links:[],assignedAgentIds:[...n.assignedAgentIds??[]],createdBy:{kind:"user"},updatedBy:{kind:"user"},createdAt:s,updatedAt:s,version:1};return this.projectTickets(t).set(i.ref,i),this.system?.emit({type:"issueCreated",issueId:i.id,issueRef:i.ref}),structuredClone(i)}async read(t,n,r=!1){const s=structuredClone(this.require(t,n));return r&&(s.carnet=this.projectCarnets(t).get(n)??""),s}async list(t,n){const r=n??{},s=r.text?.trim().toLowerCase(),i=r.statuses??[],l=r.priorities??[];let a=[...this.projectTickets(t).values()].filter(d=>i.length===0||i.includes(d.status)).filter(d=>l.length===0||l.includes(d.priority)).filter(d=>!r.assignedAgentId||d.assignedAgentIds.includes(r.assignedAgentId)).filter(d=>!s||d.title.toLowerCase().includes(s)||d.description.toLowerCase().includes(s));a=r.sort?QE(a,r.sort):a.sort((d,f)=>f.number-d.number);const c=Number.parseInt(r.cursor??"0",10)||0,u=Math.min(Math.max(r.limit??100,1),500),h=Math.min(a.length,c+u);return{items:a.slice(c,h).map(d=>({ref:d.ref,path:`.ideai/tickets/${d.number}.md`,title:d.title,status:d.status,priority:d.priority,sprintId:d.sprintId??null,assignedAgentIds:[...d.assignedAgentIds],updatedAt:d.updatedAt})),...hc.targetRef===r&&c.kind===s)||l.links.push({targetRef:r,kind:s}),this.bump(l),this.system?.emit({type:"issueLinked",issueRef:n,target:r,kind:s,version:l.version}),structuredClone(l)}async unlink(t,n,r,s,i){const l=this.require(t,n);return this.guard(l,s),l.links=l.links.filter(a=>a.targetRef!==r||i!==void 0&&a.kind!==i),this.bump(l),this.system?.emit({type:"issueUnlinked",issueRef:n,target:r,kind:i??"relatesTo",version:l.version}),structuredClone(l)}async assign(t,n,r,s,i){const l=this.require(t,n);this.guard(l,i);const a=l.assignedAgentIds.includes(r);return s&&!a&&l.assignedAgentIds.push(r),!s&&a&&(l.assignedAgentIds=l.assignedAgentIds.filter(c=>c!==r)),this.bump(l),this.system?.emit({type:s?"issueAgentAssigned":"issueAgentUnassigned",issueRef:n,agentId:r,version:l.version}),structuredClone(l)}async listSprints(t){return this.recountSprints(t),[...this.projectSprints(t).values()].sort((n,r)=>n.order-r.order).map(n=>structuredClone(n))}async setTicketSprint(t,n,r,s){const i=this.require(t,n);if(this.guard(i,s),r!==null&&!this.projectSprints(t).has(r))throw{code:"NOT_FOUND",message:`sprint ${r} not found`};const l=i.sprintId??null;return i.sprintId=r,this.bump(i),this.recountSprints(t),this.system?.emit({type:"issueSprintChanged",issueRef:n,from:l,to:r,version:i.version}),structuredClone(i)}async createSprint(t,n){const r=this.projectSprints(t),s=(this.sprintCounters.get(t)??0)+1;this.sprintCounters.set(t,s);const i=r.size===0?1:Math.max(...[...r.values()].map(a=>a.order))+1,l={id:`mock-sprint-${t}-${s}`,order:i,name:n,status:"planned",ticketCount:0,version:1};return r.set(l.id,l),this.system?.emit({type:"sprintCreated",sprintId:l.id,order:l.order}),structuredClone(l)}async renameSprint(t,n,r,s){const i=this.requireSprint(t,n);return this.guardSprint(i,s),i.name=r,i.version+=1,this.system?.emit({type:"sprintRenamed",sprintId:n,name:r,version:i.version}),structuredClone(i)}async reorderSprints(t,n){const r=this.projectSprints(t);for(const i of n)this.requireSprint(t,i);const s=[...r.values()].filter(i=>!n.includes(i.id)).sort((i,l)=>i.order-l.order).map(i=>i.id);return[...n,...s].forEach((i,l)=>{const a=r.get(i);a&&(a.order=l+1,this.system?.emit({type:"sprintReordered",sprintId:i,order:a.order,version:a.version}))}),this.listSprints(t)}async deleteSprint(t,n){this.requireSprint(t,n);for(const r of this.projectTickets(t).values())r.sprintId===n&&(r.sprintId=null,this.bump(r),this.system?.emit({type:"issueSprintChanged",issueRef:r.ref,from:n,to:null,version:r.version}));this.projectSprints(t).delete(n),this.system?.emit({type:"sprintDeleted",sprintId:n})}async openTicketChat(t,n,r){this.require(t,n);const s=`mock-ticket-chat-${++this.chatCounter}`;return this.chatSessions.set(n,s),this.system?.emit({type:"ticketAssistantOpened",issueRef:n,profileId:r}),{sessionId:s,requester:"ticket-assistant",issueRef:n}}async closeTicketChat(t,n){this.chatSessions.delete(n)&&this.system?.emit({type:"ticketAssistantClosed",issueRef:n})}async sendTicketChat(t,n,r){if(![...this.chatSessions.values()].includes(t))throw{code:"NOT_FOUND",message:`chat session ${t} not found`};const s=`Assistant: reçu « ${n} ».`,i=[{kind:"textDelta",text:"Assistant: reçu "},{kind:"textDelta",text:`« ${n} ».`},{kind:"final",content:s}];for(const l of i)await Promise.resolve(),r(l)}requireSprint(t,n){const r=this.projectSprints(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`sprint ${n} not found`};return r}guardSprint(t,n){if(t.version!==n)throw{code:"INVALID",message:`sprint version conflict: expected ${n}, actual ${t.version}`}}}class k2{constructor(){X(this,"store",new Map)}read(t){const n=this.store.get(t);if(n===void 0)return null;try{return JSON.parse(n)}catch{return this.store.delete(t),null}}write(t,n){try{this.store.set(t,JSON.stringify(n))}catch{}}remove(t){this.store.delete(t)}}function C2(e,t){const n={allow:0,ask:1,deny:2},r=e??t??"ask";return t&&n[t]>=n[r]?t:r}class j2{constructor(){X(this,"plugins",[]);X(this,"seq",0)}summaryFor(t){return{topLevelMenus:0,menuItems:0,layouts:0,mcpServers:0}}_seedPlugin(t){this.plugins.push(t)}async listPlugins(){return structuredClone(this.plugins)}async reviewPackage(t){this.seq+=1;const n=t.path.split("/").pop()??t.path;return{id:`mock.plugin.${this.seq}`,displayName:n.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",description:`Reviewed from ${t.sourceKind}: ${t.path}`,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`),issues:[],installable:!0}}async install(t,n){this.seq+=1;const r=n.split("/").pop()??n,s={id:`mock.plugin.${this.seq}`,displayName:r.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",sourceKind:t,sourceLabel:n,lifecycleState:"enabled",enabled:!0,pendingUninstall:!1,restartRequired:!0,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`)};return this.plugins.push(s),{plugin:structuredClone(s),restartRequired:!0}}installFromArchive(t){return this.install("archive",t)}installFromDirectory(t){return this.install("directory",t)}async setEnabled(t,n){const r=this.plugins.find(i=>i.id===t);if(!r)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};const s=n?"enabled":"disabled";return r.enabled=n,r.lifecycleState=s,r.restartRequired=!0,structuredClone(r)}async uninstall(t){const n=this.plugins.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};return this.plugins.splice(n,1),{pluginId:t,restartRequired:!0}}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){}}function N2(){const e=new ZE,t=new JE;return{system:t,agent:e,input:new v2,terminal:new e2,project:new t2,layout:new n2,git:new s2,remote:new i2,profile:new c2,modelServer:new u2,desktopServer:new f2,template:new p2(e),skill:new m2(e),memory:new g2,embedder:new x2,device:new _2,permission:new y2,workState:new b2,conversation:new w2,ticket:new S2(t),window:new l2,focusedProject:new o2,uiPreferences:new k2,plugin:new j2}}function ow(){const e=globalThis.fetch;return typeof e=="function"?e.bind(globalThis):e}function E2(e,t){if(e&&typeof e=="object"){const n=e,r=typeof n.code=="string"?n.code:void 0,s=typeof n.message=="string"?n.message:void 0;if(r||s)return{code:r??"ERROR",message:s??t}}return{code:"TRANSPORT_ERROR",message:t}}class P2{constructor(t){X(this,"baseUrl");X(this,"token");X(this,"fetchImpl");X(this,"onUnauthorized");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.onUnauthorized=t.onUnauthorized,this.fetchImpl=t.fetchImpl??ow()}invoke(t,n={}){return this.request("POST","/api/invoke",{command:t,args:n},`command '${t}'`)}async request(t,n,r,s=`${t} ${n}`){const i={"Content-Type":"application/json"};this.token&&(i.Authorization=`Bearer ${this.token}`);let l;try{l=await this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:i,body:r===void 0?void 0:JSON.stringify(r),credentials:"same-origin"})}catch(c){throw{code:"TRANSPORT_ERROR",message:`HTTP request for ${s} failed: ${String(c)}`}}if(!l.ok){l.status===401&&this.onUnauthorized?.();let c;try{c=await l.json()}catch{c=void 0}throw E2(c,`${s} failed (HTTP ${l.status})`)}let a;try{a=await l.json()}catch{a=void 0}return a}}function A2(e){let t="";for(let n=0;naw(i.bytesBase64)),n=t.reduce((i,l)=>i+l.length,0),r=new Uint8Array(n);let s=0;for(const i of t)r.set(i,s),s+=i.length;return r}class cw{constructor(t){X(this,"wsUrl");X(this,"token");X(this,"socketFactory");X(this,"reconnectBaseMs");X(this,"reconnectMaxMs");X(this,"setTimeoutImpl");X(this,"clearTimeoutImpl");X(this,"onReconnectFailed");X(this,"socket",null);X(this,"opening",null);X(this,"disposed",!1);X(this,"everConnected",!1);X(this,"connState","connecting");X(this,"reconnectAttempt",0);X(this,"reconnectHandle",null);X(this,"outputSinks",new Map);X(this,"terminals",new Map);X(this,"pending",new Map);X(this,"domainEventHandler",null);X(this,"connListeners",new Set);this.wsUrl=t.wsUrl.replace(/\/+$/,""),this.token=t.token,this.socketFactory=t.socketFactory??(n=>new WebSocket(n)),this.reconnectBaseMs=t.reconnectBaseMs??500,this.reconnectMaxMs=t.reconnectMaxMs??1e4,this.setTimeoutImpl=t.setTimeoutImpl??((n,r)=>setTimeout(n,r)),this.clearTimeoutImpl=t.clearTimeoutImpl??(n=>clearTimeout(n)),this.onReconnectFailed=t.onReconnectFailed}getConnectionState(){return this.connState}onConnectionStateChange(t){return this.connListeners.add(t),()=>this.connListeners.delete(t)}setConnState(t){if(this.connState!==t){this.connState=t;for(const n of this.connListeners)n(t)}}setDomainEventHandler(t){this.domainEventHandler=t}clearDomainEventHandler(){this.domainEventHandler=null}setOutputSink(t,n){this.outputSinks.set(t,n)}removeOutputSink(t){this.outputSinks.delete(t)}async ensureConnected(){if(!this.socket)return this.opening?this.opening:this.connect()}connect(){return this.setConnState(this.everConnected?"reconnecting":"connecting"),this.opening=new Promise((t,n)=>{const r=this.token?`${this.wsUrl}${rx}?token=${encodeURIComponent(this.token)}`:`${this.wsUrl}${rx}`,s=this.socketFactory(r);s.onopen=()=>{this.socket=s,this.opening=null,this.everConnected=!0,this.reconnectAttempt=0,this.setConnState("connected"),t()},s.onerror=i=>{this.opening=null,n(i)},s.onclose=()=>this.handleSocketClosed(),s.onmessage=i=>this.handleMessage(i.data)}),this.opening}handleSocketClosed(){if(this.socket=null,this.opening=null,this.rejectAllPending({code:"WS_CLOSED",message:"socket closed"}),this.disposed){this.setConnState("closed");return}if(this.setConnState("reconnecting"),this.terminals.size>0)for(const t of this.terminals.values())t.onData(Su("déconnecté — reconnexion…"));this.needsReconnect()&&this.scheduleReconnect()}needsReconnect(){return this.terminals.size>0||this.domainEventHandler!==null}scheduleReconnect(){if(this.disposed||this.reconnectHandle)return;const t=Math.min(this.reconnectMaxMs,this.reconnectBaseMs*2**this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectHandle=this.setTimeoutImpl(()=>{this.reconnectHandle=null,this.reconnectNow()},t)}async reconnectNow(){if(!this.disposed)try{await this.connect(),await this.reattachAll()}catch{this.onReconnectFailed?.(),this.needsReconnect()&&this.scheduleReconnect()}}async reattachAll(){for(const[t,n]of this.terminals)try{const s=(await this.send("terminal.attach",{sessionId:t,lastSeq:n.lastSeq})).payload;n.onData(Su("reconnecté"));const i=lx(s);i.length>0&&n.onData(i),typeof s.nextSeq=="number"&&(n.lastSeq=Math.max(0,s.nextSeq-1))}catch{}}openTerminal(t){return this.attachInternal("terminal.open",{cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}launchAgent(t){return this.attachInternal("agent.launch",{projectId:t.projectId,agentId:t.agentId,nodeId:t.nodeId??null,rows:t.rows,cols:t.cols,conversationId:t.conversationId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}attachTerminal(t){return this.attachInternal("terminal.attach",{sessionId:t.sessionId,rows:t.rows,cols:t.cols,lastSeq:t.lastSeq??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:t.lastSeq??0},t.sessionId)}async attachInternal(t,n,r,s){const l=(await this.send(t,n)).payload,a=s??l.session.sessionId;return typeof l.nextSeq=="number"&&(r.lastSeq=Math.max(0,l.nextSeq-1)),this.terminals.set(a,r),this.setOutputSink(a,r.onData),{sessionId:a,scrollback:lx(l),assignedConversationId:l.assignedConversationId,status:l.status}}async detachTerminal(t){this.removeTerminal(t),await this.sendFireAndForget("terminal.detach",{sessionId:t})}async closeTerminalSession(t){this.removeTerminal(t),await this.send("terminal.close",{sessionId:t})}removeTerminal(t){this.terminals.delete(t),this.outputSinks.delete(t)}async send(t,n){await this.ensureConnected();const r=this.socket;if(!r)throw{code:"WS_CLOSED",message:"socket not connected"};const s=ix(),i={id:s,kind:t,payload:n},l=new Promise((a,c)=>{this.pending.set(s,{resolve:a,reject:c})});return r.send(JSON.stringify(i)),l}async sendFireAndForget(t,n){await this.ensureConnected();const s={id:ix(),kind:t,payload:n};this.socket?.send(JSON.stringify(s))}static encodeInput(t){return A2(t)}disconnect(){this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disconnected"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null;const t=this.socket;t&&(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close()),this.socket=null,this.opening=null,this.everConnected=!1,this.reconnectAttempt=0,this.setConnState("closed")}dispose(){this.disposed=!0,this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disposed"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null,this.socket?.close(),this.socket=null,this.opening=null,this.setConnState("closed")}rejectAllPending(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}switch(n.kind){case"terminal.output":{const r=n.payload,s=this.terminals.get(r.sessionId);s&&typeof r.seq=="number"&&(s.lastSeq=r.seq);const i=this.outputSinks.get(r.sessionId);i&&i(aw(r.bytesBase64));return}case"terminal.status":{const r=n.payload;this.handleStatus(r);return}case"event.domain":{this.domainEventHandler?.(n.payload);return}}if(n.replyTo){const r=this.pending.get(n.replyTo);r&&(this.pending.delete(n.replyTo),n.kind==="error"?r.reject(n.payload):r.resolve(n))}}handleStatus(t){const n=this.terminals.get(t.sessionId);if(n)if(t.status==="exited"||t.status==="closed"){const r=t.exitCode;n.onData(Su(r==null?"session terminée":`session terminée (code ${r})`)),n.onStatus?.(t.status,t.exitCode),this.removeTerminal(t.sessionId)}else n.onStatus?.(t.status,t.exitCode)}}const ku="idea.web.paired";function L2(){const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n),removeItem:t=>void e.delete(t)}}function D2(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return L2()}function R2(){return typeof window<"u"&&window.location?window.location.origin:"http://localhost"}const M2={invalidOrExpired:"Code invalide ou expiré.",invalidName:"Nom d'appareil invalide (1 à 40 caractères). Le code reste valable.",rateLimited:"Trop de tentatives. Réessayez dans quelques minutes avec un nouveau code.",pairingFailed:"Échec de l'appairage."};function I2(e,t){const n=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;let r;return n==="invalid_or_expired"?r="invalidOrExpired":n==="invalid_name"?r="invalidName":n==="rate_limited"||t===429?r="rateLimited":t===401||t===403?r="invalidOrExpired":r="pairingFailed",{code:r,message:M2[r]}}class O2{constructor(t={}){X(this,"baseUrl");X(this,"fetchImpl");X(this,"store");X(this,"unauthorizedHandlers",new Set);this.baseUrl=(t.baseUrl??R2()).replace(/\/+$/,""),this.fetchImpl=t.fetchImpl??ow(),this.store=t.store??D2()}isPaired(){return this.store.getItem(ku)==="1"}markPaired(){this.store.setItem(ku,"1")}forget(){this.store.removeItem(ku)}async logout(){try{await this.fetchImpl(`${this.baseUrl}/api/logout`,{method:"POST",credentials:"same-origin"})}catch{}finally{this.forget()}}async pair(t,n){let r;try{r=await this.fetchImpl(`${this.baseUrl}/api/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,name:n})})}catch(s){throw{code:"TRANSPORT_ERROR",message:`Impossible de joindre le serveur : ${String(s)}`}}if(!r.ok){let s;try{s=await r.json()}catch{s=void 0}throw I2(s,r.status)}this.markPaired()}notifyUnauthorized(){this.forget();for(const t of this.unauthorizedHandlers)t()}onUnauthorized(t){return this.unauthorizedHandlers.add(t),()=>this.unauthorizedHandlers.delete(t)}}let Cu=null;function uw(){return Cu||(Cu=new O2),Cu}let dp=null;function B2(e){dp=e}function Bh(){return dp}function ox(){dp?.disconnect()}class z2{constructor(t){this.http=t}async listDevices(){return(await this.http.request("GET","/api/devices")).devices}createPairingCode(){return this.http.request("POST","/api/pairing-code")}renameDevice(t,n){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/rename`,{name:n})}revokeDevice(t){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/revoke`)}revokeAllDevices(){return this.http.request("POST","/api/devices/revoke-all")}}class F2{constructor(t){this.http=t}listProjects(){return this.http.invoke("list_projects")}createProject(t,n){return this.http.invoke("create_project",{request:{name:t,root:n}})}openProject(t){return this.http.invoke("open_project",{projectId:t})}async closeProject(t){await this.http.invoke("close_project",{projectId:t})}readProjectContext(t){return this.http.invoke("read_project_context",{projectId:t})}async updateProjectContext(t,n){await this.http.invoke("update_project_context",{request:{projectId:t,content:n}})}}class $2{constructor(t){this.http=t}loadLayout(t,n){return this.http.invoke("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return this.http.invoke("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return this.http.invoke("list_layouts",{projectId:t})}createLayout(t,n,r){return this.http.invoke("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return this.http.invoke("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return this.http.invoke("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return this.http.invoke("set_active_layout",{request:{projectId:t,layoutId:n}})}}class W2{constructor(t){this.http=t}status(t){return this.http.invoke("git_status",{projectId:t})}async stage(t,n){await this.http.invoke("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await this.http.invoke("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return this.http.invoke("git_commit",{request:{projectId:t,message:n}})}branches(t){return this.http.invoke("git_branches",{projectId:t})}async checkout(t,n){await this.http.invoke("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return this.http.invoke("git_log",{projectId:t,limit:n})}async init(t){await this.http.invoke("git_init",{projectId:t})}graph(t,n){return this.http.invoke("git_graph",{projectId:t,limit:n})}}class H2{constructor(t){this.http=t}firstRunState(){return this.http.invoke("first_run_state")}referenceProfiles(){return this.http.invoke("reference_profiles")}detectProfiles(t){return this.http.invoke("detect_profiles",{request:{candidates:t}})}listProfiles(){return this.http.invoke("list_profiles")}saveProfile(t){return this.http.invoke("save_profile",{request:{profile:t}})}async deleteProfile(t){await this.http.invoke("delete_profile",{profileId:t})}configureProfiles(t){return this.http.invoke("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return this.http.invoke("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return this.http.invoke("list_opencode_providers")}saveOpenCodeProviderProfile(t){return this.http.invoke("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class U2{constructor(t){this.http=t}listModelServers(){return this.http.invoke("list_model_servers")}saveModelServer(t){return this.http.invoke("save_model_server",{request:{config:t}})}async deleteModelServer(t){await this.http.invoke("delete_model_server",{serverId:t})}previewModelServerCommand(t){return this.http.invoke("preview_model_server_command",{config:t})}}class q2{constructor(t){this.http=t}listTemplates(){return this.http.invoke("list_templates")}createTemplate(t){return this.http.invoke("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return this.http.invoke("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await this.http.invoke("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return this.http.invoke("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return this.http.invoke("detect_agent_drift",{projectId:t})}syncAgent(t,n){return this.http.invoke("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class V2{constructor(t){this.http=t}listSkills(t,n){return this.http.invoke("list_skills",{projectId:t,scope:n})}createSkill(t){return this.http.invoke("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,s){return this.http.invoke("update_skill",{request:{projectId:t,scope:n,skillId:r,content:s}})}async deleteSkill(t,n,r){await this.http.invoke("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,s){await this.http.invoke("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:s}})}async unassignSkill(t,n,r){await this.http.invoke("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class K2{constructor(t){this.http=t}listMemories(t){return this.http.invoke("list_memories",{projectId:t})}getMemory(t,n){return this.http.invoke("get_memory",{projectId:t,slug:n})}createMemory(t){return this.http.invoke("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,s,i){return this.http.invoke("update_memory",{request:{projectId:t,slug:n,description:r,type:s,content:i}})}async deleteMemory(t,n){await this.http.invoke("delete_memory",{projectId:t,slug:n})}readIndex(t){return this.http.invoke("read_memory_index",{projectId:t})}resolveLinks(t,n){return this.http.invoke("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return this.http.invoke("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class G2{constructor(t){this.http=t}listEmbedderProfiles(){return this.http.invoke("list_embedder_profiles")}saveEmbedderProfile(t){return this.http.invoke("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await this.http.invoke("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return this.http.invoke("describe_embedder_engines")}}class Y2{constructor(t){this.http=t}getProjectPermissions(t){return this.http.invoke("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return this.http.invoke("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return this.http.invoke("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return this.http.invoke("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getProjectSystemPermissions(t){return this.http.invoke("get_project_system_permissions",{projectId:t})}updateProjectSystemPermissions(t,n){return this.http.invoke("update_project_system_permissions",{request:{projectId:t,permissions:n}})}updateAgentSystemPermissions(t,n,r){return this.http.invoke("update_agent_system_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentSystemPermissions(t,n){return this.http.invoke("resolve_agent_system_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return this.http.invoke("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return this.http.invoke("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return this.http.invoke("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}class X2{constructor(t){this.http=t}async getProjectWorkState(t){const n=await this.http.invoke("get_project_work_state",{projectId:t});return ap(n)}async cancelBackgroundTask(t){await this.http.invoke("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await this.http.invoke("retry_background_task",{taskId:t})}}class Q2{constructor(t){this.http=t}async readPage(t,n,r){const s=await this.http.invoke("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return iw(s)}}class J2{constructor(t){this.http=t}async interrupt(t,n){await this.http.invoke("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){await this.http.invoke("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}})}async setFrontAttached(t,n){await this.http.invoke("set_front_attached",{request:{agentId:t,attached:n}})}async cancelResume(t){return this.http.invoke("cancel_resume",{agentId:t})}async setResumeAt(t,n){await this.http.invoke("set_resume_at",{agentId:t,resetsAtMs:n})}}function at(e){throw{code:"UNSUPPORTED_ON_WEB",message:`${e} is not available in the web client (desktop-only).`}}class Z2{openViewWindow(){return at("Detaching a panel into an OS window")}closeViewWindow(){return at("Closing a detached OS window")}listOpenViewWindows(){return Promise.resolve([])}onViewWindowClosed(t){return Promise.resolve(()=>{})}}class eP{setFocusedProject(t){return Promise.resolve()}getFocusedProject(){return Promise.resolve(null)}onFocusedProjectChanged(t){return Promise.resolve(()=>{})}}class tP{connect(){return at("Remote (SSH/WSL) connection")}}class nP{async getExposureSettings(){return at("Embedded server settings")}async saveExposureSettings(t){return at("Embedded server settings")}async previewExposure(t){return at("Embedded server settings")}async status(){return at("Embedded server status")}async start(){return at("Starting the embedded server")}async stop(){return at("Stopping the embedded server")}onStatusChanged(t){return Promise.resolve(()=>{})}}class rP{async listPlugins(){return at("Plugin management")}async reviewPackage(t){return at("Plugin management")}async installFromArchive(t){return at("Plugin management")}async installFromDirectory(t){return at("Plugin management")}async setEnabled(t,n){return at("Plugin management")}async uninstall(t){return at("Plugin management")}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){return at("Plugin management")}}function ec(e,t,n){return{sessionId:e,...n?{assignedConversationId:n}:{},async write(r){await t.sendFireAndForget("terminal.input",{sessionId:e,bytesBase64:cw.encodeInput(r)})},async resize(r,s){await t.sendFireAndForget("terminal.resize",{sessionId:e,rows:r,cols:s})},detach(){t.detachTerminal(e)},async close(){await t.closeTerminalSession(e)}}}class sP{constructor(t,n){this.http=t,this.ws=n}health(t){return this.http.invoke("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await this.ws.ensureConnected(),this.ws.setDomainEventHandler(t),()=>this.ws.clearDomainEventHandler()}pickFolder(){return at("Native folder picker")}pickArchiveFile(){return at("Native file picker")}onAppExitWorkGuard(t){return Promise.resolve(()=>{})}confirmAppExit(){return at("Confirming an app exit")}}class iP{constructor(t){this.ws=t}async openTerminal(t,n){const r=await this.ws.openTerminal({cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null,onData:n});return ec(r.sessionId,this.ws)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:ec(r.sessionId,this.ws),scrollback:r.scrollback}}async closeTerminal(t){await this.ws.closeTerminalSession(t)}}class lP{constructor(t,n){this.http=t,this.ws=n}listAgents(t){return this.http.invoke("list_agents",{projectId:t})}listLiveAgents(t){return this.http.invoke("list_live_agents",{projectId:t})}listResumableAgents(t){return this.http.invoke("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return this.http.invoke("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return this.http.invoke("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return this.http.invoke("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,s,i){return this.http.invoke("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:s,cols:i}})}readContext(t,n){return this.http.invoke("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await this.http.invoke("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await this.http.invoke("delete_agent",{projectId:t,agentId:n})}inspectConversation(t,n,r){return this.http.invoke("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}async launchAgent(t,n,r,s){const i=await this.ws.launchAgent({projectId:t,agentId:n,nodeId:r.nodeId??null,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,onData:s});return ec(i.sessionId,this.ws,i.assignedConversationId)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:ec(r.sessionId,this.ws),scrollback:r.scrollback}}}class oP{constructor(t,n){this.http=t,this.ws=n}create(t,n){return this.http.invoke("ticket_create",{request:{projectId:t,...n}})}read(t,n,r=!1){return this.http.invoke("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}list(t,n){const{statuses:r,priorities:s,...i}=n??{};return this.http.invoke("ticket_list",{request:{projectId:t,statuses:r??[],priorities:s??[],...i}})}update(t,n,r){return this.http.invoke("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await this.http.invoke("ticket_delete",{request:{projectId:t,ref:n}})}readCarnet(t,n){return this.http.invoke("ticket_read_carnet",{request:{projectId:t,ref:n}})}updateCarnet(t,n,r,s){return this.http.invoke("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:s}})}link(t,n,r,s,i){return this.http.invoke("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:s,expectedVersion:i}})}unlink(t,n,r,s,i){return this.http.invoke("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:s,kind:i}})}assign(t,n,r,s,i){return this.http.invoke("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:s,expectedVersion:i}})}async listSprints(t){return(await this.http.invoke("sprint_list",{request:{projectId:t}})).items}setTicketSprint(t,n,r,s){return r===null?this.http.invoke("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:s}}):this.http.invoke("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:s}})}createSprint(t,n){return this.http.invoke("sprint_create",{request:{projectId:t,name:n}})}renameSprint(t,n,r,s){return this.http.invoke("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:s}})}async reorderSprints(t,n){return(await this.http.invoke("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await this.http.invoke("sprint_delete",{request:{projectId:t,sprintId:n}})}openTicketChat(t,n,r){return this.http.invoke("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await this.http.invoke("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const i=(await this.ws.send("chat.send",{sessionId:t,prompt:n})).payload;i&&i.chunk&&r(i.chunk)}}function aP(e){const t=typeof window<"u"&&window.location?window.location.origin:"http://localhost",n=e.baseUrl??t,r=e.wsUrl??n.replace(/^http(s?):\/\//,(s,i)=>`ws${i}://`);return{baseUrl:n,wsUrl:r}}function cP(e={}){const{baseUrl:t,wsUrl:n}=aP(e),r=uw();let s;const i=new P2({baseUrl:t,token:e.token,onUnauthorized:()=>{r.notifyUnauthorized(),s?.disconnect()}});return s=new cw({wsUrl:n,token:e.token,onReconnectFailed:()=>{i.invoke("health",{request:null}).catch(()=>{})}}),B2(s),{system:new sP(i,s),agent:new lP(i,s),input:new J2(i),terminal:new iP(s),project:new F2(i),layout:new $2(i),git:new W2(i),remote:new tP,profile:new H2(i),modelServer:new U2(i),desktopServer:new nP,template:new q2(i),skill:new V2(i),memory:new K2(i),embedder:new G2(i),device:new z2(i),permission:new Y2(i),workState:new X2(i),conversation:new Q2(i),ticket:new oP(i,s),window:new Z2,focusedProject:new eP,uiPreferences:new lw,plugin:new rP}}function uP(e){return"http"}const dw=g.createContext(null);function hw(){return uP()}function dP(){switch(hw()){case"mock":return N2();case"http":return cP();case"tauri":return VE()}}function hP({children:e,gateways:t}){const n=g.useMemo(()=>t??dP(),[t]);return o.jsx(dw.Provider,{value:n,children:e})}function fe(){const e=g.useContext(dw);if(!e)throw new Error("useGateways must be used within a ");return e}function hp({cwd:e,open:t,reattach:n,sessionId:r,onSessionId:s,agentMode:i=!1,portal:l,onReady:a,refitSignal:c,systemPermissions:u}){const{terminal:h}=fe(),d=g.useRef(null),[f,p]=g.useState(null),m=g.useRef(t);m.current=t;const x=g.useRef(n);x.current=n;const w=g.useRef(r);w.current=r;const v=g.useRef(s);v.current=s;const _=g.useRef(h);_.current=h;const y=g.useRef(i);y.current=i;const b=g.useRef(l);b.current=l;const C=g.useRef(a);C.current=a;const S=g.useRef(null);g.useEffect(()=>{const A=d.current,k=_.current,D=m.current??k?.openTerminal.bind(k),R=x.current??k?.reattach.bind(k);if(!A||!D)return;p(null);const E=new QN({convertEol:!1,cursorBlink:!0,fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'}),O=new eE;E.loadAddon(O);try{E.open(A)}catch{E.dispose();return}try{O.fit()}catch{}let I=!1,W=null;const G=new TextEncoder;let P="";const z=E.onData($=>{const B=b.current;y.current&&B&&(B.onHumanData($),B.isSuspended())||(W?W.write(G.encode($)):P+=$)});C.current?.({send:$=>{I||E.input($)},focus:()=>{I||E.focus()}});const j=$=>{I||E.write($)},se=$=>{if(I){$.detach();return}W=$,y.current&&b.current?.bindHandle($),P&&($.write(G.encode(P)),P="")},q=$=>{if(!I){if(fP($)==="AGENT_ALREADY_RUNNING"){E.write(`\r -\x1B[2mCellule disponible — l'agent est en cours dans une autre cellule.\x1B[0m\r -`);return}p(`Échec du lancement de l'agent : ${ax($)}`),E.write(`\r -\x1B[31mfailed to open terminal: ${ax($)}\x1B[0m\r -`)}},T=w.current;T&&R?R(T,j).then(({handle:$,scrollback:B})=>{if(I){$.detach();return}B.length>0&&E.write(B),se($)}).catch(()=>{I||D({cwd:e,rows:E.rows,cols:E.cols},j).then($=>{v.current?.($.sessionId),se($)}).catch(q)}):D({cwd:e,rows:E.rows,cols:E.cols},j).then($=>{v.current?.($.sessionId),se($)}).catch(q);let re=0,ee=E.rows,Q=E.cols;const V=8;let Y=0;const oe=()=>{if(re=0,!I){if(A.clientWidth===0||A.clientHeight===0){Y{re&&cancelAnimationFrame(re),re=requestAnimationFrame(oe)},Pe=new ResizeObserver(pe);return Pe.observe(A),S.current=pe,()=>{I=!0,S.current=null,re&&cancelAnimationFrame(re),Pe.disconnect(),z.dispose(),b.current?.unbindHandle(),W&&W.detach(),E.dispose()}},[e]),g.useEffect(()=>{c!==void 0&&S.current?.()},[c]);const N=u!=null&&(u.runtimeLock.state==="locked"||u.effective==="deny"),L=u?.runtimeLock.reason??u?.control.reason??"Le réseau est interdit pour cette cellule.";return o.jsxs("div",{"data-testid":"terminal-view",style:{position:"relative",width:"100%",height:"100%",minHeight:"16rem"},children:[o.jsx("div",{ref:d,style:{width:"100%",height:"100%"}}),N&&o.jsxs("div",{role:"status","data-testid":"terminal-network-banner",style:{position:"absolute",top:8,left:8,right:8,padding:"0.5rem 0.75rem",border:"1px solid rgba(245, 158, 11, 0.45)",borderRadius:6,background:"rgba(24, 24, 27, 0.94)",color:"var(--color-warning, #f59e0b)",fontSize:12,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:2},children:[u.runtimeLock.state==="locked"?"Réseau verrouillé par le runtime.":"Réseau interdit pour cet agent."," ",L]}),f&&o.jsx("div",{role:"alert","data-testid":"terminal-error",style:{position:"absolute",top:0,left:0,right:0,padding:"0.5rem 0.75rem",background:"rgba(120, 20, 20, 0.92)",color:"#fff",fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:3},children:f})]})}function ax(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function fP(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function pP({agentWasRunning:e,details:t,onResume:n,onNewConversation:r}){const s=e?"en cours":"clot";return o.jsx("div",{"data-testid":"resume-conversation-popup",role:"dialog","aria-label":"Reprise de conversation",style:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)"},children:o.jsxs("div",{style:{minWidth:260,maxWidth:360,padding:"16px 18px",background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:6,boxShadow:"0 8px 24px rgba(0, 0, 0, 0.5)",fontSize:13},children:[o.jsx("p",{style:{margin:"0 0 8px",fontWeight:600},children:"Reprise de conversation"}),o.jsxs("p",{style:{margin:"0 0 6px"},children:["Statut :"," ",o.jsx("span",{"data-testid":"resume-status",children:s})]}),t?.lastTopic&&o.jsxs("p",{style:{margin:"0 0 6px"},"data-testid":"resume-last-topic",children:["Dernier sujet : ",t.lastTopic]}),t?.tokenCount!==void 0&&o.jsxs("p",{style:{margin:"0 0 10px"},"data-testid":"resume-token-count",children:["Tokens : ",t.tokenCount]}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[o.jsx("button",{type:"button",onClick:n,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Reprendre la dernière conversation"}),o.jsx("button",{type:"button",onClick:r,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Nouvelle conversation"})]})]})})}const ju="\r",cx=350,mP=2e3,gP=512,xP=8,vP="[write-portal]",Pr=new TextEncoder;function _P(e){if(e.length===0)return!1;for(const t of e){const n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function yP(e,t){const{system:n,input:r}=fe(),[s,i]=g.useState(!1),l=g.useRef(0),a=g.useRef([]),c=g.useRef(null),u=g.useRef(!1),h=g.useRef(!1),d=g.useRef(null),f=g.useRef(null),p=g.useRef(r);p.current=r;const m=g.useRef(t);m.current=t;const x=g.useRef(e);x.current=e;const w=g.useRef(()=>{});w.current=()=>{const y=c.current&&d.current?d.current:null,b=f.current;b!==y&&(b&&(Ze("front-attached:set",{agent:b,attached:!1}),p.current?.setFrontAttached(b,!1).catch(C=>{Ze("front-attached:set-failed",{agent:b,attached:!1,error:Nu(C)})})),y&&(Ze("front-attached:set",{agent:y,attached:!0}),p.current?.setFrontAttached(y,!0).catch(C=>{Ze("front-attached:set-failed",{agent:y,attached:!0,error:Nu(C)})})),f.current=y)};const v=g.useRef(()=>{});return v.current=()=>{if(h.current)return;const y=a.current[0];if(!y||l.current>0)return;const b=c.current;if(!b)return;const C=m.current,S=x.current;if(!C)return;h.current=!0;const N=Date.now();u.current=!0,i(!0),(async()=>{let L=!1;try{Ze("inject:start",{agent:C,ticket:y.ticket,textBytes:Pr.encode(y.text).byteLength,queue:a.current.length,submitSequence:pa(y.submitSequence),submitDelayMs:y.submitDelayMs??cx}),await Promise.resolve();const A=l.current;A>0&&(Ze("inject:erase-human-window",{agent:C,ticket:y.ticket,count:A}),await b.write(Pr.encode("".repeat(A))),l.current=0),await bP(b,y.text,y.ticket);const k=y.submitDelayMs??cx;Ze("inject:before-submit-delay",{agent:C,ticket:y.ticket,delay:k}),await zh(k);const D=wP(y.submitSequence,y.ticket);Ze("inject:submit-write:start",{agent:C,ticket:y.ticket,submitSequence:pa(D),submitBytes:Pr.encode(D).byteLength}),await b.write(Pr.encode(D)),Ze("inject:submit-write:ok",{agent:C,ticket:y.ticket}),a.current.shift(),L=!0;try{Ze("inject:ack:start",{agent:C,ticket:y.ticket}),await p.current.delegationDelivered(S,C,y.ticket),Ze("inject:ack:ok",{agent:C,ticket:y.ticket})}catch{Ze("inject:ack:failed",{agent:C,ticket:y.ticket})}}catch(A){Ze("inject:failed",{agent:C,ticket:y.ticket,error:Nu(A)})}finally{const A=Date.now()-N,k=mP-A;k>0&&await zh(k),u.current=!1,i(!1),h.current=!1,a.current.length>0&&L&&v.current()}})()},g.useEffect(()=>{if(!n||!t){d.current=null,w.current();return}let y,b=!1;const C=t;return n.onDomainEvent(S=>{S.type==="delegationReady"&&S.agentId===C&&(a.current.push({ticket:S.ticket,text:S.text,submitSequence:S.submitSequence,submitDelayMs:S.submitDelayMs}),Ze("event:delegation-ready",{agent:C,ticket:S.ticket,textBytes:Pr.encode(S.text).byteLength,queue:a.current.length,submitSequence:pa(S.submitSequence),submitDelayMs:S.submitDelayMs}),v.current())}).then(S=>{b?S():(y=S,d.current=C,Ze("event:subscribed",{agent:C}),w.current())}),()=>{b=!0,y?.(),d.current===C&&(d.current=null,Ze("event:unsubscribed",{agent:C})),f.current===C?(p.current?.setFrontAttached(C,!1).catch(()=>{}),f.current=null):w.current()}},[n,t]),{portal:g.useMemo(()=>({onHumanData(y){if(y==="\r"||y===` -`||y===""){l.current=0,v.current();return}_P(y)&&(l.current+=1)},isSuspended(){return u.current},bindHandle(y){c.current=y,Ze("handle:bound",{agent:m.current,sessionId:y.sessionId}),w.current(),v.current()},unbindHandle(){Ze("handle:unbound",{agent:m.current,sessionId:c.current?.sessionId}),c.current=null,w.current()}}),[]),overlay:s}}function zh(e){return new Promise(t=>setTimeout(t,e))}async function bP(e,t,n){const r=SP(t,gP);for(let s=0;s0?e:(Ze("inject:empty-submit-sequence-defaulted",{ticket:t,defaultSubmitSequence:pa(ju)}),ju)}function SP(e,t){if(e.length===0)return[""];const n=[];let r="",s=0;for(const i of e){const l=Pr.encode(i).byteLength;r.length>0&&s+l>t&&(n.push(r),r="",s=0),r+=i,s+=l}return r.length>0&&n.push(r),n}function pa(e){return e==null?"":e.length===0?"":[...e].map(t=>{switch(t){case"\r":return"\\r";case` -`:return"\\n";case"":return"\\x7f";default:{const n=t.codePointAt(0);return n<32?`\\x${n.toString(16).padStart(2,"0")}`:t}}}).join("")}function Nu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Ze(e,t){console.info(vP,e,t)}function kP(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function eo(e){const{workState:t,system:n}=fe(),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{s(await t.getProjectWorkState(e))}catch(h){l(kP(h))}finally{c(!1)}},[e,t]);return g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let h,d=!1;return n.onDomainEvent(f=>{(f.type==="agentLaunched"||f.type==="agentExited"||f.type==="agentBusyChanged"||f.type==="delegationReady"||f.type==="orchestratorRequestProcessed"||f.type==="backgroundTaskChanged"||f.type==="agentInboxChanged"||f.type==="agentWakeChanged")&&u()}).then(f=>{d?f():h=f}),()=>{d=!0,h?.()}},[u,n]),{state:r,error:i,busy:a,refresh:u}}const CP=50;function fw(){return{byTarget:{},nextSeq:1}}function jP(e,t,n=CP){const{target:r,ticketId:s}=t,i={...t,seq:e.nextSeq},l=e.byTarget[r]??{},c=[...l[s]??[],i],u=c.length>n?c.slice(c.length-n):c;return{byTarget:{...e.byTarget,[r]:{...l,[s]:u}},nextSeq:e.nextSeq+1}}function NP(e,t){if(!(t in e.byTarget))return e;const{[t]:n,...r}=e.byTarget;return{byTarget:r,nextSeq:e.nextSeq}}function pw(e,t){return e.atMs-t.atMs||e.seq-t.seq}function EP(e,t){const n=e.byTarget[t];return n?Object.values(n).flat().sort(pw):[]}function PP(e,t,n){const r=[];for(const s of Object.values(e.byTarget))for(const[i,l]of Object.entries(s))if(!(n!==void 0&&i!==n))for(const a of l)a.requester===t&&r.push(a);return r.sort(pw)}const AP=()=>{},TP=fw(),LP={},DP={index:TP,busy:LP,seedBusy:AP},fp=g.createContext(null);function RP({children:e}){const{system:t}=fe(),[n,r]=g.useState(fw),[s,i]=g.useState({}),l=g.useCallback((c,u)=>{i(h=>c in h?h:{...h,[c]:u})},[]);g.useEffect(()=>{if(!t)return;let c,u=!1;return t.onDomainEvent(h=>{if(h.type==="agentAnnouncement")r(d=>jP(d,{requester:h.requester,target:h.target,ticketId:h.ticketId,text:h.text,atMs:h.atMs}));else if(h.type==="agentBusyChanged"){const{agentId:d,busy:f}=h;i(p=>({...p,[d]:f})),f||r(p=>NP(p,d))}}).then(h=>{u?h():c=h}).catch(()=>{}),()=>{u=!0,c?.()}},[t]);const a=g.useMemo(()=>({index:n,busy:s,seedBusy:l}),[n,s,l]);return o.jsx(fp.Provider,{value:a,children:e})}function pp(){return g.useContext(fp)??DP}function MP(){return g.useContext(fp)!==null}function mw(e){const{index:t,busy:n}=pp();return g.useMemo(()=>({announcements:EP(t,e),active:n[e]===!0}),[t,n,e])}function IP(e,t){const{workState:n}=fe(),{seedBusy:r}=pp(),s=MP();g.useEffect(()=>{if(!s||!n)return;let i=!1;return n.getProjectWorkState(e).then(l=>{if(i)return;const a=l.agents.find(c=>c.agentId===t);a&&r(t,a.busy.state==="busy")}).catch(()=>{}),()=>{i=!0}},[s,n,e,t,r])}function OP(e,t){const{index:n}=pp();return g.useMemo(()=>PP(n,e,t),[n,e,t])}function U(...e){return e.filter(Boolean).join(" ")}function Me({size:e=16,className:t,label:n="Loading"}){return o.jsx("span",{role:"status","aria-label":n,className:U("inline-block animate-spin rounded-full border-2 border-current border-t-transparent",t),style:{width:e,height:e}})}const BP="inline-flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors select-none disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none",zP={sm:"h-7 px-2.5 text-xs",md:"h-9 px-3.5 text-sm"},FP={primary:"bg-primary text-on-primary hover:bg-primary-hover",secondary:"bg-raised text-content border border-border hover:border-border-strong",ghost:"text-muted hover:text-content hover:bg-raised",danger:"bg-danger text-white hover:brightness-110"},M=g.forwardRef(function({variant:t="secondary",size:n="md",loading:r=!1,disabled:s,className:i,children:l,...a},c){return o.jsxs("button",{ref:c,type:a.type??"button",disabled:s||r,className:U(BP,zP[n],FP[t],i),...a,children:[r&&o.jsx(Me,{size:n==="sm"?12:14}),l]})}),$P={sm:"h-6 w-6 text-xs",md:"h-8 w-8 text-sm"},sr=g.forwardRef(function({size:t="md",className:n,children:r,...s},i){return o.jsx("button",{ref:i,type:s.type??"button",className:U("inline-flex items-center justify-center rounded-md text-muted transition-colors","hover:bg-raised hover:text-content focus-visible:outline-none","disabled:opacity-50 disabled:cursor-not-allowed",$P[t],n),...s,children:r})}),ce=g.forwardRef(function({invalid:t=!1,className:n,...r},s){return o.jsx("input",{ref:s,"aria-invalid":t||void 0,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border placeholder:text-faint outline-none transition-colors",t?"border-danger":"border-border focus:border-primary","disabled:opacity-50 disabled:cursor-not-allowed",n),...r})});function qt({label:e,hint:t,error:n,hideLabel:r,className:s,children:i}){const l=g.useId(),a=`${l}-msg`,c=n??t;return o.jsxs("div",{className:U("flex flex-col gap-1",s),children:[o.jsx("label",{htmlFor:l,className:U("text-xs font-medium text-muted",r&&"sr-only"),children:e}),i({id:l,describedBy:c?a:void 0}),c&&o.jsx("p",{id:a,role:n?"alert":void 0,className:U("text-xs",n?"text-danger":"text-faint"),children:c})]})}function ke({title:e,actions:t,flush:n,className:r,children:s,...i}){const l=e!=null||t!=null;return o.jsxs("section",{className:U("rounded-lg border border-border bg-surface",r),...i,children:[l&&o.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-2.5",children:[typeof e=="string"?o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}):e,t]}),o.jsx("div",{className:U(!n&&"p-4"),children:s})]})}function WP({items:e,value:t,onSelect:n,onClose:r,className:s}){return o.jsx("div",{role:"tablist",className:U("flex flex-wrap items-stretch gap-1",s),children:e.map(i=>{const l=i.id===t;return o.jsxs("div",{className:U("group flex items-center gap-1 rounded-md border px-1 transition-colors",l?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[o.jsx("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>n(i.id),className:U("px-2 py-1 text-sm focus-visible:outline-none",l?"font-semibold text-content":"text-muted hover:text-content"),children:i.label}),r&&o.jsx(sr,{size:"sm","aria-label":`close ${i.label}`,onClick:()=>r(i.id),className:"opacity-60 group-hover:opacity-100",children:"×"})]},i.id)})})}const HP={start:"justify-start",between:"justify-between",end:"justify-end"};function gw({justify:e="start",className:t,children:n,...r}){return o.jsx("div",{role:"toolbar",className:U("flex items-center gap-2",HP[e],t),...r,children:n})}const Sn={menuDropdown:40,floatingWindow:50,floatingWindowNested:60,toast:70},UP={sm:"max-w-sm",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"},ux='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',qi=[];function Fh({open:e,title:t,onClose:n,size:r="md",children:s}){return e?o.jsx(qP,{title:t,onClose:n,size:r,children:s}):null}function qP({title:e,onClose:t,size:n,children:r}){const s=g.useRef(null),i=g.useRef(t);return i.current=t,g.useEffect(()=>{const l=document.activeElement,a=s.current,c={};qi.push(c);const u=()=>qi[qi.length-1]===c;(a?.querySelector(ux)??a)?.focus();function d(f){if(!u())return;if(f.key==="Escape"){f.preventDefault(),i.current();return}if(f.key!=="Tab"||!a)return;const p=Array.from(a.querySelectorAll(ux));if(p.length===0){f.preventDefault(),a.focus();return}const m=p[0],x=p[p.length-1],w=document.activeElement;f.shiftKey&&w===m?(f.preventDefault(),x.focus()):!f.shiftKey&&w===x&&(f.preventDefault(),m.focus())}return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d);const f=qi.indexOf(c);f>=0&&qi.splice(f,1),l?.focus?.()}},[]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindow},onMouseDown:l=>{l.target===l.currentTarget&&t()},children:o.jsxs("div",{ref:s,role:"dialog","aria-modal":"true","aria-label":e,tabIndex:-1,className:U("flex max-h-[80vh] w-full flex-col overflow-hidden rounded-lg","border border-border bg-surface shadow-xl outline-none",UP[n??"md"]),children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:e}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`close ${e}`,onClick:t,children:"Close"})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})})}function VP({menus:e,className:t}){const[n,r]=g.useState(null),[s,i]=g.useState(null),l=g.useRef(null);function a(){r(null),i(null)}return g.useEffect(()=>{if(n===null)return;function c(h){l.current?.contains(h.target)||a()}function u(h){h.key==="Escape"&&a()}return document.addEventListener("mousedown",c),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("keydown",u)}},[n]),o.jsx("div",{ref:l,className:U("flex shrink-0 items-center gap-0.5 border-b border-border bg-surface px-2 py-1",t),children:e.map(c=>{const u=n===c.id;return o.jsxs("div",{className:"relative",children:[o.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":u,onClick:()=>{i(null),r(h=>h===c.id?null:c.id)},className:U("rounded px-2.5 py-1 text-sm transition-colors",u?"bg-raised text-content":"text-muted hover:bg-raised hover:text-content"),children:c.label}),u&&o.jsx("div",{role:"menu","aria-label":c.label,style:{zIndex:Sn.menuDropdown},className:U("absolute left-0 top-full mt-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:c.items.map(h=>{const d=(h.submenu?.length??0)>0,f=d&&s===h.id;return o.jsxs("div",{className:"relative",onMouseEnter:()=>i(d?h.id:null),children:[o.jsxs("button",{type:"button",disabled:h.disabled,"aria-haspopup":d?"menu":void 0,"aria-expanded":d?f:void 0,onClick:()=>{if(d){i(p=>p===h.id?null:h.id);return}h.onSelect(),a()},className:U("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[o.jsx("span",{children:h.label}),d?o.jsx("span",{"aria-hidden":!0,className:"text-muted",children:h.active?"● ▸":"▸"}):h.active&&o.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]}),f&&o.jsx("div",{role:"menu","aria-label":h.label,style:{zIndex:Sn.floatingWindowNested},className:U("absolute left-full top-0 ml-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:h.submenu.map(p=>o.jsxs("button",{type:"button",disabled:p.disabled,onClick:()=>{p.onSelect(),a()},className:U("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[o.jsx("span",{children:p.label}),p.active&&o.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]},p.id))})]},h.id)})})]},c.id)})})}const KP=240,GP=720;function dx({side:e,width:t,onResize:n,minWidth:r=KP,maxWidth:s=GP,"aria-label":i,children:l}){const a=g.useRef(null);function c(p){return Math.min(s,Math.max(r,p))}function u(p){p.preventDefault(),p.currentTarget.setPointerCapture?.(p.pointerId),a.current={startX:p.clientX,startWidth:t}}function h(p){const m=a.current;if(!m)return;const x=p.clientX-m.startX,w=e==="left"?x:-x;n(c(m.startWidth+w))}function d(p){if(!a.current)return;const m=p.clientX-a.current.startX,x=e==="left"?m:-m;a.current=null,n(c(t+x))}const f=o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":`resize ${e} dock`,onPointerDown:u,onPointerMove:h,onPointerUp:d,className:"shrink-0 cursor-col-resize bg-border hover:bg-border-strong",style:{flex:"0 0 4px",touchAction:"none"}});return o.jsxs("aside",{"aria-label":i??`${e} dock`,className:U("flex h-full shrink-0 bg-surface",e==="left"?"flex-row border-r border-border":"flex-row-reverse border-l border-border"),style:{width:t},children:[o.jsx("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:l}),f]})}function YP(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleTimeString()}catch{return""}}function XP({projectId:e,agentId:t}){IP(e,t);const{announcements:n,active:r}=mw(t),s=g.useRef(null);return g.useEffect(()=>{const i=s.current;i&&(i.scrollTop=i.scrollHeight)},[n]),r?o.jsxs("div",{"data-testid":"target-announcements-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-[4] flex flex-col bg-canvas/85 backdrop-blur-sm",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-surface/80 px-4 py-2",children:[o.jsx(Me,{size:14}),o.jsx("span",{className:"text-sm font-medium text-content",children:"Un agent est en train de lui parler…"})]}),o.jsx("div",{ref:s,className:"flex flex-1 flex-col justify-end gap-1.5 overflow-hidden px-6 py-4",children:n.map(i=>{const l=YP(i.atMs);return o.jsxs("div",{className:"flex items-baseline gap-2 text-sm text-muted",children:[l&&o.jsx("span",{className:"shrink-0 text-xs text-faint",children:l}),o.jsx("span",{className:"whitespace-pre-wrap break-words text-content/90",children:i.text})]},i.seq)})})]}):null}function QP({requester:e,ticketId:t,limit:n=3}){const r=OP(e,t);if(r.length===0)return null;const s=r.slice(Math.max(0,r.length-n));return o.jsxs("div",{"data-testid":"announcements-preview",className:"flex flex-col gap-1 rounded-md border border-primary/25 bg-primary/5 px-2.5 py-1.5",children:[o.jsxs("span",{className:"flex items-center gap-1.5 text-[0.65rem] font-medium uppercase tracking-wide text-primary",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-primary"}),"En attente d'un agent"]}),o.jsx("ul",{className:"flex flex-col gap-0.5",children:s.map(i=>o.jsx("li",{className:"truncate text-xs text-muted",title:i.text,children:i.text},i.seq))})]})}class JP{constructor(t,n){X(this,"handlers",new Map);this.pluginId=t,this.declaredCommandIds=n}register(t,n){if(!this.declaredCommandIds.has(t))throw new Error(`plugin "${this.pluginId}" tried to register command "${t}" which is not declared by any menu item in its manifest`);return this.handlers.set(t,n),{dispose:()=>{this.handlers.get(t)===n&&this.handlers.delete(t)}}}async run(t,...n){const r=this.handlers.get(t);r&&await r(...n)}has(t){return this.handlers.has(t)}}class ZP{constructor(t,n){X(this,"components",new Map);this.pluginId=t,this.declaredLayoutTypes=n}register(t){if(!this.declaredLayoutTypes.has(t.type))throw new Error(`plugin "${this.pluginId}" tried to register layout type "${t.type}" which is not declared in its manifest`);return this.components.set(t.type,t.component),{dispose:()=>{this.components.get(t.type)===t.component&&this.components.delete(t.type)}}}get(t){return this.components.get(t)}}class eA{constructor(t){this.pluginId=t}get ownerPluginId(){return this.pluginId}}class mp{constructor(){X(this,"loaded",new Map)}add(t){this.loaded.set(t.pluginId,t)}async remove(t){const n=this.loaded.get(t);if(n)try{await n.dispose()}finally{this.loaded.delete(t)}}get(t){return this.loaded.get(t)}list(){return[...this.loaded.values()]}topLevelMenus(){return this.list().flatMap(t=>t.contributes.menus.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,menu:n})))}menuItems(){return this.list().flatMap(t=>t.contributes.menuItems.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,item:n})))}layoutComponent(t,n){return this.loaded.get(t)?.layouts.get(n)}layoutContributions(){return this.list().flatMap(t=>t.contributes.layouts.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,layout:n})))}async runCommand(t,n,...r){await this.loaded.get(t)?.commands.run(n,...r)}}function tA(e){return typeof e=="object"&&e!==null&&"activate"in e&&typeof e.activate=="function"}async function nA(e,t){try{const n=await import(e.bundleUrl);if(!tA(n))return{failure:{pluginId:e.id,reason:'bundle does not export an "activate(ctx)" function'}};const r=new Set(e.contributes.menuItems.map(d=>d.command)),s=new Set(e.contributes.layouts.map(d=>d.type)),i=new JP(e.id,r),l=new ZP(e.id,s),a=new eA(e.id),c={pluginId:e.id,pluginDisplayName:e.displayName,version:e.version,commands:i,layouts:l,menu:a,...t},u=await n.activate(c);return{plugin:{pluginId:e.id,displayName:e.displayName,contributes:e.contributes,commands:i,layouts:l,menu:a,dispose:async()=>{try{await u.dispose?.()}catch{}}}}}catch(n){return{failure:{pluginId:e.id,reason:n instanceof Error?n.message:String(n)}}}}async function rA(e,t){const n=new mp,r=[],s=await Promise.all(e.map(i=>nA(i,t)));for(const i of s)"failure"in i?r.push(i.failure):n.add(i.plugin);return{registry:n,failures:r}}const sA=new Set(["projectOpen","gitRepository","agentSelected","terminalFocused","layoutCellFocused"]);function iA(e){const t=[];let n=0;for(;n=this.tokens.length}}function oA(e,t){if(e===void 0||e.trim()==="")return{ok:!0,value:!0};const n=iA(e);if(!n)return{ok:!1,reason:`invalid "when" expression: ${e}`};try{const r=new lA(n),s=r.parseOr(t);if(!r.finished())throw new Error("unexpected trailing tokens");return{ok:!0,value:s}}catch(r){const s=r instanceof Error?r.message:String(r);return{ok:!1,reason:`invalid "when" expression "${e}": ${s}`}}}const aA={registry:new mp,failures:[],loading:!1},xw=g.createContext(aA);function cA({children:e,value:t}){const n=fe(),[r,s]=g.useState(t??{registry:new mp,failures:[],loading:!0});return g.useEffect(()=>{if(t)return;let i=!1;return n.plugin.listRuntimeContributions().then(l=>rA(l.plugins,{project:n.project,git:n.git,terminal:n.terminal,agents:n.agent,system:n.system})).then(l=>{i||s({registry:l.registry,failures:l.failures,loading:!1})}).catch(()=>{i||s(l=>({...l,loading:!1}))}),()=>{i=!0}},[]),o.jsx(xw.Provider,{value:r,children:e})}function gp(){return g.useContext(xw)}function hx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:s=!1,onConfirm:i,onCancel:l}){const a=g.useRef(null);return g.useEffect(()=>{a.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.floatingWindow},onClick:l,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-md flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"whitespace-pre-line text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),o.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:s,onClick:()=>void i(),children:n})]})]})})}function Zr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function uA(){const{plugin:e,system:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(null),[l,a]=g.useState(!1),c=g.useCallback(async()=>{a(!0),i(null);try{r(await e.listPlugins())}catch(y){i(Zr(y))}finally{a(!1)}},[e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async y=>{a(!0),i(null);try{return await e.reviewPackage(y)}catch(b){return i(Zr(b)),null}finally{a(!1)}},[e]),h=g.useCallback(y=>u({sourceKind:"archive",path:y}),[u]),d=g.useCallback(y=>u({sourceKind:"directory",path:y}),[u]),f=g.useCallback(async y=>{a(!0),i(null);try{const b=await e.installFromArchive(y);return r(C=>[...C.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return i(Zr(b)),!1}finally{a(!1)}},[e]),p=g.useCallback(async y=>{a(!0),i(null);try{const b=await e.installFromDirectory(y);return r(C=>[...C.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return i(Zr(b)),!1}finally{a(!1)}},[e]),m=g.useCallback(async(y,b)=>{a(!0),i(null);try{const C=await e.setEnabled(y,b);r(S=>S.map(N=>N.id===y?C:N))}catch(C){i(Zr(C))}finally{a(!1)}},[e]),x=g.useCallback(async y=>{a(!0),i(null);try{await e.uninstall(y),r(b=>b.filter(C=>C.id!==y))}catch(b){i(Zr(b))}finally{a(!1)}},[e]),w=g.useCallback(async y=>{try{await e.openPluginsFolder(y)}catch(b){i(Zr(b))}},[e]),v=g.useCallback(()=>t.pickArchiveFile(),[t]),_=g.useCallback(()=>t.pickFolder(),[t]);return{plugins:n,error:s,busy:l,refresh:c,reviewArchive:h,reviewDirectory:d,installFromArchive:f,installFromDirectory:p,setEnabled:m,uninstall:x,openPluginsFolder:w,pickArchiveFile:v,pickDirectory:_}}const dA={enabled:"Activé",disabled:"Désactivé","pending-enable":"Activation en attente","pending-disable":"Désactivation en attente","pending-uninstall":"Désinstallation en attente",invalid:"Invalide"};function hA(){const e=uA(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(null);async function a(){l(null);const d=await e.pickArchiveFile();if(!d)return;const f=await e.reviewArchive(d);if(!f){l("La revue du paquet a échoué.");return}s({sourceKind:"archive",path:d,review:f})}async function c(){l(null);const d=await e.pickDirectory();if(!d)return;const f=await e.reviewDirectory(d);if(!f){l("La revue du paquet a échoué.");return}s({sourceKind:"directory",path:d,review:f})}async function u(){if(!r)return;(r.sourceKind==="archive"?await e.installFromArchive(r.path):await e.installFromDirectory(r.path))&&s(null)}async function h(){t&&(t.kind==="disable"?await e.setEnabled(t.plugin.id,!1):await e.uninstall(t.plugin.id),n(null))}return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:"Plugins"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{size:"sm",onClick:()=>void a(),disabled:e.busy,children:"Installer depuis une archive…"}),o.jsx(M,{size:"sm",variant:"secondary",onClick:()=>void c(),disabled:e.busy,children:"Installer depuis un dossier…"})]})]}),(e.error||i)&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error??i}),e.plugins.length===0?o.jsx(ke,{children:o.jsx("p",{className:"text-sm text-muted",children:"Aucun plugin installé."})}):o.jsx("ul",{className:"flex flex-col gap-2",children:e.plugins.map(d=>o.jsx("li",{children:o.jsxs(ke,{className:"flex items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:d.displayName}),o.jsxs("span",{className:"text-xs text-faint",children:["v",d.version]}),d.publisher&&o.jsxs("span",{className:"text-xs text-faint",children:["· ",d.publisher]}),o.jsx("span",{className:"rounded bg-raised px-1.5 py-0.5 text-[0.65rem] uppercase text-muted",children:"full-trust"})]}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted",children:[o.jsx("span",{"aria-label":"plugin state",className:d.lifecycleState==="invalid"?"text-danger":void 0,children:dA[d.lifecycleState]}),d.restartRequired&&o.jsx("span",{className:"text-warning",children:"Redémarrage requis"}),d.sourceLabel&&o.jsxs("span",{children:["· ",d.sourceLabel]})]}),d.error&&o.jsx("p",{className:"text-xs text-danger",role:"alert",children:d.error})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[d.enabled?o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>n({kind:"disable",plugin:d}),disabled:e.busy,children:"Désactiver"}):o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.setEnabled(d.id,!0),disabled:e.busy,children:"Activer"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.openPluginsFolder(d.id),disabled:e.busy,children:"Ouvrir le dossier"}),o.jsx(M,{size:"sm",variant:"danger",onClick:()=>n({kind:"uninstall",plugin:d}),disabled:e.busy,children:"Désinstaller"})]})]})},d.id))}),r&&o.jsx(hx,{title:`Installer "${r.review.displayName}" ?`,body:fA(r.review),confirmLabel:r.review.installable?"Installer":"Corriger avant d'installer",busy:e.busy,danger:!r.review.installable,onConfirm:()=>{r.review.installable?u():s(null)},onCancel:()=>s(null)}),t&&o.jsx(hx,{title:t.kind==="disable"?`Désactiver "${t.plugin.displayName}" ?`:`Désinstaller "${t.plugin.displayName}" ?`,body:t.kind==="disable"?"Ses contributions seront masquées immédiatement ; un redémarrage sera peut-être nécessaire pour purger complètement le plugin.":"Le plugin, ses fichiers et ses contributions seront supprimés après redémarrage.",confirmLabel:t.kind==="disable"?"Désactiver":"Désinstaller",danger:t.kind==="uninstall",busy:e.busy,onConfirm:()=>void h(),onCancel:()=>n(null)})]})}function fA(e){const{contributionSummary:t}=e;return[`Éditeur : ${e.publisher??"inconnu"}`,`Version : ${e.version}`,e.description??null,"Confiance : full-trust — ce plugin peut exécuter du code arbitraire dans IdeA.",`Contributions : ${t.topLevelMenus} menu(s), ${t.menuItems} item(s), ${t.layouts} layout(s), ${t.mcpServers} serveur(s) MCP.`,...e.issues.map(r=>`${r.severity==="error"?"Erreur":"Avertissement"} : ${r.message}`)].filter(r=>!!r).join(` -`)}function pA(e){return e.topLevelMenus().map(({pluginId:t,pluginDisplayName:n,menu:r})=>({id:`plugin:${r.id}`,pluginId:t,pluginDisplayName:n,label:r.label,icon:r.icon,order:r.order??0})).sort((t,n)=>t.order-n.order||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.label.localeCompare(n.label))}function mA(e,t,n){return e.menuItems().filter(({item:r})=>r.targetMenuId===t).map(({pluginId:r,pluginDisplayName:s,item:i})=>{const l=oA(i.when,n);return{id:i.id,pluginId:r,pluginDisplayName:s,targetMenuId:i.targetMenuId,label:i.label,command:i.command,enabled:l.ok?l.value:!1,disabledReason:l.ok?void 0:l.reason,groupLabel:s,order:i.order??0,iconUrl:i.icon}}).sort((r,s)=>r.order-s.order||r.pluginDisplayName.localeCompare(s.pluginDisplayName)||r.label.localeCompare(s.label))}function gA(e,t){const n=g.useMemo(()=>(i,l)=>e.runCommand(i,l),[e]),r=g.useMemo(()=>i=>mA(e,i,t).map(l=>({id:l.id,label:`${l.label} · ${l.pluginDisplayName}`,disabled:!l.enabled,onSelect:()=>{n(l.pluginId,l.command)}})),[e,t,n]);return{topLevelMenus:g.useMemo(()=>pA(e).map(i=>({id:i.id,label:i.label,items:r(i.id)})),[e,r]),itemsFor:r,runCommand:n}}function xA(e,t,n){const r=e.get(t.pluginId);if(!r){const l=n?.find(a=>a.id===t.pluginId);return l&&!l.enabled?"plugin-disabled":"plugin-missing"}return!r.contributes.layouts.some(l=>l.type===t.layoutType)||!r.layouts.get(t.layoutType)?"incompatible":"available"}const vA={"plugin-disabled":"Le plugin fournisseur est désactivé.","plugin-missing":"Le plugin fournisseur n'est pas installé.",incompatible:"Le plugin fournisseur ne déclare plus ce type de layout."};function _A({cell:e,availability:t,providerDisplayName:n,onOpenPlugins:r,onChooseAnotherLayout:s}){return o.jsxs(ke,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[o.jsx("p",{className:"text-sm font-semibold text-content",children:"Layout indisponible"}),o.jsx("p",{className:"text-xs text-muted",children:vA[t]}),o.jsxs("p",{className:"text-xs text-faint",children:["Fourni par « ",n??e.pluginId," »"]}),o.jsxs("div",{className:"mt-2 flex gap-2",children:[o.jsx(M,{size:"sm",variant:"secondary",onClick:r,children:"Ouvrir Plugins"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:s,children:"Choisir un autre layout"})]})]})}function yA({projectId:e,cell:t,installedPlugins:n,onStateChange:r,onOpenPlugins:s,onChooseAnotherLayout:i}){const{registry:l}=gp(),a=fe(),c=xA(l,t,n);if(c!=="available"){const h=l.get(t.pluginId)?.displayName??n?.find(d=>d.id===t.pluginId)?.displayName;return o.jsx(_A,{cell:t,availability:c,providerDisplayName:h,onOpenPlugins:s,onChooseAnotherLayout:i})}const u=l.layoutComponent(t.pluginId,t.layoutType);return o.jsx(u,{projectId:e,nodeId:t.id,layoutType:t.layoutType,state:t.state,setState:r,availability:"available",gateways:{project:a.project,git:a.git,terminal:a.terminal,agents:a.agent,system:a.system}})}function bA(e){return e.layoutContributions().map(({pluginId:t,pluginDisplayName:n,layout:r})=>({pluginId:t,pluginDisplayName:n,layout:r})).sort((t,n)=>(t.layout.order??0)-(n.layout.order??0)||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.layout.label.localeCompare(n.layout.label))}function wA({registry:e,onSelect:t}){const n=bA(e);return n.length===0?null:o.jsxs("div",{role:"group","aria-label":"Layouts plugins",children:[o.jsx("p",{className:"px-3 pt-2 text-[0.65rem] font-semibold uppercase tracking-wide text-faint",children:"Layouts plugins"}),n.map(r=>o.jsxs("button",{type:"button",role:"menuitem","aria-label":`create ${r.layout.label} layout`,onClick:()=>t(r),className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm text-content hover:bg-raised",children:[o.jsx("span",{children:r.layout.label}),o.jsx("span",{className:"text-xs text-faint",children:r.pluginDisplayName})]},`${r.pluginId}:${r.layout.type}`))]})}function fx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function SA(e){const{template:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(!1),[l,a]=g.useState(null),c=g.useCallback(async()=>{i(!0),a(null);try{const d=await t.detectDrift(e);r(d)}catch(d){a(fx(d))}finally{i(!1)}},[t,e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async(d,f)=>{i(!0),a(null);try{await t.syncAgent(e,d),f&&await f();const p=await t.detectDrift(e);r(p)}catch(p){a(fx(p))}finally{i(!1)}},[t,e]);return{driftByAgentId:new Map(n.map(d=>[d.agentId,d])),driftBusy:s,driftError:l,refreshDrift:c,syncAgent:u}}function Bn(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function kA(e){const{agent:t,profile:n,system:r,terminal:s,input:i}=fe(),[l,a]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState([]),[w,v]=g.useState(null),[_,y]=g.useState(!1),[b,C]=g.useState(null),[S,N]=g.useState({}),[L,A]=g.useState({}),[k,D]=g.useState({}),[R,E]=g.useState({}),O=g.useCallback(async()=>{y(!0),v(null);try{const[ee,Q]=await Promise.all([t.listAgents(e),n.listProfiles()]);a(ee),p(Q)}catch(ee){v(Bn(ee))}finally{y(!1)}},[t,n,e]),I=g.useCallback(async()=>{try{x(await t.listLiveAgents(e))}catch{x([])}},[t,e]);g.useEffect(()=>{O()},[O]),g.useEffect(()=>{I()},[I]),g.useEffect(()=>{if(!r)return;let ee,Q=!1;return r.onDomainEvent(V=>{if((V.type==="agentLaunched"||V.type==="agentExited"||V.type==="agentProfileChanged")&&(O(),I()),V.type==="agentLaunched"&&E(Y=>{if(!(V.agentId in Y))return Y;const{[V.agentId]:oe,...pe}=Y;return pe}),V.type==="orchestratorRequestProcessed"&&V.source!==void 0){const{requesterId:Y,source:oe}=V;N(pe=>pe[Y]===oe?pe:{...pe,[Y]:oe})}switch(V.type){case"agentRateLimited":A(Y=>({...Y,[V.agentId]:{limitedUntil:V.resetsAtMs,resumeFireAt:Y[V.agentId]?.resumeFireAt,suspected:!1}}));break;case"agentResumeScheduled":A(Y=>({...Y,[V.agentId]:{...Y[V.agentId],resumeFireAt:V.fireAtMs}}));break;case"agentResumeCancelled":A(Y=>{const oe=Y[V.agentId];if(!oe)return Y;const{resumeFireAt:pe,...Pe}=oe;return{...Y,[V.agentId]:Pe}});break;case"agentResumed":A(Y=>{if(!(V.agentId in Y))return Y;const{[V.agentId]:oe,...pe}=Y;return pe});break;case"agentRateLimitSuspected":A(Y=>({...Y,[V.agentId]:{...Y[V.agentId],limitedUntil:V.resetsAtMs,suspected:!0}}));break;case"modelServerStatusChanged":D(Y=>({...Y,[V.serverId]:V.status}));break;case"agentLaunchFailed":E(Y=>({...Y,[V.agentId]:{cause:V.cause,code:V.code,message:V.message}}));break}}).then(V=>{Q?V():ee=V}),()=>{Q=!0,ee?.()}},[r,O,I]);const W=g.useCallback(async(ee,Q,V)=>{y(!0),v(null);try{const Y=await t.createAgent(e,{name:ee,profileId:Q,initialContent:V});a(oe=>[...oe,Y])}catch(Y){v(Bn(Y))}finally{y(!1)}},[t,e]),G=g.useCallback(async ee=>{y(!0),v(null);try{const Q=await t.readContext(e,ee);u(ee),d(Q)}catch(Q){v(Bn(Q))}finally{y(!1)}},[t,e]),P=g.useCallback(async ee=>{if(c){y(!0),v(null);try{await t.updateContext(e,c,ee),d(ee)}catch(Q){v(Bn(Q))}finally{y(!1)}}},[t,e,c]),z=g.useCallback(async(ee,Q,V,Y)=>{y(!0),v(null);try{const{agent:oe,relaunchedSession:pe}=await t.changeAgentProfile(e,ee,Q,V,Y);return a(Pe=>Pe.map($=>$.id===oe.id?oe:$)),I(),pe}catch(oe){v(Bn(oe));return}finally{y(!1)}},[t,e,I]),j=g.useCallback(async ee=>{y(!0),v(null);try{await t.deleteAgent(e,ee),a(Q=>Q.filter(V=>V.id!==ee)),u(Q=>Q===ee?null:Q),c===ee&&d(""),C(Q=>Q===ee?null:Q)}catch(Q){v(Bn(Q))}finally{y(!1)}},[t,e,c]),se=g.useCallback(async(ee,Q,V)=>{v(null);try{const Y=await t.launchAgent(e,ee,Q,V);return C(ee),I(),Y}catch(Y){throw v(Bn(Y)),Y}},[t,e,I]),q=g.useCallback(async ee=>{const Q=ee??b,V=Q?m.find(Y=>Y.agentId===Q):null;if(C(Y=>Y===Q||!Q?null:Y),V?.sessionId)try{await s?.closeTerminal(V.sessionId),x(Y=>Y.filter(oe=>oe.agentId!==Q))}catch(Y){v(Bn(Y)),await I()}},[m,I,b,s]),T=g.useCallback(async ee=>{A(Q=>{const V=Q[ee];if(!V?.resumeFireAt)return Q;const{resumeFireAt:Y,...oe}=V;return{...Q,[ee]:oe}});try{return await i?.cancelResume(ee)??!1}catch(Q){return v(Bn(Q)),!1}},[i]),re=g.useCallback(async(ee,Q)=>{try{await i?.setResumeAt(ee,Q)}catch(V){v(Bn(V))}},[i]);return{agents:l,selectedAgentId:c,context:h,profiles:f,liveAgents:m,delegationSourceByRequester:S,limitByAgent:L,modelServerStatusByServer:k,launchFailureByAgent:R,error:w,busy:_,runningAgentId:b,refresh:O,refreshLiveAgents:I,createAgent:W,selectAgent:G,saveContext:P,changeAgentProfile:z,deleteAgent:j,launchAgent:se,stopAgent:q,cancelResume:T,setResumeAt:re}}function vw(e,t,n){if(!e)return;const r=t.find(s=>s.id===e.profileId)?.opencode?.localModelServerId;return r?n[r]:void 0}function CA(e){if(!e)return null;switch(e.state){case"downloading":return"Téléchargement du modèle…";case"starting":case"probing":return"Chargement du serveur…";default:return null}}function Eu(e){if(!Number.isFinite(e)||e<=0)return"0 o";const t=["o","Ko","Mo","Go","To"];let n=e,r=0;for(;n>=1e3&&r{t&&t.listProfiles().then(s).catch(()=>{})},[t]);return g.useEffect(()=>{a()},[a]),g.useEffect(()=>{if(!n)return;let u,h=!1;return n.onDomainEvent(d=>{d.type==="modelServerStatusChanged"?l(f=>({...f,[d.serverId]:d.status})):d.type==="agentProfileChanged"&&a()}).then(d=>{h?d():u=d}),()=>{h=!0,u?.()}},[n,a]),{statusForAgent:g.useCallback(u=>vw(u,r,i),[r,i])}}function EA(e,t){const n=/^(\d{1,2}):(\d{2})$/.exec(e.trim());if(!n)return null;const r=Number(n[1]),s=Number(n[2]);if(r>23||s>59)return null;const i=new Date(t);return i.setHours(r,s,0,0),i.getTime()}function PA(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function AA(e){const t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function TA({state:e,onCancelResume:t,onSetResumeAt:n,busy:r=!1}){const{limitedUntil:s,resumeFireAt:i,suspected:l}=e,[a,c]=g.useState(()=>Date.now());g.useEffect(()=>{if(i===void 0)return;const m=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(m)},[i]);const[u,h]=g.useState(""),d=l===!0&&s===void 0&&i===void 0;function f(m){m.preventDefault();const x=EA(u,Date.now());x!==null&&(n(x),h(""))}const p=s!==void 0?`limité jusqu'à ${PA(s)}`:"limité";return o.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[o.jsx("span",{"aria-label":"session limit",title:l?"Limite de session détectée sans heure fiable":"Limite de session atteinte",className:U("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:p}),d&&o.jsxs("form",{onSubmit:f,className:"flex items-center gap-2","aria-label":"resume time form",children:[o.jsx("span",{className:"text-xs text-muted",role:"note",children:"heure inconnue"}),o.jsx(ce,{type:"time","aria-label":"resume time",value:u,disabled:r,onChange:m=>h(m.target.value),className:"h-8 w-28 text-xs"}),o.jsx(M,{type:"submit",size:"sm",variant:"primary","aria-label":"schedule resume",disabled:r||u.trim()==="",children:"Programmer la reprise"})]}),i!==void 0&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsxs("span",{"aria-label":"resume countdown",className:"text-xs text-muted",children:["reprise dans ",AA(i-a)]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel resume",disabled:r,onClick:t,children:"Annuler la reprise"})]})]})}function LA(e){switch(e.state){case"notConfigured":return null;case"probing":return{label:"vérification du serveur…",tone:"bg-muted/20 text-muted",role:"status"};case"starting":return{label:"démarrage du serveur…",tone:"bg-warning/20 text-warning",role:"status"};case"downloading":return{label:"téléchargement du modèle…",tone:"bg-warning/20 text-warning",role:"status"};case"ready":return e.reused?{label:"serveur prêt (réutilisé)",tone:"bg-success/20 text-success"}:{label:"serveur prêt",tone:"bg-success/20 text-success"};case"failed":return null}}function DA({status:e,failure:t}){const[n,r]=g.useState(!1),s=t||(e?.state==="failed"?{code:e.code,message:e.message}:null);if(s)return o.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[o.jsxs("span",{role:"alert","aria-label":"model server launch failed",className:U("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:["Échec du lancement : ",s.message]}),o.jsx("button",{type:"button","aria-label":"toggle launch failure detail",onClick:()=>r(l=>!l),className:"text-xs text-muted underline hover:text-content",children:"Détails"}),n&&o.jsxs("span",{"aria-label":"launch failure detail",className:"text-xs text-faint",children:["code ",s.code,s.cause?` · cause ${s.cause}`:""]})]});if(!e)return null;const i=LA(e);return i?o.jsx("span",{role:i.role,"aria-label":"model server status",className:U("rounded-full px-2 py-0.5 text-xs font-medium",i.tone),children:i.label}):null}function _w({projectId:e,projectRoot:t=""}){const n=kA(e),r=SA(e),s=fe(),i=s.template??null,l=s.permission??null,[a,c]=g.useState(""),[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState([]),[x,w]=g.useState(!1);!x&&i&&(w(!0),i.listTemplates().then(m).catch(()=>{}));const v=s.skill??null,[_,y]=g.useState([]),[b,C]=g.useState(!1),[S,N]=g.useState("");async function L(){if(v)try{const[$,B]=await Promise.all([v.listSkills(e,"global"),v.listSkills(e,"project")]);y([...B,...$])}catch{}}!b&&v&&(C(!0),L());async function A(){if(!v||!n.selectedAgentId||!S)return;const $=_.find(B=>B.id===S);$&&(await v.assignSkill(e,n.selectedAgentId,$.id,$.scope),N(""),await n.refresh())}async function k($){!v||!n.selectedAgentId||(await v.unassignSkill(e,n.selectedAgentId,$),await n.refresh())}const[D,R]=g.useState(n.context),[E,O]=g.useState(n.context);n.context!==E&&(O(n.context),R(n.context));const[I,W]=g.useState(null),[G,P]=g.useState({}),[z,j]=g.useState({}),[se,q]=g.useState({});g.useEffect(()=>{if(!l||n.agents.length===0){q({});return}let $=!1;return Promise.all(n.agents.map(async B=>{try{return[B.id,await l.resolveAgentSystemPermissions(e,B.id)]}catch{return[B.id,null]}})).then(B=>{$||q(Object.fromEntries(B.filter(he=>he[1]!==null)))}),()=>{$=!0}},[l,e,n.agents]);const[T,re]=g.useState(null);async function ee(){if(!T)return;const{agentId:$,profileId:B}=T;re(null);const he=await n.changeAgentProfile($,B,24,80);he&&$===I&&j(ue=>({...ue,[$]:he.sessionId}))}const Q=a.trim().length>0&&!n.busy;async function V($){if($.preventDefault(),!!Q){if(d&&i)await i.createAgentFromTemplate(e,d,{name:a.trim(),synchronized:!0}),await n.refresh();else{const B=u.trim()||"";await n.createAgent(a.trim(),B)}c(""),h(""),f("")}}function Y($){P(B=>({...B,[$]:B[$]??crypto.randomUUID()})),W($)}function oe($){n.stopAgent($),W(null)}const pe=n.agents.find($=>$.id===n.selectedAgentId)??null,Pe=d!=="";return o.jsxs(ke,{title:"Agents",className:"flex flex-col gap-0",children:[n.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),o.jsxs("form",{onSubmit:$=>void V($),className:"flex flex-col gap-3 border-b border-border p-4",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"agent-name-input",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"agent-name-input","aria-label":"agent name",placeholder:"My agent",value:a,onChange:$=>c($.target.value),className:"w-full"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"agent-template-select",className:"text-xs font-medium text-muted",children:"Template"}),o.jsxs("select",{id:"agent-template-select","aria-label":"agent template",value:d,onChange:$=>f($.target.value),className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:n.busy,children:[o.jsx("option",{value:"",children:"(none / from scratch)"}),p.map($=>o.jsx("option",{value:$.id,children:$.name},$.id))]})]}),!Pe&&o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("label",{htmlFor:"agent-profile-select",className:"text-xs font-medium text-muted",children:["Profile",n.profiles.length===0&&o.jsx("span",{className:"ml-1 text-faint",children:"(no profiles configured — you can still enter an id)"})]}),n.profiles.length>0?o.jsxs("select",{id:"agent-profile-select","aria-label":"agent profile",value:u,onChange:$=>h($.target.value),className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— select profile —"}),n.profiles.map($=>o.jsx("option",{value:$.id,children:$.name},$.id))]}):o.jsx(ce,{id:"agent-profile-select","aria-label":"agent profile",placeholder:"profile-id (optional)",value:u,onChange:$=>h($.target.value),className:"min-w-32"})]}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"create agent",disabled:!Q,loading:n.busy,className:"self-end",children:"Create"})]}),o.jsx("div",{className:"p-4",children:n.agents.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.agents.map($=>{const B=$.id===n.selectedAgentId,he=$.id===I,ue=n.liveAgents.find(_e=>_e.agentId===$.id),Ee=n.profiles.find(_e=>_e.id===$.profileId)?.name??$.profileId,dt=r.driftByAgentId.get($.id),Rn=n.delegationSourceByRequester[$.id],Yr=n.limitByAgent[$.id],Ps=vw($,n.profiles,n.modelServerStatusByServer),le=n.launchFailureByAgent[$.id],ge=se[$.id]??null;return o.jsxs("li",{className:U("flex flex-col gap-2 py-3 first:pt-0 last:pb-0",B&&"rounded-md bg-raised px-2"),children:[o.jsxs("button",{type:"button",onClick:()=>void n.selectAgent($.id),className:"flex min-w-0 flex-col items-start gap-0.5 text-left","aria-pressed":B,children:[o.jsxs("span",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:[o.jsx("span",{className:"font-medium text-content",children:$.name}),dt&&o.jsx("span",{"aria-label":"update available",className:"rounded-full bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary",children:"update available"}),Rn&&o.jsx("span",{"aria-label":`delegation source ${Rn}`,title:Rn==="mcp"?"Last delegation arrived via the MCP server":"Last delegation arrived via .ideai/requests",className:"rounded-full bg-raised px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-muted",children:Rn}),ge&&o.jsx(RA,{state:ge})]}),o.jsx("span",{className:"text-xs text-muted",children:Ee}),ue&&o.jsxs("span",{className:"block w-full min-w-0 truncate text-xs text-primary",children:["running in IdeA · ",ue.sessionId??ue.nodeId]})]}),Yr&&o.jsx(TA,{state:Yr,busy:n.busy,onCancelResume:()=>void n.cancelResume($.id),onSetResumeAt:_e=>void n.setResumeAt($.id,_e)}),o.jsx(DA,{status:Ps,failure:le}),o.jsx(QP,{requester:$.id}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.profiles.length>0&&o.jsxs("select",{"aria-label":`profile for ${$.name}`,value:$.profileId,disabled:n.busy,onChange:_e=>{const St=_e.target.value;St&&St!==$.profileId&&re({agentId:$.id,profileId:St})},className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[n.profiles.every(_e=>_e.id!==$.profileId)&&o.jsx("option",{value:$.profileId,children:$.profileId}),n.profiles.map(_e=>o.jsx("option",{value:_e.id,children:_e.name},_e.id))]}),dt&&o.jsx(M,{size:"sm",variant:"primary","aria-label":`sync ${$.name}`,disabled:n.busy||r.driftBusy,onClick:()=>void r.syncAgent($.id,n.refresh),children:"Sync"}),he||ue?o.jsx(M,{size:"sm",variant:"ghost","aria-label":`stop ${$.name}`,onClick:()=>oe($.id),className:"text-danger hover:text-danger",children:"Stop"}):o.jsx(M,{size:"sm",variant:"primary","aria-label":`launch ${$.name}`,disabled:n.busy||I!==null,onClick:()=>Y($.id),children:"Launch"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete ${$.name}`,disabled:n.busy,onClick:()=>void n.deleteAgent($.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},$.id)})})}),I!==null&&o.jsx("div",{className:"border-t border-border p-4",children:o.jsx("div",{className:"h-96 overflow-hidden rounded-lg border border-border bg-surface",children:o.jsx(hp,{cwd:t,open:($,B)=>n.launchAgent(I,{...$,nodeId:G[I]},B),reattach:($,B)=>s.agent.reattach($,B),sessionId:z[I]??null,onSessionId:$=>j(B=>({...B,[I]:$})),systemPermissions:se[I]??null},I)})}),pe&&v&&o.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Skills — ",pe.name]}),pe.skills.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No skills assigned."}):o.jsx("ul",{className:"flex flex-wrap gap-1.5",children:pe.skills.map($=>{const B=_.find(he=>he.id===$.skillId)?.name??$.skillId;return o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[o.jsx("span",{children:B}),o.jsx("button",{type:"button","aria-label":`unassign ${B}`,disabled:n.busy,onClick:()=>void k($.skillId),className:"text-faint hover:text-danger",children:"✕"})]},$.skillId)})}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsxs("select",{"aria-label":"skill to assign",value:S,onChange:$=>N($.target.value),disabled:n.busy,className:U("h-9 min-w-0 flex-1 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— assign a skill —"}),_.filter($=>!pe.skills.some(B=>B.skillId===$.id)).map($=>o.jsxs("option",{value:$.id,children:[$.name," (",$.scope,")"]},$.id))]}),o.jsx(M,{variant:"primary","aria-label":"assign skill",disabled:n.busy||!S,onClick:()=>void A(),children:"Assign"})]})]}),pe&&o.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Context — ",pe.name]}),o.jsx("code",{className:"text-xs text-muted",children:pe.contextPath})]}),o.jsx("textarea",{"aria-label":"agent context",value:D,onChange:$=>R($.target.value),rows:10,className:U("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:n.busy}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.busy&&o.jsx(Me,{size:14}),o.jsx(M,{variant:"primary",disabled:n.busy,onClick:()=>void n.saveContext(D),children:"Save"})]})]}),T&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm profile change",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Changer le moteur IA"}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Changer le moteur abandonne l'historique de conversation (le contexte et la mémoire sont conservés). Continuer ?"}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.jsx(M,{variant:"ghost","aria-label":"cancel profile change",disabled:n.busy,onClick:()=>re(null),children:"Annuler"}),o.jsx(M,{variant:"primary","aria-label":"confirm profile change",loading:n.busy,disabled:n.busy,onClick:()=>void ee(),children:"Continuer"})]})]})})]})}function RA({state:e}){const t=e.runtimeLock.state==="locked",n=t?"Verrouillé":e.effective==="allow"?"Autorisé":e.effective==="deny"?"Interdit":"Demande";return o.jsxs("span",{"aria-label":`network ${n}`,title:t?e.runtimeLock.reason??"Réseau verrouillé par le runtime":`État effectif : ${n}`,className:U("rounded-full px-2 py-0.5 text-xs font-medium",t?"bg-warning/15 text-warning":e.effective==="allow"?"bg-success/15 text-success":e.effective==="deny"?"bg-danger/15 text-danger":"bg-primary/15 text-primary"),children:["Réseau: ",n]})}function Pu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function yw(e,t){const{layout:n,terminal:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState(0),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=g.useCallback(A=>{i(A),a(k=>k+1)},[]);g.useEffect(()=>{if(!e||!n){i(null);return}let A=!1;return d(!0),n.loadLayout(e,t).then(k=>{A||f(k)}).catch(k=>{A||u(Pu(k))}).finally(()=>{A||d(!1)}),()=>{A=!0}},[n,e,t,f]);const p=g.useCallback(async A=>{if(!(!e||!n)){d(!0),u(null);try{f(await n.mutateLayout(e,A,t))}catch(k){u(Pu(k))}finally{d(!1)}}},[n,e,t,f]),m=g.useCallback(async A=>{if(!(!e||!n||A.length===0)){d(!0),u(null);try{let k=null;for(const D of A)k=await n.mutateLayout(e,D,t);k&&f(k)}catch(k){u(Pu(k))}finally{d(!1)}}},[n,e,t,f]),x=g.useCallback((A,k)=>p(XE(A,k)),[p]),w=g.useCallback(async(A,k)=>{await p({type:"merge",container:A,keepIndex:k})},[p]),v=g.useCallback((A,k)=>p({type:"resize",container:A,weights:k}),[p]),_=g.useCallback((A,k)=>p({type:"move",from:A,to:k}),[p]),y=g.useCallback((A,k)=>p({type:"setSession",target:A,session:k}),[p]),b=g.useCallback(async(A,k)=>{const D=s?Ja(s).find(O=>O.id===A):void 0,R=D?.agent??null,E=D?.session??null;if(k!==R&&(await m([{type:"setCellAgent",target:A,agent:k},{type:"setSession",target:A,session:null},{type:"setCellConversation",target:A,conversationId:null}]),E&&!R&&r))try{await r.closeTerminal(E)}catch{}},[s,m,r]),C=g.useCallback(async(A,k,D)=>{const R=s?Ja(s).find(W=>W.id===A):void 0,E=R?.agent??null,O=R?.session??null,I=[];if(k!==E&&I.push({type:"setCellAgent",target:A,agent:k},{type:"setCellConversation",target:A,conversationId:null}),D!==O&&I.push({type:"setSession",target:A,session:D}),await m(I),O&&O!==D&&!E&&r)try{await r.closeTerminal(O)}catch{}},[s,m,r]),S=g.useCallback((A,k)=>p({type:"setCellConversation",target:A,conversationId:k}),[p]),N=g.useCallback((A,k)=>{i(D=>D&&GE(D,A,k)),a(D=>D+1)},[]),L=g.useCallback(A=>{i(k=>k&&YE(k,A)),a(k=>k+1)},[]);return{layout:s,layoutVersion:l,error:c,busy:h,split:x,merge:w,resize:v,move:_,setSession:y,setCellAgent:b,attachLiveAgentToCell:C,setCellConversation:S,setPluginLayoutState:N,replacePluginLayoutWithTerminal:L}}function MA(e,t,n){return e&&t&&!n}function IA({projectId:e,cwd:t,layoutId:n,onOpenConversation:r,onOpenPluginsSettings:s}){const i=yw(e,n),l=eo(e);return i.layout?o.jsxs("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%",position:"relative"},children:[i.error&&o.jsx("p",{role:"alert",style:{color:"crimson",margin:0},children:i.error}),o.jsx(xp,{node:i.layout.root,cwd:t,vm:i,parentSplit:null,projectId:e,workState:l.state,refreshWorkState:l.refresh,onOpenConversation:r,onOpenPluginsSettings:s})]}):o.jsx("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%"},children:i.error?o.jsx("p",{role:"alert",style:{color:"crimson"},children:i.error}):o.jsx("p",{children:"Loading layout…"})})}function xp({node:e,cwd:t,vm:n,parentSplit:r,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c}){switch(e.type){case"customPluginLayout":return o.jsx(yA,{projectId:s,cell:e.node,onStateChange:u=>n.setPluginLayoutState(e.node.id,u),onOpenPlugins:()=>c?.(),onChooseAnotherLayout:()=>n.replacePluginLayoutWithTerminal(e.node.id)});case"leaf":return o.jsx(BA,{id:e.node.id,session:e.node.session??null,agent:e.node.agent??null,conversationId:e.node.conversationId??null,agentWasRunning:e.node.agentWasRunning??!1,cwd:t,vm:n,parentSplit:r,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a});case"split":return o.jsx(zA,{split:e.node,cwd:t,vm:n,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c});case"grid":return o.jsx($A,{grid:e.node,cwd:t,vm:n,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c})}}function OA(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}const Vi={banner:3,veil:4,controls:5};function BA({id:e,session:t,agent:n,conversationId:r,agentWasRunning:s,cwd:i,vm:l,parentSplit:a,projectId:c,workState:u,refreshWorkState:h,onOpenConversation:d}){const f=a!==null&&a.siblings===2,p=a&&a.index===0?1:0,{agent:m,input:x,system:w}=fe(),{portal:v,overlay:_}=yP(c,n??null),[y,b]=g.useState([]);g.useEffect(()=>{if(!m)return;let le=!1;return m.listAgents(c).then(ge=>{le||b(ge)}).catch(()=>{}),()=>{le=!0}},[m,c]);const[C,S]=g.useState([]),N=()=>{m?.listLiveAgents&&m.listLiveAgents(c).then(S).catch(()=>{})};g.useEffect(()=>{if(!m?.listLiveAgents)return;let le=!1;return m.listLiveAgents(c).then(ge=>{le||S(ge)}).catch(()=>{}),()=>{le=!0}},[m,c]),g.useEffect(()=>{if(!w)return;let le,ge=!1;return w.onDomainEvent(_e=>{(_e.type==="agentLaunched"||_e.type==="agentExited")&&N()}).then(_e=>{ge?_e():le=_e}),()=>{ge=!0,le?.()}},[w,m,c]);const L=n??null,{active:A}=mw(L??""),{statusForAgent:k}=NA(),D=L?y.find(le=>le.id===L):void 0,R=k(D),E=CA(R),O=jA(R),I=L?u?.agents.find(le=>le.agentId===L):void 0,W=I?.tickets.find(le=>le.status==="inProgress"),G=I?.tickets.filter(le=>le.status==="queued")??[],P=Math.max(I?.inboxDepth??0,I?.inbox?.length??0,G.length),z=I?.backgroundTasks?.filter(le=>le.status==="completed"||le.status==="failed"||le.status==="cancelled")??[],j=I?.busy.state==="busy"||!!W,se=W?.source.kind==="agent"?W:void 0,q=W?.conversationId??r??null;async function T(){if(!(!L||!x))try{await x.interrupt(c,L),await h()}catch(le){oe({message:px(le)})}}const re=le=>C.find(ge=>ge.agentId===le),ee=async(le,ge)=>{const _e=px(le);if(!mx(le))return{message:_e};const Dt=(m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C).find(H=>H.agentId===ge);return{message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:Dt&&Dt.nodeId!==e?Dt.nodeId:void 0}},Q=le=>{if(!l.layout)return;const ge=Ja(l.layout).find(_e=>_e.id!==e&&(_e.agent??null)===le);return ge?{nodeId:ge.id}:void 0},V=le=>{const ge=re(le);if(!(!ge||ge.kind!=="pty"||ge.nodeId===e))return Q(le)?void 0:ge},[Y,oe]=g.useState(null),[pe,Pe]=g.useState(null),[$,B]=g.useState(null),[he,ue]=g.useState(0);g.useEffect(()=>{if(!L||!m?.attachLiveAgent||pe)return;const le=V(L);if(!le?.sessionId||le.sessionId===t)return;let ge=!1;return(async()=>{const _e=await m.attachLiveAgent(c,L,e);ge||(await l.attachLiveAgentToCell(e,L,_e.sessionId??le.sessionId),ge||ue(St=>St+1))})().catch(()=>{}),()=>{ge=!0}},[C,L,t]);const Ee=async(le,ge,_e)=>{const St=V(L);if(St?.sessionId&&m.attachLiveAgent){const te=(await m.attachLiveAgent(c,L,e)).sessionId??St.sessionId;l.setSession(e,te);const xe=await m.reattach(te,ge);return N(),xe.handle}const Dt=await m.launchAgent(c,L,{...le,conversationId:_e,nodeId:e},ge).catch(async H=>{throw mx(H)&&oe(await ee(H,L)),H});return Dt.assignedConversationId&&l.setCellConversation(e,Dt.assignedConversationId),Dt},dt=m&&L?(le,ge)=>r?(Promise.resolve(m.inspectConversation?.(c,L,r)).then(_e=>B(_e??{})).catch(()=>B({})),new Promise((_e,St)=>{Pe({opts:le,onData:ge,resolve:_e,reject:St})})):Ee(le,ge,void 0):void 0,Rn=()=>{const le=pe;le&&(Pe(null),B(null),Ee(le.opts,le.onData,r??void 0).then(le.resolve,le.reject))},Yr=()=>{const le=pe;le&&(Pe(null),B(null),l.setCellConversation(e,null),Ee(le.opts,le.onData,void 0).then(le.resolve,le.reject))},Ps=m&&L?(le,ge)=>m.reattach(le,ge):void 0;return o.jsxs("div",{"data-testid":"layout-leaf","data-node-id":e,style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0,border:"1px solid #2a2a2a",boxSizing:"border-box",overflow:"hidden"},children:[o.jsxs("div",{style:{position:"absolute",top:2,right:16,zIndex:Vi.controls,display:"flex",gap:2,alignItems:"center"},children:[o.jsxs("select",{"aria-label":`agent selector ${e}`,value:L??"",onChange:le=>{const ge=le.target.value;if(ge===""){oe(null),l.setCellAgent(e,null);return}(async()=>{const _e=m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C;S(_e);const St=Q(ge);if(St){oe({message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:St.nodeId});return}const Dt=_e.find(te=>te.agentId===ge);if(Dt&&Dt.kind==="pty"&&Dt.nodeId!==e){if(!m?.attachLiveAgent||!Dt.sessionId){oe({message:"Session active introuvable pour cet agent."});return}oe(null);const te=await m.attachLiveAgent(c,ge,e);await l.attachLiveAgentToCell(e,ge,te.sessionId??Dt.sessionId),N();return}oe(null),await l.setCellAgent(e,ge)})().catch(async _e=>oe(await ee(_e,ge)))},style:{fontSize:11,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,padding:"1px 2px",maxWidth:100},children:[o.jsx("option",{value:"",children:"Plain"}),y.map(le=>{const ge=Q(le.id),_e=V(le.id);return o.jsxs("option",{value:le.id,disabled:!!ge,children:[le.name,ge?" (visible ailleurs)":_e?" (arrière-plan)":""]},le.id)})]}),o.jsx("button",{type:"button",title:"Split into columns","aria-label":`split ${e} columns`,onClick:()=>void l.split(e,"row"),children:"⬌"}),o.jsx("button",{type:"button",title:"Split into rows","aria-label":`split ${e} rows`,onClick:()=>void l.split(e,"column"),children:"⬍"}),f&&o.jsx("button",{type:"button",title:"Close this terminal","aria-label":`close ${e}`,onClick:()=>void l.merge(a.container,p),children:"✕"})]}),L&&(j||P>0||z.length>0||q)&&o.jsxs("div",{role:"status","aria-live":"polite",style:{position:"absolute",top:30,left:4,zIndex:Vi.banner,display:"flex",maxWidth:"calc(100% - 8px)",alignItems:"center",gap:4,overflow:"hidden"},children:[j&&o.jsx("span",{title:se?.requesterLabel??W?.taskPreview,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-warning, #d49b3a)",borderRadius:3,background:"rgba(212, 155, 58, 0.16)",color:"var(--color-warning, #d49b3a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:se?`Busy · ${se.requesterLabel}`:"Busy"}),!j&&P>0&&o.jsxs("span",{title:`${P} pending message${P===1?"":"s"}`,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued · ",P]}),j&&P>0&&o.jsxs("span",{title:`${P} queued message${P===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued ",P]}),z.length>0&&o.jsxs("span",{title:`${z.length} background task result${z.length===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-success, #57b36a)",borderRadius:3,background:"rgba(87, 179, 106, 0.14)",color:"var(--color-success, #57b36a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Task done ",z.length]}),j&&o.jsx("button",{type:"button","aria-label":`cancel current turn ${e}`,title:"Cancel current turn",onClick:()=>void T(),disabled:!x,style:{flexShrink:0,border:"1px solid var(--color-danger, #d45a5a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-danger, #d45a5a)",cursor:x?"pointer":"default",fontSize:11,padding:"1px 6px"},children:"Cancel"}),q&&d&&o.jsx("button",{type:"button","aria-label":`open cell conversation ${e}`,title:"Open conversation history",onClick:()=>d(q),style:{flexShrink:0,border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",cursor:"pointer",fontSize:11,padding:"1px 6px"},children:"History"})]}),o.jsxs("div",{style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0},children:[o.jsx(hp,{cwd:i,open:dt,reattach:Ps,sessionId:t,onSessionId:le=>void l.setSession(e,le),agentMode:L!=null,portal:L!=null?v:void 0,refitSignal:l.layoutVersion},`${e}-${L??"plain"}-${he}`),!E&&MA(L!=null,!!_,A)&&o.jsx("div",{"data-testid":"write-portal-overlay",role:"status","aria-live":"polite",style:{position:"absolute",inset:0,zIndex:Vi.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.45)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:o.jsx("span",{style:{background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"6px 12px"},children:"Un agent est en train de parler…"})}),!E&&L!=null&&o.jsx(XP,{projectId:c,agentId:L}),E&&o.jsx("div",{"data-testid":"model-server-overlay",role:"status","aria-live":"polite","aria-label":"model server launch",style:{position:"absolute",inset:0,zIndex:Vi.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0,maxWidth:"80%",background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"8px 14px"},children:[o.jsx("span",{children:E}),O&&o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"model-server-progress",role:"progressbar","aria-label":"progression du téléchargement","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":O.percent!=null?Math.round(O.percent):void 0,style:{position:"relative",width:220,maxWidth:"100%",height:6,borderRadius:3,overflow:"hidden",background:"var(--color-raised, #2a2a2a)"},children:o.jsx("div",{style:O.percent!=null?{height:"100%",width:`${O.percent}%`,background:"var(--color-primary, #5b9bd5)",transition:"width 120ms linear"}:{position:"absolute",top:0,bottom:0,width:"40%",background:"var(--color-primary, #5b9bd5)",animation:"model-server-indeterminate 1.1s ease-in-out infinite"}})}),(O.percent!=null||O.bytesLabel)&&o.jsxs("span",{"data-testid":"model-server-progress-label",style:{fontSize:12,color:"var(--color-content-muted, #9a9a9a)"},children:[O.percent!=null?`${Math.round(O.percent)} %`:"",O.percent!=null&&O.bytesLabel?" · ":"",O.bytesLabel??""]}),O.source&&o.jsx("span",{"data-testid":"model-server-source",style:{fontSize:11,color:"var(--color-content-muted, #9a9a9a)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:O.source,children:O.source})]})]})})]}),Y&&o.jsxs("div",{role:"status",style:{position:"absolute",bottom:4,left:4,right:4,margin:0,fontSize:11,color:"var(--color-content-muted, #9a9a9a)",background:"var(--color-surface, #1e1e1e)",padding:"2px 6px",borderRadius:3,zIndex:Vi.banner,display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[o.jsx("span",{style:{minWidth:0},children:Y.message}),Y.goToNodeId&&o.jsx("button",{type:"button","aria-label":"aller à la cellule",onClick:()=>{OA(Y.goToNodeId),oe(null)},style:{flexShrink:0,fontSize:11,cursor:"pointer",background:"transparent",color:"var(--color-primary, #5b9bd5)",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,padding:"1px 6px"},children:"Aller à la cellule"})]}),pe&&o.jsx(pP,{agentWasRunning:s,details:$,onResume:Rn,onNewConversation:Yr})]})}function zA({split:e,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a}){const c=e.direction==="row",u=e.children.map(m=>m.weight),h=g.useRef(null),[d,f]=g.useState(null),p=Ih(d??u);return o.jsx("div",{ref:h,"data-testid":"layout-split","data-direction":e.direction,style:{display:"flex",flexDirection:c?"row":"column",width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.children.map((m,x)=>o.jsxs("div",{style:{display:"contents"},children:[o.jsx("div",{style:{flexBasis:`${p[x]}%`,flexGrow:0,flexShrink:0,minHeight:0,minWidth:0,overflow:"hidden"},children:o.jsx(xp,{node:m.node,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a,parentSplit:{container:e.id,index:x,siblings:e.children.length}})}),xf(Zg(u,x,w)),onDragEnd:w=>{const v=Zg(u,x,w);f(null),n.resize(e.id,v)}})]},bw(m.node,x)))})}function FA({isRow:e,container:t,onDragMove:n,onDragEnd:r}){const s=g.useRef(null);function i(u){if(s.current===null)return null;const h=t.current?.getBoundingClientRect(),d=h?e?h.width:h.height:0;return d<=0?null:(u-s.current)/d}function l(u){u.preventDefault(),u.currentTarget.setPointerCapture(u.pointerId),s.current=e?u.clientX:u.clientY}function a(u){if(s.current===null)return;const h=i(e?u.clientX:u.clientY);h!==null&&n(h)}function c(u){const h=i(e?u.clientX:u.clientY);s.current=null,h!==null&&r(h)}return o.jsx("div",{role:"separator","aria-orientation":e?"vertical":"horizontal",onPointerDown:l,onPointerMove:a,onPointerUp:c,style:{flex:"0 0 6px",cursor:e?"col-resize":"row-resize",background:"#3a3a3a",touchAction:"none"}})}function $A({grid:e,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a}){const c=Ih(e.colWeights).map(h=>`${h}fr`).join(" "),u=Ih(e.rowWeights).map(h=>`${h}fr`).join(" ");return o.jsx("div",{"data-testid":"layout-grid-container",style:{display:"grid",gridTemplateColumns:c,gridTemplateRows:u,width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.cells.map((h,d)=>o.jsx("div",{style:{gridColumn:`${h.col+1} / span ${h.colSpan}`,gridRow:`${h.row+1} / span ${h.rowSpan}`,minHeight:0,minWidth:0,overflow:"hidden"},children:o.jsx(xp,{node:h.node,cwd:t,vm:n,parentSplit:null,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a})},bw(h.node,d)))})}function bw(e,t){return e.node.id??String(t)}function px(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function mx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="AGENT_ALREADY_RUNNING"}function Is(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function gx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="NOT_FOUND"}function WA(e){const{layout:t,system:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{if(!(!e||!t))try{const{layouts:w,activeId:v}=await t.listLayouts(e);s(w),l(_=>_&&w.some(y=>y.id===_)?_:v)}catch(w){h(Is(w))}},[t,e]);g.useEffect(()=>{if(!e||!t){s([]),l(null);return}let w=!1;return c(!0),t.listLayouts(e).then(({layouts:v,activeId:_})=>{w||(s(v),l(_))}).catch(v=>{w||h(Is(v))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[t,e]),g.useEffect(()=>{if(!e||!n)return;let w=!1,v;return n.onDomainEvent(_=>{_.type==="layoutChanged"&&_.projectId===e&&d()}).then(_=>{w?_():v=_}),()=>{w=!0,v?.()}},[n,e,d]);const f=g.useCallback(async w=>{if(!(!e||!t)){c(!0),h(null);try{const v=await t.setActiveLayout(e,w);l(v?.activeId??w)}catch(v){h(Is(v))}finally{c(!1)}}},[t,e]),p=g.useCallback(async(w,v)=>{if(!e||!t)return null;c(!0),h(null);try{const{layoutId:_}=await t.createLayout(e,w,v),y=await t.listLayouts(e);return s(y.layouts),_}catch(_){return h(Is(_)),null}finally{c(!1)}},[t,e]),m=g.useCallback(async(w,v)=>{if(!(!e||!t)){c(!0),h(null);try{await t.renameLayout(e,w,v),s(_=>_.map(y=>y.id===w?{...y,name:v}:y))}catch(_){gx(_)?await d():h(Is(_))}finally{c(!1)}}},[t,e,d]),x=g.useCallback(async w=>{if(!(!e||!t)){if(r.length<=1){h("Cannot delete the last layout.");return}c(!0),h(null);try{const{activeId:v}=await t.deleteLayout(e,w);s(_=>_.filter(y=>y.id!==w)),l(v)}catch(v){gx(v)?await d():h(Is(v))}finally{c(!1)}}},[t,e,r.length,d]);return{layouts:r,activeId:i,busy:a,error:u,setActive:f,create:p,rename:m,deleteLayout:x}}function HA({projectId:e,onActiveLayoutChange:t}){const n=WA(e);g.useEffect(()=>{const _=n.layouts.find(y=>y.id===n.activeId);_&&t(_)},[n.activeId,n.layouts,t]);const[r,s]=g.useState(null),[i,l]=g.useState(""),a=g.useRef(null),[c,u]=g.useState(!1),{registry:h}=gp(),[d,f]=g.useState(null);async function p(_){await n.setActive(_)}async function m(_){n.layouts.length<=1||await n.deleteLayout(_)}function x(_,y){s(_),l(y),setTimeout(()=>a.current?.focus(),0)}async function w(){if(!r)return;const _=i.trim();_&&await n.rename(r,_),s(null),l("")}async function v(_){u(!1);const y=_==="gitGraph"?"Git Graph":"Layout",b=window.prompt("New layout name:",y);if(!b?.trim())return;const C=await n.create(b.trim(),_);C&&await n.setActive(C)}return n.layouts.length===0?null:o.jsxs("div",{"data-testid":"layout-tabs",className:"flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",children:[n.layouts.map(_=>{const y=_.id===n.activeId,b=_.id===r;return o.jsxs("div",{className:U("group flex items-center gap-1 rounded-md border px-1 transition-colors",y?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[b?o.jsx("input",{ref:a,value:i,onChange:C=>l(C.target.value),onBlur:()=>void w(),onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&(s(null),l(""))},"aria-label":`rename layout ${_.name}`,className:"w-24 rounded border border-border bg-base px-1 py-0.5 text-sm text-content focus:outline-none focus:ring-1 focus:ring-primary"}):o.jsxs("button",{type:"button",role:"tab","aria-selected":y,onClick:()=>void p(_.id),onDoubleClick:()=>x(_.id,_.name),className:U("flex items-center gap-1 px-2 py-1 text-sm focus-visible:outline-none",y?"font-semibold text-content":"text-muted hover:text-content"),children:[_.kind==="gitGraph"&&o.jsx("span",{"aria-label":"git graph layout",className:"text-xs text-primary",title:"Git Graph",children:"⎇"}),_.name]}),o.jsx("button",{type:"button","aria-label":`delete layout ${_.name}`,disabled:n.layouts.length<=1,onClick:()=>void m(_.id),className:U("flex h-4 w-4 items-center justify-center rounded text-xs transition-opacity",n.layouts.length<=1?"cursor-not-allowed opacity-20":"opacity-60 hover:opacity-100 group-hover:opacity-100"),children:"×"})]},_.id)}),o.jsxs("div",{className:"relative",children:[o.jsx("button",{type:"button","aria-label":"create layout",onClick:()=>u(_=>!_),className:"flex h-6 w-6 items-center justify-center rounded border border-transparent text-sm text-muted transition-colors hover:border-border hover:text-content",children:"+"}),c&&o.jsxs("div",{role:"menu",className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col rounded-md border border-border bg-surface shadow-lg",children:[o.jsx("button",{type:"button",role:"menuitem","aria-label":"create terminal layout",onClick:()=>void v("terminal"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"Terminal"}),o.jsx("button",{type:"button",role:"menuitem","aria-label":"create git graph layout",onClick:()=>void v("gitGraph"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"⎇ Git graph"}),o.jsx(wA,{registry:h,onSelect:_=>{u(!1),f(`« ${_.layout.label} » (${_.pluginDisplayName}) : la création de layouts plugins nécessite une extension backend pas encore livrée.`)}})]})]}),(n.error||d)&&o.jsx("span",{className:"ml-2 text-xs text-danger",role:"alert",children:n.error??d})]})}class UA extends g.Component{constructor(){super(...arguments);X(this,"state",{error:null,retryKey:0});X(this,"retry",()=>{this.setState(({retryKey:n})=>({error:null,retryKey:n+1}))})}static getDerivedStateFromError(n){return{error:n}}render(){return this.state.error?o.jsx(ke,{title:"Work",children:o.jsxs("div",{role:"alert",className:"rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[o.jsx("p",{className:"font-medium",children:"Work panel failed to render."}),o.jsx("p",{className:"mt-1 text-xs text-danger/80",children:this.state.error.message}),o.jsx(M,{size:"sm",variant:"ghost",className:"mt-2",onClick:this.retry,children:"Retry"})]})}):o.jsx("div",{children:this.props.children},this.state.retryKey)}}function cr(e){return e.length<=8?e:e.slice(0,8)}function qA(e){return e==="inProgress"?"In progress":"Queued"}function VA(e){switch(e){case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed";case"cancelled":return"Cancelled";case"delivered":return"Delivered";case"pending":return"Pending"}}function KA(e){return e==="completed"||e==="failed"||e==="cancelled"}function GA(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function YA(e){if(e.source.kind==="human")return"Human";const t=cr(e.source.agentId);return e.requesterLabel.trim()?`${e.requesterLabel} (${t})`:`Agent ${t}`}function XA(e){switch(e){case"ready":return"Summary";case"missing":return"No summary";case"partial":return"Partial";case"unavailable":return"Unavailable"}}function QA(e){if(e.objectivePreview)return`Goal: ${e.objectivePreview}`;if(e.summaryPreview)return e.summaryPreview;const t=(e.recentTurns??[]).at(-1);return t?`Last: ${t.textPreview}`:null}function xx(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}async function JA(e){if(typeof navigator<"u"&&navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}throw new Error("Clipboard unavailable")}function ZA({summary:e,onOpenConversation:t}){const n=QA(e),[r,s]=g.useState(!1),[i,l]=g.useState(!1);return n?o.jsxs("div",{className:"mt-1 min-w-0 pl-1 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="ready"?"bg-success/10 text-success":"bg-raised text-muted"),children:XA(e.status)}),t?o.jsx("button",{type:"button","aria-label":`open conversation ${e.conversationId}`,className:"min-w-0 flex-1 break-words text-left hover:text-content hover:underline",onClick:()=>t(e.conversationId),children:n}):o.jsx("span",{className:"min-w-0 flex-1 break-words",children:n}),o.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content",onClick:()=>s(a=>!a),children:r?"Hide":"View"}),o.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content disabled:opacity-50",disabled:!n,onClick:()=>{JA(n).then(()=>{l(!0),window.setTimeout(()=>l(!1),1e3)})},children:i?"Copied":"Copy"})]}),r&&o.jsxs("div",{"aria-label":`conversation ${e.conversationId} details`,className:"mt-1 space-y-1 border-l border-border pl-2",children:[e.objectivePreview&&o.jsxs("p",{children:[o.jsx("span",{className:"font-medium text-content",children:"Goal:"})," ",e.objectivePreview]}),e.summaryPreview&&o.jsxs("p",{children:[o.jsx("span",{className:"font-medium text-content",children:"Summary:"})," ",e.summaryPreview]}),(e.recentTurns??[]).length>0&&o.jsx("ul",{className:"space-y-0.5",children:(e.recentTurns??[]).map(a=>o.jsxs("li",{children:[o.jsxs("span",{className:"font-medium text-content",children:[a.role,":"]})," ",a.textPreview]},`${a.atMs}-${a.role}-${a.textPreview}`))})]})]}):null}function eT({ticket:e,summary:t,onOpenConversation:n}){const r=e.taskLen>e.taskPreview.length;return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsxs("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="inProgress"?"bg-warning/15 text-warning":"bg-raised text-muted"),children:["#",e.position+1," ",qA(e.status)]}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"font-medium text-content",children:YA(e)}),o.jsx("span",{className:"text-muted",children:" · "}),o.jsx("span",{className:"break-words",children:e.taskPreview}),r&&o.jsxs("span",{"aria-label":`${e.taskLen-e.taskPreview.length} more characters`,className:"text-muted",children:[" ","+",e.taskLen-e.taskPreview.length]})]}),o.jsx("code",{"aria-label":`ticket ${cr(e.ticketId)}`,title:e.ticketId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.ticketId)})]}),t&&o.jsx(ZA,{summary:t,onOpenConversation:n})]})}function tT({item:e}){return o.jsx("li",{className:"min-w-0 text-xs text-muted",children:o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium text-muted",children:e.kind}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:e.body}),o.jsx("code",{title:e.id,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.id)})]})})}function nT({task:e,onRefresh:t}){const{workState:n}=fe(),[r,s]=g.useState(!1),[i,l]=g.useState(!1),[a,c]=g.useState(null),u=!!(e.stdoutTail||e.stderrTail),h=e.status==="running"||e.status==="pending",d=e.status==="failed"||e.status==="cancelled";async function f(p){l(!0),c(null);try{await p(e.taskId),await t()}catch(m){c(m instanceof Error?m.message:String(m))}finally{l(!1)}}return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",GA(e.status)),children:VA(e.status)}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"font-medium text-content",children:e.kind}),e.exitCode!==null&&o.jsxs("span",{className:"text-muted",children:[" · exit ",e.exitCode]})]}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!h||i,loading:i,onClick:()=>void f(p=>n.cancelBackgroundTask(p)),children:"Cancel"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!u,onClick:()=>s(p=>!p),children:"Output"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!d||i,loading:i,onClick:()=>void f(p=>n.retryBackgroundTask(p)),children:"Retry"}),o.jsx("code",{title:e.taskId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.taskId)})]}),e.summary&&KA(e.status)&&o.jsx("p",{"aria-label":`task ${cr(e.taskId)} summary`,title:e.summary,className:"mt-1 truncate pl-1 text-[11px] text-muted",children:e.summary}),a&&o.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:a}),r&&u&&o.jsxs("pre",{"aria-label":`task ${cr(e.taskId)} output`,className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-canvas p-2 text-[11px] text-muted",children:[e.stdoutTail?`stdout -${e.stdoutTail}`:"",e.stdoutTail&&e.stderrTail?` - -`:"",e.stderrTail?`stderr -${e.stderrTail}`:""]})]})}function rT({agent:e,conversations:t,visibleLeaves:n,layout:r,projectId:s,onRefresh:i,onOpenConversation:l}){const{agent:a}=fe(),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=e.live!==void 0,p=e.busy??{state:"idle"},m=p.state==="busy",x=[...e.tickets??[]].sort((k,D)=>k.position-D.position),w=[...e.inbox??[]].sort((k,D)=>k.createdAtMs-D.createdAtMs),v=[...e.backgroundTasks??[]].sort((k,D)=>D.updatedAtMs-k.updatedAtMs||k.taskId.localeCompare(D.taskId)),_=Math.max(e.inboxDepth??0,w.length,x.length),y=new Set(n.map(k=>k.id)),b=f&&y.has(e.live.nodeId),C=n.find(k=>!k.session&&!k.agent),S=m||x.some(k=>k.status==="inProgress");async function N(){await i()}async function L(){if(!(!e.live||!C||!a?.attachLiveAgent)){d(!0),u(null);try{const k=await a.attachLiveAgent(s,e.agentId,C.id);await r.attachLiveAgentToCell(C.id,e.agentId,k.sessionId),await N(),xx(C.id)}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!1)}}}async function A(){if(!e.live||!a?.stopLiveAgent)return;const k=S?" The current turn will be interrupted.":"";if(window.confirm(`Stop ${e.name}?${k}`)){d(!0),u(null);try{const D=await a.stopLiveAgent(s,e.agentId);if(y.has(e.live.nodeId)){const R=n.find(E=>E.id===e.live?.nodeId);(!R?.session||R.session===D.sessionId)&&await r.setSession(e.live.nodeId,null)}await N()}catch(D){u(D instanceof Error?D.message:String(D))}finally{d(!1)}}}return o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),o.jsx("code",{className:"truncate text-xs text-muted",children:e.profileId})]}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx("span",{className:U("rounded-full px-2 py-0.5 text-xs font-medium",f?"bg-success/15 text-success":"bg-raised text-muted"),children:f?"Live":"Offline"}),o.jsx("span",{className:U("rounded-full px-2 py-0.5 text-xs font-medium",m?"bg-warning/15 text-warning":"bg-raised text-muted"),children:m?"Busy":"Idle"}),_>0&&o.jsxs("span",{"aria-label":`${e.name} queue depth ${_}`,className:"rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary",children:["Queue ",_]}),p.state==="busy"&&o.jsx("code",{"aria-label":`busy ticket ${cr(p.ticket)}`,title:p.ticket,className:"rounded bg-raised px-1.5 py-0.5 text-xs text-muted",children:cr(p.ticket)}),e.live&&b&&o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>xx(e.live.nodeId),children:"Open"}),e.live&&!b&&o.jsx(M,{size:"sm",variant:"ghost",disabled:!C||!a?.attachLiveAgent,loading:h,title:C?void 0:"No empty visible cell available",onClick:()=>void L(),children:"Attach"}),e.live&&o.jsx(M,{size:"sm",variant:"danger",loading:h,disabled:!a?.stopLiveAgent,onClick:()=>void A(),children:"Stop"})]})]}),e.live&&!b&&!C&&o.jsx("p",{className:"mt-1 text-xs text-muted",children:"No empty visible cell."}),c&&o.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:c}),x.length>0&&o.jsx("ul",{"aria-label":`${e.name} tickets`,className:"mt-2 flex flex-col gap-1",children:x.map(k=>o.jsx(eT,{ticket:k,summary:t.get(k.conversationId),onOpenConversation:l},k.ticketId))}),w.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),o.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:w.map(k=>o.jsx(tT,{item:k},k.id))})]}),v.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Background tasks"}),o.jsx("ul",{"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:v.map(k=>o.jsx(nT,{task:k,onRefresh:N},k.taskId))})]})]})}function sT({projectId:e,onOpenConversation:t}){const n=eo(e),r=yw(e),s=n.state?.agents??[],i=r.layout?Ja(r.layout):[],l=new Map((n.state?.conversations??[]).map(a=>[a.conversationId,a]));return o.jsxs(ke,{title:"Work",actions:o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),n.busy&&n.state===null?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading work state…"})]}):s.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agent work state."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:s.map(a=>o.jsx(rT,{agent:a,conversations:l,visibleLeaves:i,layout:r,projectId:e,onRefresh:n.refresh,onOpenConversation:t},a.agentId))})]})}function iT(e){return o.jsx(UA,{children:o.jsx(sT,{...e})})}function Au(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Tu(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function lT(e,t){const{conversation:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(!1),[a,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useRef([]),f=g.useRef(!1),p=g.useCallback(v=>{d.current=v,s(v)},[]),m=g.useCallback(async()=>{if(!f.current){f.current=!0,l(!0),c(null);try{const v=await n.readPage(e,t,{direction:"backward"});p(Tu(v.turns)),h(v.hasMore)}catch(v){c(Au(v))}finally{l(!1),f.current=!1}}},[n,e,t,p]),x=g.useCallback(async()=>{if(f.current)return;const v=d.current[0];if(!v){await m();return}f.current=!0,l(!0),c(null);try{const _=await n.readPage(e,t,{direction:"backward",anchor:v.id});_.turns.length>0&&p(Tu([..._.turns,...d.current])),h(_.hasMore)}catch(_){c(Au(_))}finally{l(!1),f.current=!1}},[n,e,t,m,p]),w=g.useCallback(async()=>{if(!f.current){if(d.current.length===0){await m();return}f.current=!0,l(!0),c(null);try{for(;;){const v=d.current.at(-1);if(!v)break;const _=await n.readPage(e,t,{direction:"forward",anchor:v.id});if(_.turns.length===0||(p(Tu([...d.current,..._.turns])),!_.hasMore))break}}catch(v){c(Au(v))}finally{l(!1),f.current=!1}}},[n,e,t,m,p]);return g.useEffect(()=>{p([]),h(!1),m()},[m,p]),{turns:r,busy:i,error:a,hasMore:u,loadOlder:x,refreshTail:w}}function vx(e){return e.length<=8?e:e.slice(0,8)}function Lu(e){return e.kind==="human"?"human":`agent:${e.agentId}`}function oT(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleString()}catch{return""}}function aT(e){switch(e){case"prompt":return"Prompt";case"response":return"Response";case"toolActivity":return"Tool"}}function cT({turn:e,sideClass:t}){const[n,r]=g.useState(!1);return o.jsx("div",{className:U("flex flex-col",t),children:o.jsxs("div",{className:"max-w-[80%] rounded-md border border-border bg-surface/60 px-3 py-1.5 text-xs text-muted",children:[o.jsxs("button",{type:"button",className:"flex items-center gap-1.5 font-medium hover:text-content",onClick:()=>r(s=>!s),"aria-expanded":n,children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),"Tool activity",o.jsxs("span",{className:"text-faint",children:["· ",e.textLen," chars"]})]}),n&&o.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted",children:e.text})]})})}function uT({projectId:e,conversationId:t,onClose:n}){const r=lT(e,t),s=eo(e),i=g.useMemo(()=>{const u=new Map;for(const h of s.state?.agents??[])h.name.trim()&&u.set(h.agentId,h.name.trim());return u},[s.state]),l=g.useMemo(()=>{const u=[],h=new Map;for(const d of r.turns){const f=Lu(d.source);if(h.has(f))continue;const p=u.length===0?"left":"right",m=d.source.kind==="human"?"User":i.get(d.source.agentId)??`Agent ${vx(d.source.agentId)}`;h.set(f,{label:m,side:p}),u.push(f)}return{order:u,meta:h}},[r.turns,i]),a=g.useMemo(()=>{const u=l.order.map(h=>l.meta.get(h)?.label??"?");return u.length>=2?`${u[0]} ↔ ${u[1]}`:u.length===1?u[0]:"Conversation"},[l]);function c(u){return l.meta.get(Lu(u))?.side??"left"}return o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border bg-surface px-4 py-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:a}),o.jsx("code",{className:"truncate text-xs text-muted",title:t,children:vx(t)})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.refreshTail(),loading:r.busy,children:"Refresh"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"← Retour aux terminaux"})]})]}),r.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),o.jsxs("div",{className:"flex flex-1 flex-col gap-2 overflow-auto px-4 py-3",children:[r.hasMore&&o.jsx("div",{className:"flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.loadOlder(),loading:r.busy,children:"Charger les tours précédents"})}),r.busy&&r.turns.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Chargement du fil…"})]}):r.turns.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun tour pour le moment."}):r.turns.map(u=>{const h=c(u.source),d=h==="right"?"items-end":"items-start";if(u.role==="toolActivity")return o.jsx(cT,{turn:u,sideClass:d},u.id);const f=l.meta.get(Lu(u.source)),p=oT(u.atMs);return o.jsx("div",{className:U("flex flex-col",d),children:o.jsxs("div",{className:U("max-w-[80%] rounded-lg border px-3 py-2 text-sm",h==="right"?"border-primary/20 bg-primary/10 text-content":"border-border bg-raised text-content"),children:[o.jsxs("div",{className:"mb-1 flex items-baseline gap-2 text-xs text-muted",children:[o.jsx("span",{className:"font-medium text-content",children:f?.label??"?"}),o.jsxs("span",{children:["· ",aT(u.role)]}),p&&o.jsxs("span",{className:"text-faint",children:["· ",p]})]}),o.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.text})]})},u.id)})]})]})}function Du(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function dT(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function hT(){const{modelServer:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{l(!0),s(null);try{n(await e.listModelServers())}catch(f){s(Du(f))}finally{l(!1)}},[e]);g.useEffect(()=>{a()},[a]);const c=g.useCallback(async f=>{l(!0),s(null);try{const p=await e.saveModelServer(f);return n(m=>{const x=m.findIndex(w=>w.id===p.id);if(x>=0){const w=m.slice();return w[x]=p,w}return[...m,p]}),p}catch(p){return s(Du(p)),null}finally{l(!1)}},[e]),u=g.useCallback(async f=>{l(!0),s(null);try{return await e.deleteModelServer(f),n(p=>p.filter(m=>m.id!==f)),!0}catch(p){return dT(p)==="model_server_in_use"?s("Ce serveur est encore utilisé par un profil : détache-le d'abord (choisis « aucun » ou un autre serveur) avant de le supprimer."):s(Du(p)),!1}finally{l(!1)}},[e]),h=g.useCallback(async f=>{try{return await e.previewModelServerCommand(f)}catch{return null}},[e]),d=g.useCallback(()=>s(null),[]);return{servers:t,error:r,busy:i,reload:a,save:c,remove:u,preview:h,clearError:d}}function fT(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function pT(e){return e.startsWith("/")||e.startsWith("\\")?!0:/^[a-zA-Z]:[/\\]/.test(e)}function mT(e){if(/\s/.test(e)||e.startsWith("http://")||e.startsWith("https://")||(e.match(/:/g)??[]).length>1)return!1;const[t,n]=e.includes(":")?[e.slice(0,e.indexOf(":")),e.slice(e.indexOf(":")+1)]:[e,void 0];if(n!==void 0&&n.length===0)return!1;const r=t.split("/");return r.length===2&&r[0].length>0&&r[1].length>0}function gT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),fT(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&(t.port="Port must be an integer between 1 and 65535."),e.servedModelName.trim().length===0&&(t.servedModelName="Le nom du modèle est requis."),(e.host.trim().length===0||/\s/.test(e.host))&&(t.host="L'adresse d'écoute est requise et ne doit pas contenir d'espace.");const n=e.modelSource;return n&&(n.type==="localPath"?n.path.trim().length===0?t.modelSource="Le chemin du fichier .gguf est requis.":pT(n.path.trim())||(t.modelSource="Le chemin du fichier doit être absolu."):n.repo.trim().length===0?t.modelSource="Le modèle Hugging Face est requis.":mT(n.repo.trim())||(t.modelSource="Format attendu : auteur/modèle ou auteur/modèle:quant (ex. unsloth/Qwen3.5-9B-GGUF:Q4_K_M).")),e.autoStart&&!n&&(t.modelSource="Le démarrage automatique nécessite une source de modèle."),t}function xT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`srv-${Math.random().toString(36).slice(2,10)}`}function vT(){return{id:xT(),kind:"llamaCpp",name:"",baseURL:"http://localhost:8080/v1",port:8080,servedModelName:"",host:"127.0.0.1",jinja:!1,args:[],autoStart:!1,stopPolicy:"stopOnAppExit"}}function _T(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function yT(e){if(!e)return"";if(e.type==="localPath"){const r=e.path.trim();return r.length===0?"":(r.split(/[/\\]/).pop()??"").replace(/\.gguf$/i,"")}const t=e.repo.trim();return t.length===0?"":(t.includes(":")?t.slice(0,t.indexOf(":")):t).split("/").pop()??""}const bT=["--model","-m","-hf","--port","--host","-ngl","--gpu-layers","-c","--ctx-size","--jinja"];function wT(e){const t=new Set(bT),n=new Set;for(const r of e){const s=r.includes("=")?r.slice(0,r.indexOf("=")):r;t.has(s)&&n.add(s)}return[...n]}function Et({children:e}){return o.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function Os({children:e}){return o.jsx("small",{className:"text-xs text-muted",children:e})}const ST=[{value:"stopOnAppExit",label:"Stop on app exit"},{value:"keepAlive",label:"Keep alive"},{value:"stopWhenUnused",label:"Stop when unused"}];function kT({vm:e}){const[t,n]=g.useState(null);function r(){e.clearError(),n(vT())}function s(l){e.clearError(),n({...l})}async function i(){if(!t)return;await e.save(t)&&n(null)}return o.jsx(ke,{"aria-label":"local model servers",title:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:"Local model servers"}),o.jsx(M,{size:"sm","aria-label":"add model server",onClick:r,className:"ml-auto",children:"Add server"})]}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[e.error&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error}),e.servers.length===0&&!t&&o.jsx("p",{className:"text-xs text-muted",children:"No local server declared yet. Add one to auto-manage a `llama-server`, or keep using an external endpoint."}),o.jsx("ul",{className:"flex list-none flex-col gap-2 p-0",children:e.servers.map(l=>o.jsxs("li",{className:"flex items-center gap-2 rounded-md border border-border bg-raised p-2",children:[o.jsxs("span",{className:"flex min-w-0 flex-col",children:[o.jsx("strong",{className:"truncate text-sm text-content",children:l.name}),o.jsxs("span",{className:"truncate text-xs text-muted",children:[l.baseURL," · ",l.servedModelName,l.autoStart?" · auto-start":""]})]}),o.jsxs("span",{className:"ml-auto flex items-center gap-1",children:[o.jsx(M,{size:"sm","aria-label":`edit ${l.name}`,onClick:()=>s(l),disabled:e.busy,children:"Edit"}),o.jsx(sr,{size:"sm","aria-label":`delete ${l.name}`,onClick:()=>void e.remove(l.id),disabled:e.busy,children:"×"})]})]},l.id))}),t&&o.jsx(NT,{draft:t,busy:e.busy,preview:e.preview,onChange:n,onCancel:()=>{e.clearError(),n(null)},onSubmit:()=>void i()})]})})}function CT({kind:e,onSelect:t}){const n=(r,s)=>{const i=e===r;return o.jsx("button",{type:"button","aria-pressed":i,onClick:()=>t(r),className:U("h-8 flex-1 rounded-md px-3 text-xs font-medium transition-colors",i?"bg-primary text-white":"bg-raised text-muted hover:text-content"),children:s})};return o.jsxs("div",{role:"group","aria-label":"source du modèle",className:"flex gap-1 rounded-md border border-border p-1",children:[n("huggingFace","Télécharger depuis Hugging Face"),n("localPath","Fichier .gguf local")]})}function jT({preview:e,autoStart:t}){const[n,r]=g.useState(!1),s=t?"Commande générée":"Commande à lancer manuellement";async function i(){if(e)try{await navigator.clipboard.writeText(e.display),r(!0),setTimeout(()=>r(!1),1500)}catch{}}return o.jsxs("section",{"aria-label":"command preview",className:"flex flex-col gap-1 rounded-md border border-border bg-raised p-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Et,{children:s}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"copier la commande",onClick:()=>void i(),disabled:!e,className:"ml-auto",children:n?"Copié":"Copier"})]}),e?o.jsx("code",{"aria-label":"preview command line",className:"whitespace-pre-wrap break-all font-mono text-xs text-content",children:e.display}):o.jsx("span",{className:"text-xs text-muted",children:"Renseigne une source de modèle pour voir la commande."})]})}function NT({draft:e,busy:t,preview:n,onChange:r,onCancel:s,onSubmit:i}){const l=gT(e),a=Object.keys(l).length===0,c=b=>r({...e,...b}),[u,h]=g.useState(e.modelSource?.type??"huggingFace"),d=e.modelSource?.type==="huggingFace"?e.modelSource.repo:"",f=e.modelSource?.type==="localPath"?e.modelSource.path:"";function p(b){const C={modelSource:b};if(e.servedModelName.trim().length===0){const S=yT(b);S.length>0&&(C.servedModelName=S)}c(C)}function m(b){b!==u&&(h(b),c({modelSource:void 0}))}const[x,w]=g.useState(null),v=JSON.stringify({modelSource:e.modelSource,port:e.port,host:e.host,gpuLayers:e.gpuLayers,contextSize:e.contextSize,jinja:e.jinja,binaryPath:e.binaryPath,args:e.args}),_=g.useRef(e);_.current=e,g.useEffect(()=>{if(!e.modelSource){w(null);return}let b=!1;const C=setTimeout(()=>{n(_.current).then(S=>{b||w(S)})},250);return()=>{b=!0,clearTimeout(C)}},[v,n]);const y=wT(e.args);return o.jsxs("fieldset",{"aria-label":"model server editor",className:"flex flex-col gap-3 rounded-md border border-primary/40 p-3",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:e.name.trim().length>0?e.name:"New server"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Nom"}),o.jsx(ce,{"aria-label":"server name",value:e.name,invalid:!!l.name,onChange:b=>c({name:b.target.value})}),l.name&&o.jsx("small",{className:"text-xs text-danger",children:l.name})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Source du modèle"}),o.jsx(CT,{kind:u,onSelect:m})]}),u==="huggingFace"?o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Modèle Hugging Face"}),o.jsx(ce,{"aria-label":"hugging face model",value:d,placeholder:"unsloth/Qwen3.5-9B-GGUF:Q4_K_M",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"huggingFace",repo:C})}}),o.jsx(Os,{children:"llama.cpp téléchargera/cache le fichier automatiquement."}),l.modelSource&&o.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}):o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Fichier .gguf"}),o.jsx(ce,{"aria-label":"local gguf file",value:f,placeholder:"/home/me/models/qwen.gguf",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"localPath",path:C})}}),o.jsx(Os,{children:"Chemin absolu vers un .gguf déjà présent."}),l.modelSource&&o.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Nom du modèle dans IdeA"}),o.jsx(ce,{"aria-label":"server served model name",value:e.servedModelName,placeholder:"qwen3-coder-30b",invalid:!!l.servedModelName,onChange:b=>c({servedModelName:b.target.value})}),o.jsx(Os,{children:"Nom envoyé aux clients OpenAI-compatible."}),l.servedModelName&&o.jsx("small",{className:"text-xs text-danger",children:l.servedModelName})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[12rem] flex-1 flex-col gap-1",children:[o.jsx(Et,{children:"Commande serveur"}),o.jsx(ce,{"aria-label":"server binary path",value:e.binaryPath??"",placeholder:"llama-server",onChange:b=>{const C=b.target.value;c({binaryPath:C.length===0?void 0:C})}}),o.jsx(Os,{children:"Laisse vide pour résoudre `llama-server` via le PATH."})]}),o.jsxs("label",{className:"flex min-w-[6rem] flex-col gap-1",children:[o.jsx(Et,{children:"Port"}),o.jsx(ce,{"aria-label":"server port",value:Number.isNaN(e.port)?"":e.port.toString(),inputMode:"numeric",invalid:!!l.port,onChange:b=>c({port:Number.parseInt(b.target.value,10)})}),l.port&&o.jsx("small",{className:"text-xs text-danger",children:l.port})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Base URL (OpenAI-compatible)"}),o.jsx(ce,{"aria-label":"server base url",value:e.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!l.baseURL,onChange:b=>c({baseURL:b.target.value})}),l.baseURL&&o.jsx("small",{className:"text-xs text-danger",children:l.baseURL})]}),o.jsxs("label",{className:"flex items-start gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":"server auto start",checked:e.autoStart,disabled:!e.modelSource,onChange:b=>c({autoStart:b.target.checked}),className:"mt-1 accent-primary disabled:opacity-50"}),o.jsxs("span",{className:"flex flex-col",children:[o.jsx(Et,{children:"Démarrer automatiquement"}),!e.modelSource&&o.jsx(Os,{children:"Renseigne d'abord une source de modèle pour l'activer."})]})]}),o.jsxs("details",{className:"rounded-md border border-border p-2",children:[o.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted",children:"Réglages llama.cpp"}),o.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsxs(Et,{children:["Couches GPU ",o.jsx("span",{className:"text-muted",children:"(-ngl)"})]}),o.jsx(ce,{"aria-label":"gpu layers",value:e.gpuLayers===void 0?"":String(e.gpuLayers),inputMode:"numeric",placeholder:"99",onChange:b=>{const C=b.target.value.trim();c({gpuLayers:C.length===0?void 0:Number.parseInt(C,10)})}}),o.jsx(Os,{children:"0 = CPU seul."})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsxs(Et,{children:["Taille de contexte ",o.jsx("span",{className:"text-muted",children:"(-c)"})]}),o.jsx(ce,{"aria-label":"context size",value:e.contextSize===void 0?"":String(e.contextSize),inputMode:"numeric",placeholder:"16384",onChange:b=>{const C=b.target.value.trim();c({contextSize:C.length===0?void 0:Number.parseInt(C,10)})}})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsxs(Et,{children:["Adresse d'écoute ",o.jsx("span",{className:"text-muted",children:"(--host)"})]}),o.jsx(ce,{"aria-label":"listen host",value:e.host,placeholder:"127.0.0.1",invalid:!!l.host,onChange:b=>c({host:b.target.value})}),l.host&&o.jsx("small",{className:"text-xs text-danger",children:l.host})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":"jinja template",checked:e.jinja,onChange:b=>c({jinja:b.target.checked}),className:"accent-primary"}),o.jsxs(Et,{children:["Template chat Jinja ",o.jsx("span",{className:"text-muted",children:"(--jinja)"})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Arguments supplémentaires"}),o.jsx(ce,{"aria-label":"extra arguments",value:e.args.join(" "),placeholder:"--flash-attn --parallel 2",onChange:b=>c({args:_T(b.target.value)})}),y.length>0&&o.jsxs("small",{className:"text-xs text-warning",role:"status",children:[y.join(", ")," : cette option est déjà pilotée par un champ ci-dessus."]})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx(Et,{children:"Stop policy"}),o.jsx("select",{"aria-label":"server stop policy",value:e.stopPolicy,onChange:b=>c({stopPolicy:b.target.value}),className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:ST.map(b=>o.jsx("option",{value:b.value,children:b.label},b.value))})]})]})]}),o.jsx(jT,{preview:x,autoStart:e.autoStart}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{variant:"primary",size:"sm","aria-label":"save model server",onClick:i,disabled:t||!a,children:"Save server"}),o.jsx(M,{variant:"ghost",size:"sm","aria-label":"cancel model server",onClick:s,disabled:t,children:"Cancel"})]})]})}const Ru="";function ET({servers:e,value:t,onChange:n,ariaLabel:r="local model server"}){const s=t!==void 0&&!e.some(i=>i.id===t);return o.jsxs("select",{"aria-label":r,value:t??Ru,onChange:i=>n(i.target.value===Ru?void 0:i.target.value),className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:[o.jsx("option",{value:Ru,children:"None (external endpoint)"}),e.map(i=>o.jsxs("option",{value:i.id,children:[i.name," — ",i.servedModelName]},i.id)),s&&o.jsxs("option",{value:t,children:[t," (unknown / removed)"]})]})}function PT({mode:e,configured:t,references:n}){if(e==="firstRun")return n.map(l=>({profile:l,selected:!1,available:null}));const r=new Set(t.map(l=>l.id)),s=t.map(l=>({profile:l,selected:!0,available:null})),i=n.filter(l=>!r.has(l.id)).map(l=>({profile:l,selected:!1,available:null}));return[...s,...i]}const AT=3e3;function Ro(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function TT(e="firstRun"){const{profile:t}=fe(),[n,r]=g.useState(null),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),f=g.useRef(0),p=g.useRef(null);g.useEffect(()=>()=>{f.current+=1,p.current!==null&&clearTimeout(p.current)},[]);const m=g.useCallback(async(S,N)=>{const L=f.current+1;f.current=L;const A=()=>f.current!==L;d(!0),p.current!==null&&clearTimeout(p.current),p.current=setTimeout(()=>{A()||d(!1)},AT);try{const k=await t.detectProfiles(S);if(A())return;const D=new Map(k.map(R=>[R.profile.id,R.available]));i(R=>R.map(E=>{const O=D.get(E.profile.id)??E.available;return{...E,available:O,selected:N.preselect?O===!0:E.selected}}))}catch(k){if(A())return;N.reportError&&a(Ro(k))}finally{A()||(p.current!==null&&clearTimeout(p.current),p.current=null,d(!1))}},[t]),x=g.useCallback(async()=>{u(!0),a(null);let S=null;try{const[N,L]=await Promise.all([t.firstRunState(),e==="edit"?t.listProfiles():Promise.resolve([])]);r(N.isFirstRun);const A=PT({mode:e,configured:L,references:N.referenceProfiles});S=A.map(k=>k.profile),i(A)}catch(N){a(Ro(N)),r(!1)}finally{u(!1)}S!==null&&m(S,{preselect:e==="firstRun",reportError:!1})},[t,m,e]);g.useEffect(()=>{x()},[x]);const w=g.useCallback(S=>{i(N=>N.map(L=>L.profile.id===S?{...L,selected:!L.selected}:L))},[]),v=g.useCallback((S,N)=>{i(L=>L.map(A=>A.profile.id===S?{...A,profile:N}:A))},[]),_=g.useCallback(async S=>{a(null);try{const N=await t.cloneOpenCodeProfileFromSeed(S);i(L=>[...L,{profile:N,selected:!0,available:null}])}catch(N){a(Ro(N))}},[t]),y=g.useCallback(S=>{i(N=>N.filter(L=>L.profile.id!==S))},[]),b=g.useCallback(async()=>{a(null),await m(s.map(S=>S.profile),{preselect:!1,reportError:!0})},[m,s]),C=g.useCallback(async()=>{u(!0),a(null);try{const S=s.filter(N=>N.selected).map(N=>N.profile);await t.configureProfiles(S),r(!1)}catch(S){a(Ro(S))}finally{u(!1)}},[t,s]);return{isFirstRun:n,entries:s,error:l,busy:c,detecting:h,toggle:w,updateProfile:v,addOpenCodeProfile:_,remove:y,detect:b,finish:C,reload:x}}function LT(e){return e.length===0||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:/.test(e)?!1:!e.split(/[/\\]/).includes("..")}function ww(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Sw(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function Mu(e,t){return e===void 0?!0:Number.isInteger(e)&&e>0&&e<=t}const _x=4294967295,DT=65535;function RT(e){const t={};return Sw(e.endpoint)||(t.endpoint="Endpoint must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),e.apiKeyEnv!==void 0&&e.apiKeyEnv.length>0&&!ww(e.apiKeyEnv)&&(t.apiKeyEnv="Must be a valid env var name (not the key itself)."),Mu(e.requestTimeoutMs,_x)||(t.requestTimeoutMs="Must be a positive integer (ms)."),Mu(e.connectTimeoutMs,_x)||(t.connectTimeoutMs="Must be a positive integer (ms)."),Mu(e.maxToolIterations,DT)||(t.maxToolIterations="Must be a positive integer."),t}function MT(e){const t={};return Sw(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),t}function IT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),e.command.trim().length===0&&(t.command="Command is required.");const n=e.contextInjection;return n.strategy==="conventionFile"?LT(n.target)||(t.target="Target must be a relative file name (no .. or absolute)."):n.strategy==="flag"?n.flag.trim().length===0&&(t.flag="Flag is required."):n.strategy==="env"&&(ww(n.var)||(t.var="Must be a valid env var identifier.")),e.structuredAdapter==="openAiCompatible"&&(e.chatHttp?Object.assign(t,RT(e.chatHttp)):(t.endpoint="Endpoint must start with http:// or https://.",t.model="Model is required.")),e.structuredAdapter==="openCode"&&!e.opencodeProvider&&(e.opencode?Object.assign(t,MT(e.opencode)):(t.baseURL="Base URL must start with http:// or https://.",t.model="Model is required.")),t}function OT(){return{endpoint:"http://localhost:11434/v1",model:"qwen2.5-coder",requestTimeoutMs:12e4,connectTimeoutMs:5e3,maxToolIterations:16}}function BT(){return{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}function zT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function qe({children:e}){return o.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function kw(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function FT(){const{profile:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useCallback(async()=>{s(!0),l(null);try{n(await e.listOpenCodeProviders())}catch(c){n(null),l(kw(c))}finally{s(!1)}},[e]);return g.useEffect(()=>{a()},[a]),{providers:t,loading:r,error:i,reload:()=>void a()}}function Cw({onDone:e,forceOpen:t=!1}){const n=TT(t?"edit":"firstRun"),r=hT(),s=FT();if(n.isFirstRun===null||!t&&n.isFirstRun===!1)return null;async function i(){await n.finish(),e?.()}return o.jsx(ke,{"aria-label":"first run setup",className:"border-primary/40",title:o.jsxs("div",{className:"flex flex-col",children:[o.jsx("h2",{className:"text-base font-semibold text-content",children:"Welcome to IdeA"}),o.jsx("p",{className:"text-sm text-muted",children:"Choose which AI CLIs to configure. Commands are pre-filled and editable."})]}),children:o.jsxs("div",{className:"flex flex-col gap-4",children:[n.error&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),o.jsxs(gw,{children:[o.jsx(M,{onClick:()=>void n.detect(),disabled:n.busy,className:"whitespace-nowrap",children:"Detect installed CLIs"}),n.detecting&&o.jsx("span",{role:"status",className:"text-xs text-muted",children:"Detecting…"}),o.jsx(M,{onClick:()=>void n.addOpenCodeProfile(),disabled:n.busy,className:"whitespace-nowrap",children:"Add OpenCode profile"})]}),o.jsx(kT,{vm:r}),o.jsx("ul",{className:"flex list-none flex-col gap-3 p-0",children:n.entries.map(l=>o.jsx($T,{entry:l,servers:r.servers,providerCatalog:s,onToggle:()=>n.toggle(l.profile.id),onChange:a=>n.updateProfile(l.profile.id,a),onRemove:()=>n.remove(l.profile.id),onDuplicate:l.profile.structuredAdapter==="openCode"?()=>n.addOpenCodeProfile({name:`${l.profile.name} (copy)`,opencode:l.profile.opencode}):void 0},l.profile.id))}),o.jsx("footer",{className:"flex gap-2",children:o.jsx(M,{variant:"primary",onClick:()=>void i(),disabled:n.busy,children:"Save and continue"})})]})})}function $T({entry:e,servers:t,providerCatalog:n,onToggle:r,onChange:s,onRemove:i,onDuplicate:l}){const{profile:a,selected:c,available:u}=e,h=IT(a),d=a.structuredAdapter==="openCode";return o.jsxs("li",{className:"flex flex-col gap-2 rounded-md border border-border bg-raised p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:r,"aria-label":`use ${a.name}`,className:"accent-primary"}),o.jsx("strong",{className:"text-sm text-content",children:a.name})]}),o.jsx("span",{"aria-label":`${a.name} availability`,className:U("text-xs",u===null?"text-faint":u?"text-success":"text-danger"),children:u===null?"—":u?"✓ installed":"✗ not found"}),o.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[l&&o.jsx(M,{size:"sm","aria-label":`duplicate ${a.name}`,onClick:l,children:"Duplicate"}),o.jsx(sr,{size:"sm","aria-label":`remove ${a.name}`,onClick:i,children:"×"})]})]}),d&&o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Name"}),o.jsx(ce,{"aria-label":`${a.name} name`,value:a.name,invalid:!!h.name,onChange:f=>s({...a,name:f.target.value})}),h.name&&o.jsx("small",{className:"text-xs text-danger",children:h.name})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Command"}),o.jsx(ce,{"aria-label":`${a.name} command`,value:a.command,invalid:!!h.command,onChange:f=>s({...a,command:f.target.value})}),h.command&&o.jsx("small",{className:"text-xs text-danger",children:h.command})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Arguments"}),o.jsx(ce,{"aria-label":`${a.name} args`,value:a.args.join(" "),onChange:f=>s({...a,args:zT(f.target.value)})})]}),a.structuredAdapter==="openAiCompatible"&&o.jsx(qT,{profile:a,errors:h,onChange:s}),a.structuredAdapter==="openCode"&&o.jsx(WT,{profile:a,errors:h,servers:t,providerCatalog:n,onChange:s})]})}function WT({profile:e,errors:t,servers:n,providerCatalog:r,onChange:s}){const[i,l]=g.useState(e.opencodeProvider?"cloud":"local");return o.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[o.jsx("div",{role:"radiogroup","aria-label":"mode du profil OpenCode",className:"flex w-fit gap-1 rounded-md border border-border bg-raised p-0.5",children:[{id:"local",label:"Local (llama.cpp)"},{id:"cloud",label:"Provider cloud"}].map(a=>{const c=i===a.id;return o.jsx("button",{type:"button",role:"radio","aria-checked":c,onClick:()=>l(a.id),className:U("rounded px-2.5 py-1 text-xs font-medium transition-colors",c?"bg-primary text-on-primary":"text-muted hover:text-content"),children:a.label},a.id)})}),i==="local"&&o.jsx(UT,{profile:e,errors:t,servers:n,onChange:s}),i==="cloud"&&o.jsx(HT,{profile:e,catalog:r,onChange:s})]})}const yx="__custom__",bx="@ai-sdk/openai-compatible";function HT({profile:e,catalog:t,onChange:n}){const{profile:r}=fe(),s=e.opencodeProvider,[i,l]=g.useState(s?.custom?"custom":"catalog"),[a,c]=g.useState(s?.providerId??""),[u,h]=g.useState(s?.model??""),[d,f]=g.useState(""),[p,m]=g.useState(s?.custom?.npm??bx),[x,w]=g.useState(s?.custom?.baseUrl??""),[v,_]=g.useState(s?.custom?.displayName??""),[y,b]=g.useState(""),[C,S]=g.useState(!1),[N,L]=g.useState(!1),[A,k]=g.useState(null),[D,R]=g.useState({}),E=s!==void 0,O=t.providers?.find(z=>z.providerId===a)?.models??[],I=t.providers!==null&&!t.loading,W=(t.providers??[]).filter(z=>{if(z.providerId===a)return!0;const j=d.trim().toLowerCase();return j.length===0?!0:z.displayName.toLowerCase().includes(j)||z.providerId.toLowerCase().includes(j)}),G=N||y.length===0||i==="catalog"&&(!I||!!t.error);async function P(){const z={};if(a.trim().length===0&&(z.providerId="Le provider est obligatoire."),u.trim().length===0&&(z.model="Le modèle est obligatoire."),i==="custom"&&(p.trim().length===0&&(z.npm="Le paquet npm est obligatoire."),x.trim().length===0&&(z.baseUrl="L'URL de base est obligatoire.")),y.length===0&&(z.apiKey="La clé API est obligatoire."),R(z),!(Object.keys(z).length>0)){L(!0),k(null);try{const j=await r.saveOpenCodeProviderProfile({profile:e,providerId:a.trim(),model:u.trim(),apiKey:y,...i==="custom"?{custom:{npm:p.trim(),baseUrl:x.trim(),displayName:v.trim().length>0?v.trim():void 0}}:{}});n(j),b("")}catch(j){k(kw(j))}finally{L(!1)}}}return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider cloud (OpenCode)"}),A&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:A}),t.loading&&o.jsx("p",{className:"text-xs text-faint",children:"Chargement des providers…"}),t.error&&o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"Impossible de charger la liste des providers cloud."}),o.jsx(M,{size:"sm",onClick:()=>t.reload(),className:"w-fit",children:"Réessayer"})]}),i==="catalog"&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Provider"}),I&&o.jsx("input",{type:"text","aria-label":`${e.name} provider search`,placeholder:"Rechercher un provider…",value:d,onChange:z=>f(z.target.value),className:"h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"}),o.jsxs("select",{"aria-label":`${e.name} provider`,value:a,disabled:!I,onChange:z=>{const j=z.target.value;j===yx?(l("custom"),c(""),h("")):(c(j),h("")),R(se=>({...se,providerId:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",D.providerId?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:t.loading?"Chargement des providers…":"Choisir un provider…"}),W.map(z=>o.jsx("option",{value:z.providerId,children:z.displayName},z.providerId)),o.jsx("option",{value:yx,children:"Autre / personnalisé…"})]}),D.providerId&&o.jsx("small",{className:"text-xs text-danger",children:D.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Modèle"}),o.jsxs("select",{"aria-label":`${e.name} model`,value:u,disabled:a.length===0,onChange:z=>{h(z.target.value),R(j=>({...j,model:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",D.model?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:a.length===0?"—":"Choisir un modèle…"}),O.map(z=>o.jsx("option",{value:z,children:z},z))]}),D.model&&o.jsx("small",{className:"text-xs text-danger",children:D.model})]})]}),i==="custom"&&o.jsxs("fieldset",{className:"flex flex-col gap-2 rounded-md border border-border/50 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider personnalisé"}),o.jsx(M,{variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{l("catalog"),c(""),h(""),R({})},children:"← Choisir un provider du catalogue"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Identifiant du provider"}),o.jsx(ce,{"aria-label":`${e.name} custom provider id`,value:a,placeholder:"ex. mon-provider",invalid:!!D.providerId,onChange:z=>{c(z.target.value),R(j=>({...j,providerId:void 0}))}}),D.providerId&&o.jsx("small",{className:"text-xs text-danger",children:D.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Paquet npm"}),o.jsx(ce,{"aria-label":`${e.name} custom npm package`,value:p,placeholder:bx,invalid:!!D.npm,onChange:z=>{m(z.target.value),R(j=>({...j,npm:void 0}))}}),D.npm&&o.jsx("small",{className:"text-xs text-danger",children:D.npm})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"URL de base"}),o.jsx(ce,{"aria-label":`${e.name} custom base url`,value:x,placeholder:"https://api.mon-provider.example/v1",invalid:!!D.baseUrl,onChange:z=>{w(z.target.value),R(j=>({...j,baseUrl:void 0}))}}),D.baseUrl&&o.jsx("small",{className:"text-xs text-danger",children:D.baseUrl})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Modèle"}),o.jsx(ce,{"aria-label":`${e.name} model`,value:u,placeholder:"ex. mon-modele-1",invalid:!!D.model,onChange:z=>{h(z.target.value),R(j=>({...j,model:void 0}))}}),D.model&&o.jsx("small",{className:"text-xs text-danger",children:D.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Libellé du modèle (optionnel)"}),o.jsx(ce,{"aria-label":`${e.name} custom display name`,value:v,placeholder:"ex. Mon modèle",onChange:z=>_(z.target.value)})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Clé API"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ce,{"aria-label":`${e.name} api key`,type:C?"text":"password",value:y,placeholder:E?"Ressaisissez la clé API pour confirmer l'enregistrement":"ex. sk-ant-…",invalid:!!D.apiKey,onChange:z=>{b(z.target.value),R(j=>({...j,apiKey:void 0}))}}),o.jsx(sr,{size:"sm","aria-label":"afficher/masquer la clé API",onClick:()=>S(z=>!z),children:C?"🙈":"👁"})]}),D.apiKey&&o.jsx("small",{className:"text-xs text-danger",children:D.apiKey}),o.jsx("small",{className:"text-xs text-faint",children:"Jamais affichée ni renvoyée par IdeA une fois enregistrée ; stockée chiffrée localement."}),E&&o.jsx("small",{className:"text-xs text-muted",children:"Pour des raisons de sécurité, la clé n'est jamais réaffichée : ressaisissez-la à chaque modification de ce profil."})]}),o.jsx(M,{variant:"primary",size:"sm",loading:N,disabled:G,onClick:()=>void P(),className:"w-fit",children:"Enregistrer"})]})}function UT({profile:e,errors:t,servers:n,onChange:r}){const s=e.opencode??BT(),i=l=>r({...e,opencode:{...s,...l}});return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local model (OpenCode + llama.cpp)"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Base URL"}),o.jsx(ce,{"aria-label":`${e.name} base url`,value:s.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!t.baseURL,onChange:l=>i({baseURL:l.target.value})}),t.baseURL&&o.jsx("small",{className:"text-xs text-danger",children:t.baseURL})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Model"}),o.jsx(ce,{"aria-label":`${e.name} model`,value:s.model,placeholder:"qwen3-coder-30b",invalid:!!t.model,onChange:l=>i({model:l.target.value})}),t.model&&o.jsx("small",{className:"text-xs text-danger",children:t.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"API key (optional — a local llama.cpp needs none)"}),o.jsx(ce,{"aria-label":`${e.name} api key`,value:s.apiKey??"",placeholder:"e.g. sk-no-key",onChange:l=>{const a=l.target.value;i({apiKey:a.length===0?void 0:a})}})]}),o.jsxs("div",{className:"flex flex-wrap gap-4",children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":`${e.name} reasoning`,checked:s.reasoning??!0,onChange:l=>i({reasoning:l.target.checked}),className:"accent-primary"}),o.jsx(qe,{children:"Reasoning"})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":`${e.name} attachment`,checked:s.attachment??!1,onChange:l=>i({attachment:l.target.checked}),className:"accent-primary"}),o.jsx(qe,{children:"Attachments"})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Local model server (bind to a managed llama.cpp server, or none)"}),o.jsx(ET,{ariaLabel:`${e.name} local model server`,servers:n,value:s.localModelServerId,onChange:l=>i({localModelServerId:l})})]})]})}function Iu(e){const t=e.trim();if(t.length===0)return;const n=Number(t);return Number.isFinite(n)?n:NaN}function qT({profile:e,errors:t,onChange:n}){const r=e.chatHttp??OT(),s=i=>n({...e,chatHttp:{...r,...i}});return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local / LAN model (OpenAI-compatible)"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Endpoint"}),o.jsx(ce,{"aria-label":`${e.name} endpoint`,value:r.endpoint,placeholder:"http://localhost:11434/v1",invalid:!!t.endpoint,onChange:i=>s({endpoint:i.target.value})}),t.endpoint&&o.jsx("small",{className:"text-xs text-danger",children:t.endpoint})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Model"}),o.jsx(ce,{"aria-label":`${e.name} model`,value:r.model,placeholder:"qwen2.5-coder",invalid:!!t.model,onChange:i=>s({model:i.target.value})}),t.model&&o.jsx("small",{className:"text-xs text-danger",children:t.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"API key — environment variable name (never the key itself)"}),o.jsx(ce,{"aria-label":`${e.name} api key env`,value:r.apiKeyEnv??"",placeholder:"e.g. OPENAI_API_KEY (variable name, not the secret)",invalid:!!t.apiKeyEnv,onChange:i=>{const l=i.target.value.trim();s({apiKeyEnv:l.length===0?void 0:l})}}),t.apiKeyEnv&&o.jsx("small",{className:"text-xs text-danger",children:t.apiKeyEnv})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(qe,{children:"Request timeout (ms)"}),o.jsx(ce,{"aria-label":`${e.name} request timeout`,value:r.requestTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.requestTimeoutMs,onChange:i=>s({requestTimeoutMs:Iu(i.target.value)})}),t.requestTimeoutMs&&o.jsx("small",{className:"text-xs text-danger",children:t.requestTimeoutMs})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(qe,{children:"Connect timeout (ms)"}),o.jsx(ce,{"aria-label":`${e.name} connect timeout`,value:r.connectTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.connectTimeoutMs,onChange:i=>s({connectTimeoutMs:Iu(i.target.value)})}),t.connectTimeoutMs&&o.jsx("small",{className:"text-xs text-danger",children:t.connectTimeoutMs})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(qe,{children:"Max tool iterations"}),o.jsx(ce,{"aria-label":`${e.name} max tool iterations`,value:r.maxToolIterations?.toString()??"",inputMode:"numeric",invalid:!!t.maxToolIterations,onChange:i=>s({maxToolIterations:Iu(i.target.value)})}),t.maxToolIterations&&o.jsx("small",{className:"text-xs text-danger",children:t.maxToolIterations})]})]})]})}function jw(){const{profile:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{s(null);try{n(await e.listProfiles())}catch(u){s(u&&typeof u=="object"&&"message"in u?String(u.message):String(u))}},[e]);g.useEffect(()=>{a()},[a]);async function c(u){await e.deleteProfile(u),await a()}return i?o.jsx(Cw,{forceOpen:!0,onDone:()=>{l(!1),a()}}):o.jsx(ke,{"aria-label":"ai profiles settings",title:"Profils IA",actions:o.jsx(M,{size:"sm",onClick:()=>l(!0),children:"Configurer les profils"}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[r&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:r}),t.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun profil configuré."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(u=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex items-baseline gap-2",children:[o.jsx("strong",{className:"text-sm text-content",children:u.name}),o.jsx("code",{className:"text-xs text-muted",children:u.command})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`supprimer ${u.name}`,onClick:()=>void c(u.id),children:"Supprimer"})]},u.id))})]})})}const VT=3e3,KT=2500;function wx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function GT(){const{device:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(!1),[a,c]=g.useState(!1),[u,h]=g.useState(null),[d,f]=g.useState([]),[p,m]=g.useState(!1),x=g.useRef(null),w=g.useCallback(async()=>{try{const L=await e.listDevices();return n(L),s(null),L}catch(L){return s(wx(L)),null}},[e]),v=g.useCallback(async()=>{const L=await w();L&&(x.current=new Set(L.map(A=>A.deviceId)))},[w]);g.useEffect(()=>{v()},[v]),g.useEffect(()=>{if(!u)return;const L=setInterval(()=>{(async()=>{const A=await w();if(!A)return;const k=x.current;if(x.current=new Set(A.map(R=>R.deviceId)),!k)return;const D=A.filter(R=>!k.has(R.deviceId)).map(R=>R.deviceId);D.length>0&&f(D)})()},VT);return()=>clearInterval(L)},[u,w]),g.useEffect(()=>{if(d.length===0)return;const L=setTimeout(()=>f([]),KT);return()=>clearTimeout(L)},[d]);const _=g.useCallback(async L=>{l(!0),s(null);try{return await L(),!0}catch(A){return s(wx(A)),!1}finally{l(!1)}},[]),y=g.useCallback(async()=>{c(!0);try{await _(async()=>{h(await e.createPairingCode())})}finally{c(!1)}},[e,_]),b=g.useCallback(()=>h(null),[]),C=g.useCallback(async(L,A)=>{await _(()=>e.renameDevice(L,A))&&await v()},[e,_,v]),S=g.useCallback(async L=>{const A=L.isCurrentDevice;await _(()=>e.revokeDevice(L.deviceId))&&(A?m(!0):await v())},[e,_,v]),N=g.useCallback(async()=>{const L=t?.some(A=>A.isCurrentDevice)??!1;await _(()=>e.revokeAllDevices())&&(L?m(!0):await v())},[t,e,_,v]);return{devices:t,error:r,busy:i,generating:a,code:u,freshDeviceIds:d,sessionEnded:p,refresh:v,generateCode:y,dismissCode:b,rename:C,revoke:S,revokeAll:N}}const YT=2*60*1e3;function Sx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function XT(e){return e.toLocaleTimeString("fr-FR",{hour:"2-digit",minute:"2-digit"})}function Nw(e,t=new Date){const n=new Date(e),r=n.getFullYear()===t.getFullYear();return n.toLocaleDateString("fr-FR",{day:"numeric",month:"short",...r?{}:{year:"numeric"}})}function QT(e,t=new Date){if(t.getTime()-eOu(e.expiresAtMs)),[i,l]=g.useState(!1);g.useEffect(()=>{s(Ou(e.expiresAtMs));const c=setInterval(()=>s(Ou(e.expiresAtMs)),1e3);return()=>clearInterval(c)},[e.expiresAtMs]),g.useEffect(()=>{l(!1)},[e.code]),g.useEffect(()=>{if(!i)return;const c=setTimeout(()=>l(!1),2e3);return()=>clearTimeout(c)},[i]);const a=r===null;return o.jsx(ke,{"data-testid":"pairing-code-panel",className:"flex flex-col gap-3",children:a?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm text-muted",children:"Ce code a expiré."}),o.jsx("div",{children:o.jsx(M,{size:"sm",onClick:t,children:"Générer un nouveau code"})})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm text-muted",children:"Saisissez ce code sur le nouvel appareil."}),o.jsx("p",{"data-testid":"pairing-code-value","aria-label":e.code,className:"flex gap-3 font-mono text-2xl font-semibold tracking-[0.2em] text-content sm:text-3xl",children:ZT(e.code).map((c,u)=>o.jsx("span",{"aria-hidden":"true",children:c},u))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void eL(e.code).then(c=>l(c)),children:i?"Copié":"Copier"}),o.jsx("span",{className:"text-xs text-faint","data-testid":"pairing-code-countdown",children:r}),o.jsx(M,{size:"sm",variant:"ghost",className:"ml-auto",onClick:n,children:"Fermer"})]})]})})}function kx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:s=!1,onConfirm:i,onCancel:l}){const a=g.useRef(null);return g.useEffect(()=>{a.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.floatingWindow},onClick:l,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),o.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:s,onClick:()=>void i(),children:n})]})]})})}const vp=40,Ew="Cet appareil",nL=[[/\bEdg(?:e|A|iOS)?\//,"Edge"],[/\bOPR\/|\bOpera\//,"Opera"],[/\bFirefox\/|\bFxiOS\//,"Firefox"],[/\bChrome\/|\bCriOS\//,"Chrome"],[/\bSafari\//,"Safari"]],rL=[[/\bWindows\b/,"Windows"],[/\bMac OS X\b|\bMacintosh\b/,"Mac"],[/\bCrOS\b/,"ChromeOS"],[/\bLinux\b|\bX11\b/,"Linux"]];function sL(e){const t=e??"";if(/\biPhone\b/.test(t))return"iPhone";if(/\biPad\b/.test(t))return"iPad";if(/\bAndroid\b/.test(t))return"Android";const n=nL.find(([s])=>s.test(t))?.[1],r=rL.find(([s])=>s.test(t))?.[1];return n&&r?`${n} sur ${r}`:n??r??Ew}function Cx(e){return Array.from(e.trim()).slice(0,vp).join("")}function iL(){return typeof navigator>"u"||!navigator.userAgent?Ew:sL(navigator.userAgent)}function Pw({onSessionEnded:e}){const t=GT(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[l,a]=g.useState(null);g.useEffect(()=>{t.sessionEnded&&e?.()},[t.sessionEnded,e]);const c=t.devices;return o.jsxs("section",{"data-testid":"devices-screen",className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Appareils"}),o.jsx("p",{className:"text-sm text-muted",children:"Les appareils autorisés à accéder à cette instance IdeA."})]}),o.jsx(M,{onClick:()=>void t.generateCode(),loading:t.generating,children:"Appairer"})]}),t.code&&o.jsx(tL,{code:t.code,onRegenerate:()=>void t.generateCode(),onDismiss:t.dismissCode}),t.error&&o.jsx(ke,{className:"border-danger/40",children:o.jsx("p",{role:"alert",className:"text-sm text-danger",children:t.error})}),c===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des appareils…"]}):c.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun appareil appairé."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"device-list",children:c.map(u=>o.jsx(lL,{device:u,fresh:t.freshDeviceIds.includes(u.deviceId),renaming:l===u.deviceId,onStartRename:()=>a(u.deviceId),onCancelRename:()=>a(null),onRename:async h=>{await t.rename(u.deviceId,h),a(null)},onRevoke:()=>r(u)},u.deviceId))}),c!==null&&c.length>0&&o.jsx("div",{className:"pt-1",children:o.jsx(M,{variant:"ghost",size:"sm",onClick:()=>i(!0),children:"Révoquer tous les appareils"})}),n&&o.jsx(kx,{title:"Révoquer cet appareil ?",body:n.isCurrentDevice?"Il devra être appairé à nouveau pour accéder à IdeA. Vous serez déconnecté immédiatement.":"Il devra être appairé à nouveau pour accéder à IdeA.",confirmLabel:"Révoquer",busy:t.busy,onConfirm:async()=>{const u=n;r(null),await t.revoke(u)},onCancel:()=>r(null)}),s&&o.jsx(kx,{title:"Révoquer tous les appareils ?",body:"Tous les appareils, y compris celui-ci, devront être appairés à nouveau. Vous serez déconnecté immédiatement.",confirmLabel:"Tout révoquer",danger:!0,busy:t.busy,onConfirm:async()=>{i(!1),await t.revokeAll()},onCancel:()=>i(!1)})]})}function lL({device:e,fresh:t,renaming:n,onStartRename:r,onCancelRename:s,onRename:i,onRevoke:l}){return o.jsx("li",{"data-testid":"device-row","data-fresh":t||void 0,className:U("py-3 transition-colors first:pt-0 last:pb-0",t&&"bg-success/10"),children:n?o.jsx(oL,{device:e,onSubmit:i,onCancel:s}):o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),e.isCurrentDevice&&o.jsx("span",{className:"shrink-0 rounded-full bg-primary/15 px-2 py-0.5 text-[0.65rem] font-medium text-primary",children:"Cet appareil"})]}),o.jsx("span",{className:"text-xs text-muted",children:QT(e.lastSeenAtMs)}),o.jsx("span",{className:"text-[0.7rem] text-faint",children:JT(e.pairedAtMs)})]}),o.jsx(aL,{deviceName:e.name,onRename:r,onRevoke:l})]})})}function oL({device:e,onSubmit:t,onCancel:n}){const[r,s]=g.useState(e.name),i=r.trim();return o.jsxs("form",{className:"flex flex-col gap-2",onSubmit:l=>{l.preventDefault(),i.length>0&&t(i)},children:[o.jsx(qt,{label:"Nom de l'appareil",hideLabel:!0,children:({id:l})=>o.jsx(ce,{id:l,value:r,autoFocus:!0,maxLength:vp,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Escape"&&n()}})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{type:"submit",size:"sm",disabled:i.length===0,children:"Renommer"}),o.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Annuler"})]})]})}function aL({deviceName:e,onRename:t,onRevoke:n}){const[r,s]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const i=()=>s(!1);return window.addEventListener("click",i),()=>window.removeEventListener("click",i)},[r]),o.jsxs("div",{className:"relative shrink-0",onClick:i=>i.stopPropagation(),children:[o.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":r,"aria-label":`Actions pour ${e}`,onClick:()=>s(i=>!i),className:"rounded-md px-2 py-1 text-sm text-muted transition-colors hover:bg-raised hover:text-content",children:"⋯"}),r&&o.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-10 mt-1 flex min-w-36 flex-col rounded-md border border-border bg-raised py-1 shadow-lg",children:[o.jsx("button",{type:"button",role:"menuitem",onClick:()=>{s(!1),t()},className:"px-3 py-1.5 text-left text-sm text-content transition-colors hover:bg-canvas",children:"Renommer"}),o.jsx("button",{type:"button",role:"menuitem",onClick:()=>{s(!1),n()},className:"px-3 py-1.5 text-left text-sm text-danger transition-colors hover:bg-canvas",children:"Révoquer"})]})]})}const cL=250;function Ki(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function uL(){const{desktopServer:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState({state:"stopped"}),[i,l]=g.useState([]),[a,c]=g.useState(),[u,h]=g.useState([]),[d,f]=g.useState(null),[p,m]=g.useState(null),[x,w]=g.useState(!1),[v,_]=g.useState(!1),y=g.useRef(0);g.useEffect(()=>{let E=!0;return(async()=>{try{const[O,I]=await Promise.all([e.getExposureSettings(),e.status()]);if(!E)return;n(O),s(I)}catch(O){E&&m(Ki(O))}})(),()=>{E=!1}},[e]),g.useEffect(()=>{let E=!0;return(async()=>{try{const O=await e.previewExposure({mode:"localOnly",autoStart:!1,port:0,trustedProxies:[]});E&&l(O.candidateLanAddresses)}catch{}})(),()=>{E=!1}},[e]),g.useEffect(()=>{let E,O=!1;return e.onStatusChanged(s).then(I=>{O?I():E=I}),()=>{O=!0,E?.()}},[e]),g.useEffect(()=>{if(!t)return;const E=++y.current,O=setTimeout(()=>{e.previewExposure(t).then(I=>{E===y.current&&(c(I.upstreamUrl),h(I.warnings),f(null))},I=>{E===y.current&&(c(void 0),h([]),f(Ki(I)))})},cL);return()=>clearTimeout(O)},[e,t]);const b=g.useCallback(E=>{m(null),n(O=>O&&{...O,...E})},[]),C=g.useCallback(E=>{b(E==="localOnly"?{mode:E,publicOrigin:void 0,lanBindAddress:void 0,trustedProxies:[]}:E==="remoteProxyLocal"?{mode:E,lanBindAddress:void 0,trustedProxies:[]}:{mode:E})},[b]),S=g.useCallback(E=>b({publicOrigin:E.trim()||void 0}),[b]),N=g.useCallback(E=>b({lanBindAddress:E||void 0}),[b]),L=g.useCallback(E=>b({trustedProxies:E.split(/[\s,]+/).map(O=>O.trim()).filter(Boolean)}),[b]),A=g.useCallback(E=>b({port:E}),[b]),k=g.useCallback(async E=>{if(!t)return;const O={...t,autoStart:E};_(!0),m(null);try{await e.saveExposureSettings(O),n(O)}catch(I){m(Ki(I))}finally{_(!1)}},[e,t]),D=g.useCallback(async()=>{if(t){w(!0),m(null);try{await e.saveExposureSettings(t),s(await e.start())}catch(E){m(Ki(E))}finally{w(!1)}}},[e,t]),R=g.useCallback(async()=>{w(!0),m(null);try{s(await e.stop())}catch(E){m(Ki(E))}finally{w(!1)}},[e]);return{ready:t!==null,settings:t,status:r,candidateLanAddresses:i,upstreamUrl:a,warnings:u,validationError:d,actionError:p,busy:x,autoStartBusy:v,setMode:C,setPublicOrigin:S,setLanBindAddress:N,setTrustedProxies:L,setPort:A,setAutoStart:k,start:D,stop:R}}const dL=[{mode:"localOnly",title:"Cet ordinateur uniquement",description:"Pour utiliser IdeA uniquement sur cet ordinateur. Les appareils distants ne peuvent pas se connecter."},{mode:"remoteProxyLocal",title:"Accès distant, proxy sur cet ordinateur",description:"À utiliser quand le proxy HTTPS tourne sur la même machine qu'IdeA Desktop."},{mode:"remoteProxyOtherMachine",title:"Accès distant, proxy sur une autre machine",description:"À utiliser quand le proxy HTTPS tourne sur une autre machine. IdeA n'acceptera que le trafic provenant de ce proxy."}],hL={stopped:"Arrêté",starting:"Démarrage…",running:"En cours d'exécution",stopping:"Arrêt…",failed:"Échec"};function fL({value:e,label:t}){const[n,r]=g.useState(!1),s=typeof navigator<"u"&&!!navigator.clipboard;return o.jsx(M,{size:"sm",variant:"ghost","aria-label":t,disabled:!s,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),window.setTimeout(()=>r(!1),1500)},()=>r(!1))},children:n?"Copié":"Copier"})}function pL({value:e,copyLabel:t}){return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"flex-1 truncate rounded-md border border-border bg-raised px-2 py-1.5 font-mono text-xs text-content",children:e}),o.jsx(fL,{value:e,label:t})]})}function mL(){const e=uL(),t=g.useRef(null);if(!e.ready||!e.settings)return o.jsx(ke,{"aria-label":"deployment settings",title:"Déploiement",children:o.jsx("p",{className:"text-sm text-muted",children:"Chargement…"})});const{settings:n,status:r}=e,s=r.state==="running",i=n.mode!=="localOnly",l=n.mode==="remoteProxyOtherMachine",a=r.state==="starting"||r.state==="stopping";return o.jsxs("div",{"aria-label":"deployment settings",className:"flex flex-col gap-4",children:[o.jsx(ke,{title:"Serveur",actions:s||r.state==="stopping"?o.jsx(M,{size:"sm",onClick:()=>void e.stop(),disabled:e.busy||a,children:"Arrêter"}):o.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy||a,children:"Démarrer"}),children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{"aria-hidden":!0,className:U("size-2 rounded-full",s&&"bg-success",r.state==="failed"&&"bg-danger",(r.state==="stopped"||a)&&"bg-faint")}),o.jsx("span",{className:"text-content",children:hL[r.state]})]}),r.localUrl&&o.jsxs("p",{className:"text-xs text-muted",children:["URL locale : ",o.jsx("code",{className:"font-mono text-content",children:r.localUrl})]}),r.publicUrl&&o.jsxs("p",{className:"text-xs text-muted",children:["URL publique : ",o.jsx("code",{className:"font-mono text-content",children:r.publicUrl})]}),r.state==="failed"&&r.error&&(r.error.code==="PORT_IN_USE"?o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("p",{role:"alert",className:"text-sm text-danger",children:["Le serveur n'a pas démarré automatiquement. ",r.error.message]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>{t.current?.scrollIntoView?.({behavior:"smooth",block:"center"}),t.current?.focus()},children:"Modifier le port"}),o.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy,children:"Réessayer"})]})]}):o.jsx("p",{role:"alert",className:"text-sm text-danger",children:r.error.message})),e.actionError&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.actionError}),o.jsxs("label",{className:"flex cursor-pointer items-start gap-2 pt-2",children:[o.jsx("input",{type:"checkbox",className:"mt-0.5","aria-label":"Démarrer le serveur au lancement d'IdeA",checked:n.autoStart,disabled:e.autoStartBusy,onChange:c=>void e.setAutoStart(c.target.checked)}),o.jsxs("span",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-sm text-content",children:"Démarrer le serveur au lancement d'IdeA"}),o.jsx("span",{className:"text-xs text-muted",children:"IdeA utilisera les réglages réseau enregistrés ci-dessous au prochain démarrage de l'application desktop."})]})]})]})}),o.jsx(ke,{title:"Accès réseau",children:o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx("div",{role:"radiogroup","aria-label":"mode d'accès réseau",className:"flex flex-col gap-2",children:dL.map(c=>{const u=n.mode===c.mode;return o.jsxs("label",{className:U("flex cursor-pointer gap-3 rounded-lg border p-3 transition-colors",u?"border-border-strong bg-raised":"border-border hover:bg-raised"),children:[o.jsx("input",{type:"radio",name:"exposure-mode",className:"mt-1",checked:u,onChange:()=>e.setMode(c.mode)}),o.jsxs("span",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),o.jsx("span",{className:"text-xs text-muted",children:c.description})]})]},c.mode)})}),o.jsx(qt,{label:"Port",children:({id:c})=>o.jsx(ce,{ref:t,id:c,type:"number",value:String(n.port),onChange:u=>e.setPort(Number(u.target.value))})}),i&&o.jsx(qt,{label:"Origine publique",hint:"Exemple : https://idea.example.com",children:({id:c,describedBy:u})=>o.jsx(ce,{id:c,"aria-describedby":u,placeholder:"https://idea.example.com",value:n.publicOrigin??"",onChange:h=>e.setPublicOrigin(h.target.value)})}),l&&o.jsxs(o.Fragment,{children:[o.jsx(qt,{label:"Adresse LAN d'écoute",hint:"L'adresse de cette machine à laquelle le proxy se connectera.",children:({id:c,describedBy:u})=>e.candidateLanAddresses.length>0?o.jsxs("select",{id:c,"aria-describedby":u,className:"rounded-md border border-border bg-surface px-2 py-1.5 text-sm text-content",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value),children:[o.jsx("option",{value:"",children:"Sélectionner une adresse…"}),e.candidateLanAddresses.map(h=>o.jsx("option",{value:h,children:h},h))]}):o.jsx(ce,{id:c,"aria-describedby":u,placeholder:"192.168.1.42",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value)})}),o.jsx(qt,{label:"IP/CIDR du proxy autorisé",hint:"Ce n'est pas l'adresse d'écoute d'IdeA. C'est la machine autorisée à contacter IdeA.",children:({id:c,describedBy:u})=>o.jsx(ce,{id:c,"aria-describedby":u,placeholder:"203.0.113.7 or 203.0.113.0/24",value:n.trustedProxies.join(", "),onChange:h=>e.setTrustedProxies(h.target.value)})}),o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Si votre proxy n'est pas sur cet ordinateur, choisissez ce mode. Sinon, le proxy peut expirer sans erreur IdeA."})]}),e.warnings.map(c=>o.jsx("p",{className:"text-xs text-warning",children:c.message},c.code)),e.validationError&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.validationError})]})}),i&&o.jsx(ke,{title:"Configuration du proxy",children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("p",{className:"text-xs text-muted",children:"Faites pointer votre proxy inverse HTTPS vers cet upstream."}),e.upstreamUrl?o.jsx(pL,{value:e.upstreamUrl,copyLabel:"copier l'URL upstream"}):o.jsx("p",{className:"text-xs text-faint",children:"Complétez les paramètres ci-dessus pour obtenir l'URL upstream."})]})}),o.jsx(ke,{title:"Appairage",children:o.jsxs("p",{className:"text-sm text-muted",children:["L'appairage est géré dans"," ",o.jsx("span",{className:"text-content",children:"Paramètres → Appareils"}),", où vous pouvez générer un code et révoquer des appareils."]})})]})}const Aw={aiProfiles:"Profils IA",deployment:"Déploiement",devices:"Appareils",plugins:"Plugins"},Tw=["aiProfiles","deployment","devices","plugins"];function gL({section:e,onSectionChange:t,onClose:n}){return o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsxs("nav",{"aria-label":"settings sections",className:"flex w-52 shrink-0 flex-col gap-1 border-r border-border p-3",children:[Tw.map(r=>{const s=r===e;return o.jsx("button",{type:"button","aria-current":s?"page":void 0,onClick:()=>t(r),className:U("rounded-md px-3 py-2 text-left text-sm transition-colors",s?"bg-raised font-semibold text-content":"text-muted hover:bg-raised hover:text-content"),children:Aw[r]},r)}),o.jsx("div",{className:"mt-auto pt-2",children:o.jsx(M,{size:"sm",variant:"ghost",className:"w-full",onClick:n,children:"Fermer les paramètres"})})]}),o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-2xl",children:e==="aiProfiles"?o.jsx(jw,{}):e==="deployment"?o.jsx(mL,{}):e==="plugins"?o.jsx(hA,{}):o.jsx(Pw,{})})})]})}function Gi(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const xL={branches:[],current:null},jx=20;function vL(e){const{git:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(xL),[l,a]=g.useState([]),[c,u]=g.useState(!1),[h,d]=g.useState(null),f=g.useCallback(async()=>{u(!0),d(null);try{const[v,_,y]=await Promise.all([t.status(e),t.branches(e),t.log(e,jx)]);r(v),i(_),a(y)}catch(v){d(Gi(v))}finally{u(!1)}},[t,e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async v=>{u(!0),d(null);try{await t.stage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!0}:y))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async v=>{u(!0),d(null);try{await t.unstage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!1}:y))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]),x=g.useCallback(async v=>{u(!0),d(null);try{const _=await t.commit(e,v);r(y=>y.filter(b=>!b.staged)),a(y=>[_,...y].slice(0,jx))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]),w=g.useCallback(async v=>{u(!0),d(null);try{await t.checkout(e,v),i(_=>({branches:_.branches.includes(v)?_.branches:[..._.branches,v],current:v}))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]);return{files:n,branches:s,log:l,busy:c,error:h,refresh:f,stage:p,unstage:m,commit:x,checkout:w}}function Nx(e){const t={children:[]};for(const n of e){const r=n.path.split("/").filter(Boolean);let s=t;r.forEach((i,l)=>{const a=l===r.length-1,c=r.slice(0,l+1).join("/");let u=s.children.find(h=>h.name===i&&h.isDir===!a);u||(u={name:i,path:c,isDir:!a,staged:n.staged,children:[]},s.children.push(u)),s=u})}return Lw(t),t.children}function Lw(e){e.children.sort((t,n)=>t.isDir!==n.isDir?t.isDir?-1:1:t.name.localeCompare(n.name)),e.children.forEach(Lw)}function $h({nodes:e,depth:t,action:n,onAction:r,busy:s}){return o.jsx("ul",{className:"flex flex-col gap-0.5",children:e.map(i=>i.isDir?o.jsxs("li",{children:[o.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-xs text-muted",style:{paddingLeft:`${t*14+8}px`},children:[o.jsx("span",{"aria-hidden":!0,className:"text-faint",children:"▸"}),o.jsx("span",{className:"truncate",children:i.name})]}),o.jsx($h,{nodes:i.children,depth:t+1,action:n,onAction:r,busy:s})]},i.path):o.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:bg-raised",style:{paddingLeft:`${t*14+8}px`},children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{"aria-hidden":!0,className:U("size-1.5 shrink-0 rounded-full",n==="unstage"?"bg-success":"bg-warning")}),o.jsx("code",{className:"min-w-0 truncate text-xs text-content",children:i.name})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`${n} ${i.path}`,disabled:s,onClick:()=>r(i.path),className:"shrink-0 text-muted hover:text-content",children:n==="unstage"?"Unstage":"Stage"})]},i.path))})}function Dw({projectId:e}){const t=vL(e),[n,r]=g.useState(""),[s,i]=g.useState(""),l=t.files.filter(f=>f.staged),a=t.files.filter(f=>!f.staged),c=n.trim().length>0&&l.length>0&&!t.busy;async function u(f){f.preventDefault(),c&&(await t.commit(n.trim()),r(""))}async function h(f){await t.checkout(f)}async function d(f){f.preventDefault();const p=s.trim();!p||t.busy||(await t.checkout(p),i(""))}return o.jsxs(ke,{title:"Git",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("section",{"aria-label":"Changes",className:"border-b border-border p-4",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Changes"}),t.busy&&o.jsx(Me,{size:12})]}),t.files.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No changes."}):o.jsxs("div",{className:"flex flex-col gap-3",children:[l.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Staged"}),o.jsx($h,{nodes:Nx(l),depth:0,action:"unstage",onAction:f=>void t.unstage(f),busy:t.busy})]}),a.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Unstaged"}),o.jsx($h,{nodes:Nx(a),depth:0,action:"stage",onAction:f=>void t.stage(f),busy:t.busy})]})]})]}),o.jsxs("section",{"aria-label":"Commit",className:"border-b border-border p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Commit"}),o.jsxs("form",{onSubmit:u,className:"flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"commit message",placeholder:"Commit message",value:n,onChange:f=>r(f.target.value)}),o.jsx(M,{type:"submit",variant:"primary",disabled:!c,loading:t.busy,className:"self-end",children:"Commit"})]})]}),o.jsxs("section",{"aria-label":"Branches",className:"border-b border-border p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Branches"}),o.jsxs("p",{className:"mb-2 text-sm text-content",children:["Current:"," ",o.jsx("span",{className:"font-medium",children:t.branches.current??"(none)"})]}),t.branches.branches.length>0&&o.jsx("ul",{className:"mb-3 flex flex-col gap-0.5",children:t.branches.branches.map(f=>{const p=f===t.branches.current;return o.jsxs("li",{className:U("flex items-center justify-between gap-2 rounded-md px-2 py-1",p&&"bg-raised"),children:[o.jsx("span",{className:U("text-sm",p?"font-semibold text-primary":"text-content"),children:f}),!p&&o.jsx(M,{size:"sm",variant:"ghost","aria-label":`checkout ${f}`,disabled:t.busy,onClick:()=>void h(f),className:"shrink-0 text-muted hover:text-content",children:"Checkout"})]},f)})}),o.jsxs("form",{onSubmit:d,className:"flex items-center gap-2",children:[o.jsx(ce,{"aria-label":"new branch name",placeholder:"New branch",value:s,onChange:f=>i(f.target.value),className:"flex-1"}),o.jsx(M,{type:"submit",variant:"ghost",disabled:!s.trim()||t.busy,children:"Create & checkout"})]})]}),o.jsxs("section",{"aria-label":"Log",className:"p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Log"}),t.log.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No commits yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.log.map(f=>o.jsxs("li",{className:"flex items-baseline gap-2 py-1.5",children:[o.jsx("code",{className:"shrink-0 text-xs text-faint",children:f.hash.slice(0,7)}),o.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:f.summary})]},f.hash))})]})]})}const Ex=["#4f9cf9","#a78bfa","#34d399","#fbbf24","#f87171","#38bdf8","#fb923c","#c084fc","#f472b6","#2dd4bf"];function Yi(e){return Ex[e%Ex.length]}function _L(e){return e.indexOf(null)}function Px(e,t){const n=_L(e);return n!==-1?(e[n]=t,n):(e.push(t),e.length-1)}function yL(e){const t=[],n=[];for(const r of e){const{hash:s,parents:i}=r,l=t.slice();let a=t.indexOf(s);a===-1&&(a=Px(t,s));for(let f=0;f{a(!0),u(null);try{const d=await t.graph(e,bL);r(d),i(yL(d))}catch(d){u(d&&typeof d=="object"&&"message"in d?String(d.message):String(d))}finally{a(!1)}},[t,e]);return g.useEffect(()=>{h()},[h]),{commits:n,rows:s,busy:l,error:c,refresh:h}}const tc=16,ma=36,Ax=4.5,Wh=e=>e*tc+tc/2;function Tx(e,t,n){const r=Wh(e.fromLane),s=Wh(e.toLane);if(r===s)return`M ${r} ${t} L ${s} ${n}`;const i=(t+n)/2;return`M ${r} ${t} C ${r} ${i} ${s} ${i} ${s} ${n}`}function SL({row:e,laneCount:t}){const n=t*tc+tc/2,r=ma/2,s=Wh(e.lane);return o.jsxs("svg",{width:n,height:ma,"aria-hidden":!0,className:"shrink-0 overflow-visible",children:[e.incoming.map((i,l)=>o.jsx("path",{d:Tx(i,0,r),fill:"none",stroke:i.color,strokeWidth:2},`in-${l}`)),e.outgoing.map((i,l)=>o.jsx("path",{d:Tx(i,r,ma),fill:"none",stroke:i.color,strokeWidth:2},`out-${l}`)),o.jsx("circle",{cx:s,cy:r,r:Ax+1.5,className:"fill-canvas"}),o.jsx("circle",{cx:s,cy:r,r:Ax,fill:e.color,stroke:"var(--color-canvas)",strokeWidth:1})]})}function kL(e){const t=Math.floor(Date.now()/1e3)-e;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:t<31536e3?`${Math.floor(t/2592e3)}mo ago`:`${Math.floor(t/31536e3)}y ago`}function CL({commit:e,onClose:t}){const n=r=>r.startsWith("tag:");return o.jsxs("aside",{"aria-label":"commit detail",className:"flex w-80 shrink-0 flex-col gap-3 overflow-y-auto border-l border-border bg-surface p-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e.summary}),o.jsx("button",{type:"button","aria-label":"close commit detail",onClick:t,className:"shrink-0 text-muted hover:text-content",children:"×"})]}),o.jsxs("dl",{className:"flex flex-col gap-2 text-xs",children:[o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Hash"}),o.jsx("dd",{children:o.jsx("code",{className:"text-content break-all",children:e.hash})})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Author"}),o.jsx("dd",{className:"text-content",children:e.author})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Date"}),o.jsx("dd",{className:"text-content",children:new Date(e.timestamp*1e3).toLocaleString()})]}),e.parents.length>0&&o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Parents"}),o.jsx("dd",{className:"flex flex-col gap-0.5",children:e.parents.map(r=>o.jsx("code",{className:"text-content",children:r.slice(0,8)},r))})]}),e.refs.length>0&&o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Refs"}),o.jsx("dd",{className:"flex flex-wrap gap-1",children:e.refs.map(r=>o.jsx("span",{className:U("rounded px-1 py-0.5 text-xs font-medium text-base",n(r)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:r},r))})]})]})]})}function jL({projectId:e}){const t=wL(e),[n,r]=g.useState(null),s=n!=null?t.commits.find(a=>a.hash===n)??null:null,i=t.rows.reduce((a,c)=>Math.max(a,c.laneCount),1),l=a=>a.startsWith("tag:");return o.jsxs("div",{className:"flex flex-1 overflow-hidden","aria-label":"git graph",children:[o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:"Git Graph"}),t.busy&&o.jsx(Me,{size:14}),o.jsx("button",{type:"button","aria-label":"refresh git graph",onClick:()=>void t.refresh(),disabled:t.busy,className:"ml-auto text-xs text-muted hover:text-content disabled:opacity-40",children:"Refresh"})]}),t.error&&o.jsx("p",{role:"alert",className:"mx-3 mt-2 shrink-0 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger",children:t.error}),o.jsxs("div",{className:"flex-1 overflow-y-auto",role:"list","aria-label":"commits",children:[t.rows.length===0&&!t.busy&&o.jsx("p",{className:"p-4 text-sm text-muted",children:"No commits found."}),t.rows.map(a=>{const c=a.commit.hash===n;return o.jsxs("div",{role:"listitem","aria-label":`commit ${a.commit.hash.slice(0,8)}: ${a.commit.summary}`,onClick:()=>r(c?null:a.commit.hash),className:U("flex cursor-pointer items-center gap-2 border-b border-border/50 px-2 hover:bg-raised",c&&"bg-raised"),style:{height:ma},children:[o.jsx(SL,{row:a,laneCount:i}),a.commit.refs.length>0&&o.jsx("div",{className:"flex shrink-0 flex-wrap gap-1",children:a.commit.refs.map(u=>o.jsx("span",{className:U("rounded px-1 py-0.5 text-xs font-medium",l(u)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:u},u))}),o.jsx("code",{className:"shrink-0 text-xs text-faint",children:a.commit.hash.slice(0,8)}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:a.commit.summary}),o.jsx("span",{className:"shrink-0 text-xs text-muted",children:a.commit.author}),o.jsx("span",{className:"shrink-0 text-xs text-faint",children:kL(a.commit.timestamp)})]},a.commit.hash)})]})]}),s&&o.jsx(CL,{commit:s,onClose:()=>r(null)})]})}function Mo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NL(){const{project:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useCallback(async()=>{h(!0),c(null);try{n(await e.listProjects())}catch(v){c(Mo(v))}finally{h(!1)}},[e]);g.useEffect(()=>{d()},[d]);const f=g.useCallback(v=>{s(_=>_.some(y=>y.id===v.id)?_:[..._,v]),l(v.id)},[]),p=g.useCallback(async v=>{h(!0),c(null);try{const _=await e.openProject(v);f(_)}catch(_){c(Mo(_))}finally{h(!1)}},[e,f]),m=g.useCallback(async(v,_)=>{h(!0),c(null);try{const y=await e.createProject(v,_);n(b=>[...b,y]),f(y)}catch(y){c(Mo(y))}finally{h(!1)}},[e,f]),x=g.useCallback(async v=>{c(null);try{await e.closeProject(v)}catch(_){c(Mo(_))}s(_=>{const y=_.filter(b=>b.id!==v);return l(b=>b===v?y.at(-1)?.id??null:b),y})},[e]),w=g.useCallback(v=>{l(v)},[]);return{projects:t,openTabs:r,activeTabId:i,error:a,busy:u,refresh:d,createProject:m,openProject:p,closeTab:x,activateTab:w}}function EL({items:e,activeTabId:t,onSelect:n,onClose:r,projectsPanelOpen:s,onOpenProjectsPanel:i,className:l}){return o.jsxs("div",{className:U("flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",l),children:[e.length===0?o.jsx("p",{className:"px-2 text-sm text-muted",children:"No open tabs."}):o.jsx(WP,{items:e,value:t,onSelect:n,onClose:r}),o.jsx(M,{size:"sm",variant:"secondary",onClick:i,"aria-label":"open projects panel","aria-pressed":s,title:"Ajouter un projet",className:U("shrink-0",s&&"ring-1 ring-border-strong"),children:"+"})]})}function PL(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const AL=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,TL=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,LL={};function Lx(e,t){return(LL.jsx?TL:AL).test(e)}const DL=/[ \t\n\f\r]/g;function RL(e){return typeof e=="object"?e.type==="text"?Dx(e.value):!1:Dx(e)}function Dx(e){return e.replace(DL,"")===""}class to{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}to.prototype.normal={};to.prototype.property={};to.prototype.space=void 0;function Rw(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new to(n,r,t)}function Hh(e){return e.toLowerCase()}class Qt{constructor(t,n){this.attribute=n,this.property=t}}Qt.prototype.attribute="";Qt.prototype.booleanish=!1;Qt.prototype.boolean=!1;Qt.prototype.commaOrSpaceSeparated=!1;Qt.prototype.commaSeparated=!1;Qt.prototype.defined=!1;Qt.prototype.mustUseProperty=!1;Qt.prototype.number=!1;Qt.prototype.overloadedBoolean=!1;Qt.prototype.property="";Qt.prototype.spaceSeparated=!1;Qt.prototype.space=void 0;let ML=0;const ve=Es(),tt=Es(),Uh=Es(),Z=Es(),De=Es(),gs=Es(),tn=Es();function Es(){return 2**++ML}const qh=Object.freeze(Object.defineProperty({__proto__:null,boolean:ve,booleanish:tt,commaOrSpaceSeparated:tn,commaSeparated:gs,number:Z,overloadedBoolean:Uh,spaceSeparated:De},Symbol.toStringTag,{value:"Module"})),Bu=Object.keys(qh);class _p extends Qt{constructor(t,n,r,s){let i=-1;if(super(t,n),Rx(this,"space",s),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&FL.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Mx,HL);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Mx.test(i)){let l=i.replace(zL,WL);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}s=_p}return new s(r,t)}function WL(e){return"-"+e.toLowerCase()}function HL(e){return e.charAt(1).toUpperCase()}const UL=Rw([Mw,IL,Bw,zw,Fw],"html"),yp=Rw([Mw,OL,Bw,zw,Fw],"svg");function qL(e){return e.join(" ").trim()}var bp={},Ix=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,VL=/\n/g,KL=/^\s*/,GL=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,YL=/^:\s*/,XL=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,QL=/^[;\s]*/,JL=/^\s+|\s+$/g,ZL=` -`,Ox="/",Bx="*",os="",eD="comment",tD="declaration";function nD(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function s(m){var x=m.match(VL);x&&(n+=x.length);var w=m.lastIndexOf(ZL);r=~w?m.length-w:r+m.length}function i(){var m={line:n,column:r};return function(x){return x.position=new l(m),u(),x}}function l(m){this.start=m,this.end={line:n,column:r},this.source=t.source}l.prototype.content=e;function a(m){var x=new Error(t.source+":"+n+":"+r+": "+m);if(x.reason=m,x.filename=t.source,x.line=n,x.column=r,x.source=e,!t.silent)throw x}function c(m){var x=m.exec(e);if(x){var w=x[0];return s(w),e=e.slice(w.length),x}}function u(){c(KL)}function h(m){var x;for(m=m||[];x=d();)x!==!1&&m.push(x);return m}function d(){var m=i();if(!(Ox!=e.charAt(0)||Bx!=e.charAt(1))){for(var x=2;os!=e.charAt(x)&&(Bx!=e.charAt(x)||Ox!=e.charAt(x+1));)++x;if(x+=2,os===e.charAt(x-1))return a("End of comment missing");var w=e.slice(2,x-2);return r+=2,s(w),e=e.slice(x),r+=2,m({type:eD,comment:w})}}function f(){var m=i(),x=c(GL);if(x){if(d(),!c(YL))return a("property missing ':'");var w=c(XL),v=m({type:tD,property:zx(x[0].replace(Ix,os)),value:w?zx(w[0].replace(Ix,os)):os});return c(QL),v}}function p(){var m=[];h(m);for(var x;x=f();)x!==!1&&(m.push(x),h(m));return m}return u(),p()}function zx(e){return e?e.replace(JL,os):os}var rD=nD,sD=_a&&_a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(bp,"__esModule",{value:!0});bp.default=lD;const iD=sD(rD);function lD(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,iD.default)(e),s=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:l,value:a}=i;s?t(l,a,i):a&&(n=n||{},n[l]=a)}),n}var jc={};Object.defineProperty(jc,"__esModule",{value:!0});jc.camelCase=void 0;var oD=/^--[a-zA-Z0-9_-]+$/,aD=/-([a-z])/g,cD=/^[^-]+$/,uD=/^-(webkit|moz|ms|o|khtml)-/,dD=/^-(ms)-/,hD=function(e){return!e||cD.test(e)||oD.test(e)},fD=function(e,t){return t.toUpperCase()},Fx=function(e,t){return"".concat(t,"-")},pD=function(e,t){return t===void 0&&(t={}),hD(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(dD,Fx):e=e.replace(uD,Fx),e.replace(aD,fD))};jc.camelCase=pD;var mD=_a&&_a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},gD=mD(bp),xD=jc;function Vh(e,t){var n={};return!e||typeof e!="string"||(0,gD.default)(e,function(r,s){r&&s&&(n[(0,xD.camelCase)(r,t)]=s)}),n}Vh.default=Vh;var vD=Vh;const _D=nf(vD),$w=Ww("end"),wp=Ww("start");function Ww(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function yD(e){const t=wp(e),n=$w(e);if(t&&n)return{start:t,end:n}}function _l(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?$x(e.position):"start"in e||"end"in e?$x(e):"line"in e||"column"in e?Kh(e):""}function Kh(e){return Wx(e&&e.line)+":"+Wx(e&&e.column)}function $x(e){return Kh(e&&e.start)+"-"+Kh(e&&e.end)}function Wx(e){return e&&typeof e=="number"?e:1}class Lt extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?s=t:!i.cause&&t&&(l=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const a=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=_l(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=l&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Lt.prototype.file="";Lt.prototype.name="";Lt.prototype.reason="";Lt.prototype.message="";Lt.prototype.stack="";Lt.prototype.column=void 0;Lt.prototype.line=void 0;Lt.prototype.ancestors=void 0;Lt.prototype.cause=void 0;Lt.prototype.fatal=void 0;Lt.prototype.place=void 0;Lt.prototype.ruleId=void 0;Lt.prototype.source=void 0;const Sp={}.hasOwnProperty,bD=new Map,wD=/[A-Z]/g,SD=new Set(["table","tbody","thead","tfoot","tr"]),kD=new Set(["td","th"]),Hw="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function CD(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=DD(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=LD(n,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?yp:UL,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Uw(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function Uw(e,t,n){if(t.type==="element")return jD(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return ND(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return PD(e,t,n);if(t.type==="mdxjsEsm")return ED(e,t);if(t.type==="root")return AD(e,t,n);if(t.type==="text")return TD(e,t)}function jD(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=yp,e.schema=s),e.ancestors.push(t);const i=Vw(e,t.tagName,!1),l=RD(e,t);let a=Cp(e,t);return SD.has(t.tagName)&&(a=a.filter(function(c){return typeof c=="string"?!RL(c):!0})),qw(e,l,i,t),kp(l,a),e.ancestors.pop(),e.schema=r,e.create(t,i,l,n)}function ND(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Hl(e,t.position)}function ED(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Hl(e,t.position)}function PD(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=yp,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:Vw(e,t.name,!0),l=MD(e,t),a=Cp(e,t);return qw(e,l,i,t),kp(l,a),e.ancestors.pop(),e.schema=r,e.create(t,i,l,n)}function AD(e,t,n){const r={};return kp(r,Cp(e,t)),e.create(t,e.Fragment,r,n)}function TD(e,t){return t.value}function qw(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function kp(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function LD(e,t,n){return r;function r(s,i,l,a){const u=Array.isArray(l.children)?n:t;return a?u(i,l,a):u(i,l)}}function DD(e,t){return n;function n(r,s,i,l){const a=Array.isArray(i.children),c=wp(r);return t(s,i,l,a,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function RD(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&Sp.call(t.properties,s)){const i=ID(e,s,t.properties[s]);if(i){const[l,a]=i;e.tableCellAlignToStyle&&l==="align"&&typeof a=="string"&&kD.has(t.tagName)?r=a:n[l]=a}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function MD(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const a=l.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Hl(e,t.position);else{const s=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const a=r.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else Hl(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function Cp(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:bD;for(;++rs?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),e.splice(...l);else for(n&&e.splice(t,n);i0?(on(e,e.length,0,t),e):t}const qx={}.hasOwnProperty;function Gw(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ln(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const It=Gr(/[A-Za-z]/),At=Gr(/[\dA-Za-z]/),qD=Gr(/[#-'*+\--9=?A-Z^-~]/);function nc(e){return e!==null&&(e<32||e===127)}const Gh=Gr(/\d/),VD=Gr(/[\dA-Fa-f]/),KD=Gr(/[!-/:-@[-`{-~]/);function de(e){return e!==null&&e<-2}function Re(e){return e!==null&&(e<0||e===32)}function we(e){return e===-2||e===-1||e===32}const Nc=Gr(/\p{P}|\p{S}/u),ks=Gr(/\s/);function Gr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ji(e){const t=[];let n=-1,r=0,s=0;for(;++n55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(l=String.fromCharCode(i,a),s=1):l="�"}else l=String.fromCharCode(i);l&&(t.push(e.slice(r,n),encodeURIComponent(l)),r=n+s+1,l=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function je(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return we(c)?(e.enter(n),a(c)):t(c)}function a(c){return we(c)&&i++l))return;const N=t.events.length;let L=N,A,k;for(;L--;)if(t.events[L][0]==="exit"&&t.events[L][1].type==="chunkFlow"){if(A){k=t.events[L][1].end;break}A=!0}for(v(r),S=N;Sy;){const C=n[b];t.containerState=C[1],C[0].exit.call(t,e)}n.length=y}function _(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function JD(e,t,n){return je(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function vi(e){if(e===null||Re(e)||ks(e))return 1;if(Nc(e))return 2}function Ec(e,t,n){const r=[];let s=-1;for(;++s1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},f={...e[n][1].start};Kx(d,-c),Kx(f,c),l={type:c>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},a={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},i={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},s={type:c>1?"strong":"emphasis",start:{...l.start},end:{...a.end}},e[r][1].end={...l.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=xn(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=xn(u,[["enter",s,t],["enter",l,t],["exit",l,t],["enter",i,t]]),u=xn(u,Ec(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=xn(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(h=2,u=xn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):h=0,on(e,r-1,n-r+3,u),n=r+u.length-h-2;break}}for(n=-1;++n0&&we(S)?je(e,_,"linePrefix",i+1)(S):_(S)}function _(S){return S===null||de(S)?e.check(Gx,x,b)(S):(e.enter("codeFlowValue"),y(S))}function y(S){return S===null||de(S)?(e.exit("codeFlowValue"),_(S)):(e.consume(S),y)}function b(S){return e.exit("codeFenced"),t(S)}function C(S,N,L){let A=0;return k;function k(I){return S.enter("lineEnding"),S.consume(I),S.exit("lineEnding"),D}function D(I){return S.enter("codeFencedFence"),we(I)?je(S,R,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):R(I)}function R(I){return I===a?(S.enter("codeFencedFenceSequence"),E(I)):L(I)}function E(I){return I===a?(A++,S.consume(I),E):A>=l?(S.exit("codeFencedFenceSequence"),we(I)?je(S,O,"whitespace")(I):O(I)):L(I)}function O(I){return I===null||de(I)?(S.exit("codeFencedFence"),N(I)):L(I)}}}function uR(e,t,n){const r=this;return s;function s(l){return l===null?n(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const Fu={name:"codeIndented",tokenize:hR},dR={partial:!0,tokenize:fR};function hR(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),je(e,i,"linePrefix",5)(u)}function i(u){const h=r.events[r.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(u):n(u)}function l(u){return u===null?c(u):de(u)?e.attempt(dR,l,c)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||de(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),a)}function c(u){return e.exit("codeIndented"),t(u)}}function fR(e,t,n){const r=this;return s;function s(l){return r.parser.lazy[r.now().line]?n(l):de(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s):je(e,i,"linePrefix",5)(l)}function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(l):de(l)?s(l):n(l)}}const pR={name:"codeText",previous:gR,resolve:mR,tokenize:xR};function mR(e){let t=e.length-4,n=3,r,s;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const s=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return r&&Xi(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Xi(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Xi(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):e.interrupt(r.parser.constructs.flow,n,t)(l)}}function eS(e,t,n,r,s,i,l,a,c){const u=c||Number.POSITIVE_INFINITY;let h=0;return d;function d(v){return v===60?(e.enter(r),e.enter(s),e.enter(i),e.consume(v),e.exit(i),f):v===null||v===32||v===41||nc(v)?n(v):(e.enter(r),e.enter(l),e.enter(a),e.enter("chunkString",{contentType:"string"}),x(v))}function f(v){return v===62?(e.enter(i),e.consume(v),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(a),f(v)):v===null||v===60||de(v)?n(v):(e.consume(v),v===92?m:p)}function m(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function x(v){return!h&&(v===null||v===41||Re(v))?(e.exit("chunkString"),e.exit(a),e.exit(l),e.exit(r),t(v)):h999||p===null||p===91||p===93&&!c||p===94&&!a&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(e.exit(i),e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):de(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||de(p)||a++>999?(e.exit("chunkString"),h(p)):(e.consume(p),c||(c=!we(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),a++,d):d(p)}}function nS(e,t,n,r,s,i){let l;return a;function a(f){return f===34||f===39||f===40?(e.enter(r),e.enter(s),e.consume(f),e.exit(s),l=f===40?41:f,c):n(f)}function c(f){return f===l?(e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):(e.enter(i),u(f))}function u(f){return f===l?(e.exit(i),c(l)):f===null?n(f):de(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),je(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===l||f===null||de(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:h)}function d(f){return f===l||f===92?(e.consume(f),h):h(f)}}function yl(e,t){let n;return r;function r(s){return de(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):we(s)?je(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const CR={name:"definition",tokenize:NR},jR={partial:!0,tokenize:ER};function NR(e,t,n){const r=this;let s;return i;function i(p){return e.enter("definition"),l(p)}function l(p){return tS.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return s=Ln(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),c):n(p)}function c(p){return Re(p)?yl(e,u)(p):u(p)}function u(p){return eS(e,h,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(jR,d,d)(p)}function d(p){return we(p)?je(e,f,"whitespace")(p):f(p)}function f(p){return p===null||de(p)?(e.exit("definition"),r.parser.defined.push(s),t(p)):n(p)}}function ER(e,t,n){return r;function r(a){return Re(a)?yl(e,s)(a):n(a)}function s(a){return nS(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return we(a)?je(e,l,"whitespace")(a):l(a)}function l(a){return a===null||de(a)?t(a):n(a)}}const PR={name:"hardBreakEscape",tokenize:AR};function AR(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return de(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const TR={name:"headingAtx",resolve:LR,tokenize:DR};function LR(e,t){let n=e.length-2,r=3,s,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(s={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},on(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function DR(e,t,n){let r=0;return s;function s(h){return e.enter("atxHeading"),i(h)}function i(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&r++<6?(e.consume(h),l):h===null||Re(h)?(e.exit("atxHeadingSequence"),a(h)):n(h)}function a(h){return h===35?(e.enter("atxHeadingSequence"),c(h)):h===null||de(h)?(e.exit("atxHeading"),t(h)):we(h)?je(e,a,"whitespace")(h):(e.enter("atxHeadingText"),u(h))}function c(h){return h===35?(e.consume(h),c):(e.exit("atxHeadingSequence"),a(h))}function u(h){return h===null||h===35||Re(h)?(e.exit("atxHeadingText"),a(h)):(e.consume(h),u)}}const RR=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Xx=["pre","script","style","textarea"],MR={concrete:!0,name:"htmlFlow",resolveTo:BR,tokenize:zR},IR={partial:!0,tokenize:$R},OR={partial:!0,tokenize:FR};function BR(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function zR(e,t,n){const r=this;let s,i,l,a,c;return u;function u(T){return h(T)}function h(T){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(T),d}function d(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),i=!0,x):T===63?(e.consume(T),s=3,r.interrupt?t:j):It(T)?(e.consume(T),l=String.fromCharCode(T),w):n(T)}function f(T){return T===45?(e.consume(T),s=2,p):T===91?(e.consume(T),s=5,a=0,m):It(T)?(e.consume(T),s=4,r.interrupt?t:j):n(T)}function p(T){return T===45?(e.consume(T),r.interrupt?t:j):n(T)}function m(T){const re="CDATA[";return T===re.charCodeAt(a++)?(e.consume(T),a===re.length?r.interrupt?t:R:m):n(T)}function x(T){return It(T)?(e.consume(T),l=String.fromCharCode(T),w):n(T)}function w(T){if(T===null||T===47||T===62||Re(T)){const re=T===47,ee=l.toLowerCase();return!re&&!i&&Xx.includes(ee)?(s=1,r.interrupt?t(T):R(T)):RR.includes(l.toLowerCase())?(s=6,re?(e.consume(T),v):r.interrupt?t(T):R(T)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(T):i?_(T):y(T))}return T===45||At(T)?(e.consume(T),l+=String.fromCharCode(T),w):n(T)}function v(T){return T===62?(e.consume(T),r.interrupt?t:R):n(T)}function _(T){return we(T)?(e.consume(T),_):k(T)}function y(T){return T===47?(e.consume(T),k):T===58||T===95||It(T)?(e.consume(T),b):we(T)?(e.consume(T),y):k(T)}function b(T){return T===45||T===46||T===58||T===95||At(T)?(e.consume(T),b):C(T)}function C(T){return T===61?(e.consume(T),S):we(T)?(e.consume(T),C):y(T)}function S(T){return T===null||T===60||T===61||T===62||T===96?n(T):T===34||T===39?(e.consume(T),c=T,N):we(T)?(e.consume(T),S):L(T)}function N(T){return T===c?(e.consume(T),c=null,A):T===null||de(T)?n(T):(e.consume(T),N)}function L(T){return T===null||T===34||T===39||T===47||T===60||T===61||T===62||T===96||Re(T)?C(T):(e.consume(T),L)}function A(T){return T===47||T===62||we(T)?y(T):n(T)}function k(T){return T===62?(e.consume(T),D):n(T)}function D(T){return T===null||de(T)?R(T):we(T)?(e.consume(T),D):n(T)}function R(T){return T===45&&s===2?(e.consume(T),W):T===60&&s===1?(e.consume(T),G):T===62&&s===4?(e.consume(T),se):T===63&&s===3?(e.consume(T),j):T===93&&s===5?(e.consume(T),z):de(T)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(IR,q,E)(T)):T===null||de(T)?(e.exit("htmlFlowData"),E(T)):(e.consume(T),R)}function E(T){return e.check(OR,O,q)(T)}function O(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),I}function I(T){return T===null||de(T)?E(T):(e.enter("htmlFlowData"),R(T))}function W(T){return T===45?(e.consume(T),j):R(T)}function G(T){return T===47?(e.consume(T),l="",P):R(T)}function P(T){if(T===62){const re=l.toLowerCase();return Xx.includes(re)?(e.consume(T),se):R(T)}return It(T)&&l.length<8?(e.consume(T),l+=String.fromCharCode(T),P):R(T)}function z(T){return T===93?(e.consume(T),j):R(T)}function j(T){return T===62?(e.consume(T),se):T===45&&s===2?(e.consume(T),j):R(T)}function se(T){return T===null||de(T)?(e.exit("htmlFlowData"),q(T)):(e.consume(T),se)}function q(T){return e.exit("htmlFlow"),t(T)}}function FR(e,t,n){const r=this;return s;function s(l){return de(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i):n(l)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function $R(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(no,t,n)}}const WR={name:"htmlText",tokenize:HR};function HR(e,t,n){const r=this;let s,i,l;return a;function a(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),c}function c(j){return j===33?(e.consume(j),u):j===47?(e.consume(j),C):j===63?(e.consume(j),y):It(j)?(e.consume(j),L):n(j)}function u(j){return j===45?(e.consume(j),h):j===91?(e.consume(j),i=0,m):It(j)?(e.consume(j),_):n(j)}function h(j){return j===45?(e.consume(j),p):n(j)}function d(j){return j===null?n(j):j===45?(e.consume(j),f):de(j)?(l=d,G(j)):(e.consume(j),d)}function f(j){return j===45?(e.consume(j),p):d(j)}function p(j){return j===62?W(j):j===45?f(j):d(j)}function m(j){const se="CDATA[";return j===se.charCodeAt(i++)?(e.consume(j),i===se.length?x:m):n(j)}function x(j){return j===null?n(j):j===93?(e.consume(j),w):de(j)?(l=x,G(j)):(e.consume(j),x)}function w(j){return j===93?(e.consume(j),v):x(j)}function v(j){return j===62?W(j):j===93?(e.consume(j),v):x(j)}function _(j){return j===null||j===62?W(j):de(j)?(l=_,G(j)):(e.consume(j),_)}function y(j){return j===null?n(j):j===63?(e.consume(j),b):de(j)?(l=y,G(j)):(e.consume(j),y)}function b(j){return j===62?W(j):y(j)}function C(j){return It(j)?(e.consume(j),S):n(j)}function S(j){return j===45||At(j)?(e.consume(j),S):N(j)}function N(j){return de(j)?(l=N,G(j)):we(j)?(e.consume(j),N):W(j)}function L(j){return j===45||At(j)?(e.consume(j),L):j===47||j===62||Re(j)?A(j):n(j)}function A(j){return j===47?(e.consume(j),W):j===58||j===95||It(j)?(e.consume(j),k):de(j)?(l=A,G(j)):we(j)?(e.consume(j),A):W(j)}function k(j){return j===45||j===46||j===58||j===95||At(j)?(e.consume(j),k):D(j)}function D(j){return j===61?(e.consume(j),R):de(j)?(l=D,G(j)):we(j)?(e.consume(j),D):A(j)}function R(j){return j===null||j===60||j===61||j===62||j===96?n(j):j===34||j===39?(e.consume(j),s=j,E):de(j)?(l=R,G(j)):we(j)?(e.consume(j),R):(e.consume(j),O)}function E(j){return j===s?(e.consume(j),s=void 0,I):j===null?n(j):de(j)?(l=E,G(j)):(e.consume(j),E)}function O(j){return j===null||j===34||j===39||j===60||j===61||j===96?n(j):j===47||j===62||Re(j)?A(j):(e.consume(j),O)}function I(j){return j===47||j===62||Re(j)?A(j):n(j)}function W(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):n(j)}function G(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),P}function P(j){return we(j)?je(e,z,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):z(j)}function z(j){return e.enter("htmlTextData"),l(j)}}const Ep={name:"labelEnd",resolveAll:KR,resolveTo:GR,tokenize:YR},UR={tokenize:XR},qR={tokenize:QR},VR={tokenize:JR};function KR(e){let t=-1;const n=[];for(;++t=3&&(u===null||de(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===s?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),we(u)?je(e,a,"whitespace")(u):a(u))}}const Ht={continuation:{tokenize:aM},exit:uM,name:"list",tokenize:oM},iM={partial:!0,tokenize:dM},lM={partial:!0,tokenize:cM};function oM(e,t,n){const r=this,s=r.events[r.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,l=0;return a;function a(p){const m=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Gh(p)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(ga,n,u)(p):u(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(p)}return n(p)}function c(p){return Gh(p)&&++l<10?(e.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(no,r.interrupt?n:h,e.attempt(iM,f,d))}function h(p){return r.containerState.initialBlankLine=!0,i++,f(p)}function d(p){return we(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function aM(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(no,s,i);function s(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,je(e,t,"listItemIndent",r.containerState.size+1)(a)}function i(a){return r.containerState.furtherBlankLines||!we(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(lM,t,l)(a))}function l(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,je(e,e.attempt(Ht,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function cM(e,t,n){const r=this;return je(e,s,"listItemIndent",r.containerState.size+1);function s(i){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(i):n(i)}}function uM(e){e.exit(this.containerState.type)}function dM(e,t,n){const r=this;return je(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const l=r.events[r.events.length-1];return!we(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Qx={name:"setextUnderline",resolveTo:hM,tokenize:fM};function hM(e,t){let n=e.length,r,s,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(s=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const l={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",l,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=l,e.push(["exit",l,t]),e}function fM(e,t,n){const r=this;let s;return i;function i(u){let h=r.events.length,d;for(;h--;)if(r.events[h][1].type!=="lineEnding"&&r.events[h][1].type!=="linePrefix"&&r.events[h][1].type!=="content"){d=r.events[h][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),s=u,l(u)):n(u)}function l(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===s?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),we(u)?je(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||de(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const pM={tokenize:mM};function mM(e){const t=this,n=e.attempt(no,r,e.attempt(this.parser.constructs.flowInitial,s,je(e,e.attempt(this.parser.constructs.flow,s,e.attempt(yR,s)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const gM={resolveAll:sS()},xM=rS("string"),vM=rS("text");function rS(e){return{resolveAll:sS(e==="text"?_M:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,l,a);return l;function l(h){return u(h)?i(h):a(h)}function a(h){if(h===null){n.consume(h);return}return n.enter("data"),n.consume(h),c}function c(h){return u(h)?(n.exit("data"),i(h)):(n.consume(h),c)}function u(h){if(h===null)return!0;const d=s[h];let f=-1;if(d)for(;++f-1){const a=l[0];typeof a=="string"?l[0]=a.slice(r):l.shift()}i>0&&l.push(e[s].slice(0,i))}return l}function LM(e,t){let n=-1;const r=[];let s;for(;++n0){const kn=xe.tokenStack[xe.tokenStack.length-1];(kn[1]||Zx).call(xe,void 0,kn[0])}for(te.position={start:wr(H.length>0?H[0][1].start:{line:1,column:1,offset:0}),end:wr(H.length>0?H[H.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le0&&(r.className=["language-"+s[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function VM(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function KM(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function GM(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),s=ji(r.toLowerCase()),i=e.footnoteOrder.indexOf(r);let l,a=e.footnoteCounts.get(r);a===void 0?(a=0,e.footnoteOrder.push(r),l=e.footnoteOrder.length):l=i+1,a+=1,e.footnoteCounts.set(r,a);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+s,id:n+"fnref-"+s+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function YM(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function XM(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function oS(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const s=e.all(t),i=s[0];i&&i.type==="text"?i.value="["+i.value:s.unshift({type:"text",value:"["});const l=s[s.length-1];return l&&l.type==="text"?l.value+=r:s.push({type:"text",value:r}),s}function QM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return oS(e,t);const s={src:ji(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(t,i),e.applyData(t,i)}function JM(e,t){const n={src:ji(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function ZM(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function eI(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return oS(e,t);const s={href:ji(r.url||"")};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"a",properties:s,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tI(e,t){const n={href:ji(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function nI(e,t,n){const r=e.all(t),s=n?rI(n):aS(t),i={},l=[];if(typeof t.checked=="boolean"){const h=r[0];let d;h&&h.type==="element"&&h.tagName==="p"?d=h:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let a=-1;for(;++a1}function sI(e,t){const n={},r=e.all(t);let s=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++s0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},a=wp(t.children[1]),c=$w(t.children[t.children.length-1]);a&&c&&(l.position={start:a,end:c}),s.push(l)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function cI(e,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,a=l?l.length:t.children.length;let c=-1;const u=[];for(;++c0,!0),r[0]),s=r.index+r[0].length,r=n.exec(t);return i.push(nv(t.slice(s),s>0,!1)),i.join("")}function nv(e,t,n){let r=0,s=e.length;if(t){let i=e.codePointAt(r);for(;i===ev||i===tv;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(s-1);for(;i===ev||i===tv;)s--,i=e.codePointAt(s-1)}return s>r?e.slice(r,s):""}function hI(e,t){const n={type:"text",value:dI(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function fI(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const pI={blockquote:HM,break:UM,code:qM,delete:VM,emphasis:KM,footnoteReference:GM,heading:YM,html:XM,imageReference:QM,image:JM,inlineCode:ZM,linkReference:eI,link:tI,listItem:nI,list:sI,paragraph:iI,root:lI,strong:oI,table:aI,tableCell:uI,tableRow:cI,text:hI,thematicBreak:fI,toml:Io,yaml:Io,definition:Io,footnoteDefinition:Io};function Io(){}const cS=-1,Pc=0,bl=1,rc=2,Pp=3,Ap=4,Tp=5,Lp=6,uS=7,dS=8,mI=typeof self=="object"?self:globalThis,rv=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new mI[e](t)},gI=(e,t)=>{const n=(s,i)=>(e.set(i,s),s),r=s=>{if(e.has(s))return e.get(s);const[i,l]=t[s];switch(i){case Pc:case cS:return n(l,s);case bl:{const a=n([],s);for(const c of l)a.push(r(c));return a}case rc:{const a=n({},s);for(const[c,u]of l)a[r(c)]=r(u);return a}case Pp:return n(new Date(l),s);case Ap:{const{source:a,flags:c}=l;return n(new RegExp(a,c),s)}case Tp:{const a=n(new Map,s);for(const[c,u]of l)a.set(r(c),r(u));return a}case Lp:{const a=n(new Set,s);for(const c of l)a.add(r(c));return a}case uS:{const{name:a,message:c}=l;return n(rv(a,c),s)}case dS:return n(BigInt(l),s);case"BigInt":return n(Object(BigInt(l)),s);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:a}=new Uint8Array(l);return n(new DataView(a),l)}}return n(rv(i,l),s)};return r},sv=e=>gI(new Map,e)(0),Bs="",{toString:xI}={},{keys:vI}=Object,Qi=e=>{const t=typeof e;if(t!=="object"||!e)return[Pc,t];const n=xI.call(e).slice(8,-1);switch(n){case"Array":return[bl,Bs];case"Object":return[rc,Bs];case"Date":return[Pp,Bs];case"RegExp":return[Ap,Bs];case"Map":return[Tp,Bs];case"Set":return[Lp,Bs];case"DataView":return[bl,n]}return n.includes("Array")?[bl,n]:n.includes("Error")?[uS,n]:[rc,n]},Oo=([e,t])=>e===Pc&&(t==="function"||t==="symbol"),_I=(e,t,n,r)=>{const s=(l,a)=>{const c=r.push(l)-1;return n.set(a,c),c},i=l=>{if(n.has(l))return n.get(l);let[a,c]=Qi(l);switch(a){case Pc:{let h=l;switch(c){case"bigint":a=dS,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);h=null;break;case"undefined":return s([cS],l)}return s([a,h],l)}case bl:{if(c){let f=l;return c==="DataView"?f=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(f=new Uint8Array(l)),s([c,[...f]],l)}const h=[],d=s([a,h],l);for(const f of l)h.push(i(f));return d}case rc:{if(c)switch(c){case"BigInt":return s([c,l.toString()],l);case"Boolean":case"Number":case"String":return s([c,l.valueOf()],l)}if(t&&"toJSON"in l)return i(l.toJSON());const h=[],d=s([a,h],l);for(const f of vI(l))(e||!Oo(Qi(l[f])))&&h.push([i(f),i(l[f])]);return d}case Pp:return s([a,l.toISOString()],l);case Ap:{const{source:h,flags:d}=l;return s([a,{source:h,flags:d}],l)}case Tp:{const h=[],d=s([a,h],l);for(const[f,p]of l)(e||!(Oo(Qi(f))||Oo(Qi(p))))&&h.push([i(f),i(p)]);return d}case Lp:{const h=[],d=s([a,h],l);for(const f of l)(e||!Oo(Qi(f)))&&h.push(i(f));return d}}const{message:u}=l;return s([a,{name:c,message:u}],l)};return i},iv=(e,{json:t,lossy:n}={})=>{const r=[];return _I(!(t||n),!!t,new Map,r)(e),r},sc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?sv(iv(e,t)):structuredClone(e):(e,t)=>sv(iv(e,t));function yI(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function bI(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function wI(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||yI,r=e.options.footnoteBackLabel||bI,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let c=-1;for(;++c0&&m.push({type:"text",value:" "});let _=typeof n=="string"?n:n(c,p);typeof _=="string"&&(_={type:"text",value:_}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const w=h[h.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const _=w.children[w.children.length-1];_&&_.type==="text"?_.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...m)}else h.push(...m);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(h,!0)};e.patch(u,v),a.push(v)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...sc(l),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:` -`}]}}const Ac=function(e){if(e==null)return jI;if(typeof e=="function")return Tc(e);if(typeof e=="object")return Array.isArray(e)?SI(e):kI(e);if(typeof e=="string")return CI(e);throw new Error("Expected function, string, or object as test")};function SI(e){const t=[];let n=-1;for(;++n":""))+")"})}return f;function f(){let p=hS,m,x,w;if((!t||i(c,u,h[h.length-1]||void 0))&&(p=AI(n(c,h)),p[0]===Xh))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==PI)for(x=(r?v.children.length:-1)+l,w=h.concat(v);x>-1&&x0&&n.push({type:"text",value:` -`}),n}function lv(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function ov(e,t){const n=LI(e,t),r=n.one(e,void 0),s=wI(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return s&&i.children.push({type:"text",value:` -`},s),i}function OI(e,t){return e&&"run"in e?async function(n,r){const s=ov(n,{file:r,...t});await e.run(s,r)}:function(n,r){return ov(n,{file:r,...e||t})}}function av(e){if(e)throw e}var xa=Object.prototype.hasOwnProperty,pS=Object.prototype.toString,cv=Object.defineProperty,uv=Object.getOwnPropertyDescriptor,dv=function(t){return typeof Array.isArray=="function"?Array.isArray(t):pS.call(t)==="[object Array]"},hv=function(t){if(!t||pS.call(t)!=="[object Object]")return!1;var n=xa.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&xa.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var s;for(s in t);return typeof s>"u"||xa.call(t,s)},fv=function(t,n){cv&&n.name==="__proto__"?cv(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},pv=function(t,n){if(n==="__proto__")if(xa.call(t,n)){if(uv)return uv(t,n).value}else return;return t[n]},BI=function e(){var t,n,r,s,i,l,a=arguments[0],c=1,u=arguments.length,h=!1;for(typeof a=="boolean"&&(h=a,a=arguments[1]||{},c=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});cl.length;let c;a&&l.push(s);try{c=e.apply(this,l)}catch(u){const h=u;if(a&&n)throw h;return s(h)}a||(c&&c.then&&typeof c.then=="function"?c.then(i,s):c instanceof Error?s(c):i(c))}function s(l,...a){n||(n=!0,t(l,...a))}function i(l){s(null,l)}}const $n={basename:$I,dirname:WI,extname:HI,join:UI,sep:"/"};function $I(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ro(e);let n=0,r=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else r<0&&(i=!0,r=s+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,a=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else l<0&&(i=!0,l=s+1),a>-1&&(e.codePointAt(s)===t.codePointAt(a--)?a<0&&(r=s):(a=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function WI(e){if(ro(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function HI(e){ro(e);let t=e.length,n=-1,r=0,s=-1,i=0,l;for(;t--;){const a=e.codePointAt(t);if(a===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),a===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||n<0||i===0||i===1&&s===n-1&&s===r+1?"":e.slice(s,n)}function UI(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function VI(e,t){let n="",r=0,s=-1,i=0,l=-1,a,c;for(;++l<=e.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,i=0;continue}}else if(n.length>0){n="",r=0,s=l,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,i=0}else a===46&&i>-1?i++:i=-1}return n}function ro(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const KI={cwd:GI};function GI(){return"/"}function Zh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function YI(e){if(typeof e=="string")e=new URL(e);else if(!Zh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return XI(e)}function XI(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[p,...m]=h;const x=r[f][1];Jh(x)&&Jh(p)&&(p=Wu(!0,x,p)),r[f]=[u,p,...m]}}}}const e3=new Rp().freeze();function Vu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ku(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Gu(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function gv(e){if(!Jh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function xv(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Bo(e){return t3(e)?e:new mS(e)}function t3(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function n3(e){return typeof e=="string"||r3(e)}function r3(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const s3="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",vv=[],_v={allowDangerousHtml:!0},i3=/^(https?|ircs?|mailto|xmpp)$/i,l3=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function gS(e){const t=o3(e),n=a3(e);return c3(t.runSync(t.parse(n),n),e)}function o3(e){const t=e.rehypePlugins||vv,n=e.remarkPlugins||vv,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,..._v}:_v;return e3().use(WM).use(n).use(OI,r).use(t)}function a3(e){const t=e.children||"",n=new mS;return typeof t=="string"&&(n.value=t),n}function c3(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,l=t.skipHtml,a=t.unwrapDisallowed,c=t.urlTransform||u3;for(const h of l3)Object.hasOwn(t,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+s3+h.id,void 0);return Dp(e,u),CD(e,{Fragment:o.Fragment,components:s,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(h,d,f){if(h.type==="raw"&&f&&typeof d=="number")return l?f.children.splice(d,1):f.children[d]={type:"text",value:h.value},d;if(h.type==="element"){let p;for(p in zu)if(Object.hasOwn(zu,p)&&Object.hasOwn(h.properties,p)){const m=h.properties[p],x=zu[p];(x===null||x.includes(h.tagName))&&(h.properties[p]=c(String(m||""),p,h))}}if(h.type==="element"){let p=n?!n.includes(h.tagName):i?i.includes(h.tagName):!1;if(!p&&r&&typeof d=="number"&&(p=!r(h,d,f)),p&&f&&typeof d=="number")return a&&h.children?f.children.splice(d,1,...h.children):f.children.splice(d,1),d}}}function u3(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),s=e.indexOf("/");return t===-1||s!==-1&&t>s||n!==-1&&t>n||r!==-1&&t>r||i3.test(e.slice(0,t))?e:""}function yv(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,s=n.indexOf(t);for(;s!==-1;)r++,s=n.indexOf(t,s+t.length);return r}function d3(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function h3(e,t,n){const s=Ac((n||{}).ignore||[]),i=f3(t);let l=-1;for(;++l0?{type:"text",value:S}:void 0),S===!1?f.lastIndex=b+1:(m!==b&&_.push({type:"text",value:u.value.slice(m,b)}),Array.isArray(S)?_.push(...S):S&&_.push(S),m=b+y[0].length,v=!0),!f.global)break;y=f.exec(u.value)}return v?(m?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const s=yv(e,"(");let i=yv(e,")");for(;r!==-1&&s>i;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[e,n]}function xS(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||ks(n)||Nc(n))&&(!t||n!==47)}vS.peek=I3;function E3(){this.buffer()}function P3(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function A3(){this.buffer()}function T3(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function L3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ln(this.sliceSerialize(e)).toLowerCase(),n.label=t}function D3(e){this.exit(e)}function R3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ln(this.sliceSerialize(e)).toLowerCase(),n.label=t}function M3(e){this.exit(e)}function I3(){return"["}function vS(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const l=n.enter("footnoteReference"),a=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),a(),l(),i+=s.move("]"),i}function O3(){return{enter:{gfmFootnoteCallString:E3,gfmFootnoteCall:P3,gfmFootnoteDefinitionLabelString:A3,gfmFootnoteDefinition:T3},exit:{gfmFootnoteCallString:L3,gfmFootnoteCall:D3,gfmFootnoteDefinitionLabelString:R3,gfmFootnoteDefinition:M3}}}function B3(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:vS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,l){const a=i.createTracker(l);let c=a.move("[^");const u=i.enter("footnoteDefinition"),h=i.enter("label");return c+=a.move(i.safe(i.associationId(r),{before:c,after:"]"})),h(),c+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),c+=a.move((t?` -`:" ")+i.indentLines(i.containerFlow(r,a.current()),t?_S:z3))),u(),c}}function z3(e,t,n){return t===0?e:_S(e,t,n)}function _S(e,t,n){return(n?"":" ")+e}const F3=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];yS.peek=q3;function $3(){return{canContainEols:["delete"],enter:{strikethrough:H3},exit:{strikethrough:U3}}}function W3(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:F3}],handlers:{delete:yS}}}function H3(e){this.enter({type:"delete",children:[]},e)}function U3(e){this.exit(e)}function yS(e,t,n,r){const s=n.createTracker(r),i=n.enter("strikethrough");let l=s.move("~~");return l+=n.containerPhrasing(e,{...s.current(),before:l,after:"~"}),l+=s.move("~~"),i(),l}function q3(){return"~"}function V3(e){return e.length}function K3(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||V3,i=[],l=[],a=[],c=[];let u=0,h=-1;for(;++hu&&(u=e[h].length);++vc[v])&&(c[v]=y)}x.push(_)}l[h]=x,a[h]=w}let d=-1;if(typeof r=="object"&&"length"in r)for(;++dc[d]&&(c[d]=_),p[d]=_),f[d]=y}l.splice(1,0,f),a.splice(1,0,p),h=-1;const m=[];for(;++h "),i.shift(2);const l=n.indentLines(n.containerFlow(e,i.current()),X3);return s(),l}function X3(e,t,n){return">"+(n?"":" ")+e}function Q3(e,t){return wv(e,t.inConstruct,!0)&&!wv(e,t.notInConstruct,!1)}function wv(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++rl&&(l=i):i=1,s=r+t.length,r=n.indexOf(t,s);return l}function Z3(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function e5(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function t5(e,t,n,r){const s=e5(n),i=e.value||"",l=s==="`"?"GraveAccent":"Tilde";if(Z3(e,n)){const d=n.enter("codeIndented"),f=n.indentLines(i,n5);return d(),f}const a=n.createTracker(r),c=s.repeat(Math.max(J3(i,s)+1,3)),u=n.enter("codeFenced");let h=a.move(c);if(e.lang){const d=n.enter(`codeFencedLang${l}`);h+=a.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...a.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${l}`);h+=a.move(" "),h+=a.move(n.safe(e.meta,{before:h,after:` -`,encode:["`"],...a.current()})),d()}return h+=a.move(` -`),i&&(h+=a.move(i+` -`)),h+=a.move(c),u(),h}function n5(e,t,n){return(n?"":" ")+e}function Mp(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function r5(e,t,n,r){const s=Mp(n),i=s==='"'?"Quote":"Apostrophe",l=n.enter("definition");let a=n.enter("label");const c=n.createTracker(r);let u=c.move("[");return u+=c.move(n.safe(n.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),a(),!e.url||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(a=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":` -`,...c.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(n.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),a()),l(),u}function s5(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ul(e){return"&#x"+e.toString(16).toUpperCase()+";"}function ic(e,t,n){const r=vi(e),s=vi(t);return r===void 0?s===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}bS.peek=i5;function bS(e,t,n,r){const s=s5(n),i=n.enter("emphasis"),l=n.createTracker(r),a=l.move(s);let c=l.move(n.containerPhrasing(e,{after:s,before:a,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,s);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,s);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},a+c+p}function i5(e,t,n){return n.options.emphasis||"*"}function l5(e,t){let n=!1;return Dp(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Xh}),!!((!e.depth||e.depth<3)&&jp(e)&&(t.options.setext||n))}function o5(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(l5(e,n)){const h=n.enter("headingSetext"),d=n.enter("phrasing"),f=n.containerPhrasing(e,{...i.current(),before:` -`,after:` -`});return d(),h(),f+` -`+(s===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(` -`))+1))}const l="#".repeat(s),a=n.enter("headingAtx"),c=n.enter("phrasing");i.move(l+" ");let u=n.containerPhrasing(e,{before:"# ",after:` -`,...i.current()});return/^[\t ]/.test(u)&&(u=Ul(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,n.options.closeAtx&&(u+=" "+l),c(),a(),u}wS.peek=a5;function wS(e){return e.value||""}function a5(){return"<"}SS.peek=c5;function SS(e,t,n,r){const s=Mp(n),i=s==='"'?"Quote":"Apostrophe",l=n.enter("image");let a=n.enter("label");const c=n.createTracker(r);let u=c.move("![");return u+=c.move(n.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),a(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(a=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(n.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),a()),u+=c.move(")"),l(),u}function c5(){return"!"}kS.peek=u5;function kS(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let l=n.enter("label");const a=n.createTracker(r);let c=a.move("![");const u=n.safe(e.alt,{before:c,after:"]",...a.current()});c+=a.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...a.current()});return l(),n.stack=h,i(),s==="full"||!u||u!==d?c+=a.move(d+"]"):s==="shortcut"?c=c.slice(0,-1):c+=a.move("]"),c}function u5(){return"!"}CS.peek=d5;function CS(e,t,n){let r=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i\u007F]/.test(e.url))}NS.peek=h5;function NS(e,t,n,r){const s=Mp(n),i=s==='"'?"Quote":"Apostrophe",l=n.createTracker(r);let a,c;if(jS(e,n)){const h=n.stack;n.stack=[],a=n.enter("autolink");let d=l.move("<");return d+=l.move(n.containerPhrasing(e,{before:d,after:">",...l.current()})),d+=l.move(">"),a(),n.stack=h,d}a=n.enter("link"),c=n.enter("label");let u=l.move("[");return u+=l.move(n.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(c=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),c(),e.title&&(c=n.enter(`title${i}`),u+=l.move(" "+s),u+=l.move(n.safe(e.title,{before:u,after:s,...l.current()})),u+=l.move(s),c()),u+=l.move(")"),a(),u}function h5(e,t,n){return jS(e,n)?"<":"["}ES.peek=f5;function ES(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let l=n.enter("label");const a=n.createTracker(r);let c=a.move("[");const u=n.containerPhrasing(e,{before:c,after:"]",...a.current()});c+=a.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...a.current()});return l(),n.stack=h,i(),s==="full"||!u||u!==d?c+=a.move(d+"]"):s==="shortcut"?c=c.slice(0,-1):c+=a.move("]"),c}function f5(){return"["}function Ip(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function p5(e){const t=Ip(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function m5(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function PS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function g5(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let l=e.ordered?m5(n):Ip(n);const a=e.ordered?l==="."?")":".":p5(n);let c=t&&n.bulletLastUsed?l===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),PS(n)===l&&h){let d=-1;for(;++d-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let l=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(l=Math.ceil(l/4)*4);const a=n.createTracker(r);a.move(i+" ".repeat(l-i.length)),a.shift(l);const c=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,a.current()),h);return c(),u;function h(d,f,p){return f?(p?"":" ".repeat(l))+d:(p?i:i+" ".repeat(l-i.length))+d}}function _5(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),l=n.containerPhrasing(e,r);return i(),s(),l}const y5=Ac(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function b5(e,t,n,r){return(e.children.some(function(l){return y5(l)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function w5(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}AS.peek=S5;function AS(e,t,n,r){const s=w5(n),i=n.enter("strong"),l=n.createTracker(r),a=l.move(s+s);let c=l.move(n.containerPhrasing(e,{after:s,before:a,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,s);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,s);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},a+c+p}function S5(e,t,n){return n.options.strong||"*"}function k5(e,t,n,r){return n.safe(e.value,r)}function C5(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function j5(e,t,n){const r=(PS(n)+(n.options.ruleSpaces?" ":"")).repeat(C5(n));return n.options.ruleSpaces?r.slice(0,-1):r}const TS={blockquote:Y3,break:Sv,code:t5,definition:r5,emphasis:bS,hardBreak:Sv,heading:o5,html:wS,image:SS,imageReference:kS,inlineCode:CS,link:NS,linkReference:ES,list:g5,listItem:v5,paragraph:_5,root:b5,strong:AS,text:k5,thematicBreak:j5};function N5(){return{enter:{table:E5,tableData:kv,tableHeader:kv,tableRow:A5},exit:{codeText:T5,table:P5,tableData:Ju,tableHeader:Ju,tableRow:Ju}}}function E5(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function P5(e){this.exit(e),this.data.inTable=void 0}function A5(e){this.enter({type:"tableRow",children:[]},e)}function Ju(e){this.exit(e)}function kv(e){this.enter({type:"tableCell",children:[]},e)}function T5(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,L5));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function L5(e,t){return t==="|"?t:e}function D5(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:c,tableRow:a}};function l(p,m,x,w){return u(h(p,x,w),p.align)}function a(p,m,x,w){const v=d(p,x,w),_=u([v]);return _.slice(0,_.indexOf(` -`))}function c(p,m,x,w){const v=x.enter("tableCell"),_=x.enter("phrasing"),y=x.containerPhrasing(p,{...w,before:i,after:i});return _(),v(),y}function u(p,m){return K3(p,{align:m,alignDelimiters:r,padding:n,stringLength:s})}function h(p,m,x){const w=p.children;let v=-1;const _=[],y=m.enter("table");for(;++v0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const Q5={tokenize:iO,partial:!0};function J5(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:nO,continuation:{tokenize:rO},exit:sO}},text:{91:{name:"gfmFootnoteCall",tokenize:tO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Z5,resolveTo:eO}}}}function Z5(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let l;for(;s--;){const c=r.events[s][1];if(c.type==="labelImage"){l=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return a;function a(c){if(!l||!l._balanced)return n(c);const u=Ln(r.sliceSerialize({start:l.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function eO(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",l,t],["exit",l,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function tO(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,l;return a;function a(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),c}function c(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(i>999||d===93&&!l||d===null||d===91||Re(d))return n(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return s.includes(Ln(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return Re(d)||(l=!0),i++,e.consume(d),d===92?h:u}function h(d){return d===91||d===92||d===93?(e.consume(d),i++,u):u(d)}}function nO(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,l=0,a;return c;function c(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):n(m)}function h(m){if(l>999||m===93&&!a||m===null||m===91||Re(m))return n(m);if(m===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return i=Ln(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Re(m)||(a=!0),l++,e.consume(m),m===92?d:h}function d(m){return m===91||m===92||m===93?(e.consume(m),l++,h):h(m)}function f(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),s.includes(i)||s.push(i),je(e,p,"gfmFootnoteDefinitionWhitespace")):n(m)}function p(m){return t(m)}}function rO(e,t,n){return e.check(no,t,e.attempt(Q5,t,n))}function sO(e){e.exit("gfmFootnoteDefinition")}function iO(e,t,n){const r=this;return je(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const l=r.events[r.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?t(i):n(i)}}function lO(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(l,a){let c=-1;for(;++c1?c(m):(l.consume(m),d++,p);if(d<2&&!n)return c(m);const w=l.exit("strikethroughSequenceTemporary"),v=vi(m);return w._open=!v||v===2&&!!x,w._close=!x||x===2&&!!v,a(m)}}}class oO{constructor(){this.map=[]}add(t,n,r){aO(this,t,n,r)}consume(t){if(this.map.sort(function(i,l){return i[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function aO(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s-1;){const O=r.events[D][1].type;if(O==="lineEnding"||O==="linePrefix")D--;else break}const R=D>-1?r.events[D][1].type:null,E=R==="tableHead"||R==="tableRow"?S:c;return E===S&&r.parser.lazy[r.now().line]?n(k):E(k)}function c(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(l=!0,i+=1),h(k)}function h(k){return k===null?n(k):de(k)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),p):n(k):we(k)?je(e,h,"whitespace")(k):(i+=1,l&&(l=!1,s+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),d(k)))}function d(k){return k===null||k===124||Re(k)?(e.exit("data"),h(k)):(e.consume(k),k===92?f:d)}function f(k){return k===92||k===124?(e.consume(k),d):d(k)}function p(k){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(k):(e.enter("tableDelimiterRow"),l=!1,we(k)?je(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):m(k))}function m(k){return k===45||k===58?w(k):k===124?(l=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),x):C(k)}function x(k){return we(k)?je(e,w,"whitespace")(k):w(k)}function w(k){return k===58?(i+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),v):k===45?(i+=1,v(k)):k===null||de(k)?b(k):C(k)}function v(k){return k===45?(e.enter("tableDelimiterFiller"),_(k)):C(k)}function _(k){return k===45?(e.consume(k),_):k===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),y):(e.exit("tableDelimiterFiller"),y(k))}function y(k){return we(k)?je(e,b,"whitespace")(k):b(k)}function b(k){return k===124?m(k):k===null||de(k)?!l||s!==i?C(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):C(k)}function C(k){return n(k)}function S(k){return e.enter("tableRow"),N(k)}function N(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),N):k===null||de(k)?(e.exit("tableRow"),t(k)):we(k)?je(e,N,"whitespace")(k):(e.enter("data"),L(k))}function L(k){return k===null||k===124||Re(k)?(e.exit("data"),N(k)):(e.consume(k),k===92?A:L)}function A(k){return k===92||k===124?(e.consume(k),L):L(k)}}function hO(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],l=[0,0,0,0],a=!1,c=0,u,h,d;const f=new oO;for(;++nn[2]+1){const m=n[2]+1,x=n[3]-n[2]-1;e.add(m,x,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},Ws(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function jv(e,t,n,r,s){const i=[],l=Ws(t.events,n);s&&(s.end=Object.assign({},l),i.push(["exit",s,t])),r.end=Object.assign({},l),i.push(["exit",r,t]),e.add(n+1,0,i)}function Ws(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const fO={name:"tasklistCheck",tokenize:mO};function pO(){return{text:{91:fO}}}function mO(e,t,n){const r=this;return s;function s(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),i)}function i(c){return Re(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),l):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),l):n(c)}function l(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(c)}function a(c){return de(c)?t(c):we(c)?e.check({tokenize:gO},t,n)(c):n(c)}}function gO(e,t,n){return je(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function xO(e){return Gw([W5(),J5(),lO(e),uO(),pO()])}const vO={};function FS(e){const t=this,n=e||vO,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),l=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(xO(n)),i.push(B5()),l.push(z5(n))}function _O({template:e,profiles:t,onSave:n,onClose:r,busy:s=!1}){const[i,l]=g.useState(e?.name??""),[a,c]=g.useState(e?.contentMd??""),[u,h]=g.useState(e?.defaultProfileId??""),[d,f]=g.useState("edit"),p=i.trim().length>0&&!s;async function m(x){x.preventDefault(),p&&await n(i.trim(),a,u)}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"template editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:e?`Edit template — ${e.name}`:"New template"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close template editor",onClick:r,disabled:s,children:"✕"})]}),o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"te-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"te-name","aria-label":"template name",placeholder:"My template",value:i,onChange:x=>l(x.target.value),disabled:s,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"te-profile",className:"text-xs font-medium text-muted",children:"Default profile"}),t.length>0?o.jsxs("select",{id:"te-profile","aria-label":"template default profile",value:u,onChange:x=>h(x.target.value),disabled:s,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— none —"}),t.map(x=>o.jsx("option",{value:x.id,children:x.name},x.id))]}):o.jsx(ce,{id:"te-profile","aria-label":"template default profile",placeholder:"profile-id (optional)",value:u,onChange:x=>h(x.target.value),disabled:s,className:"min-w-48"})]})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>o.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":d===x,onClick:()=>f(x),className:U("px-4 py-2 text-sm font-medium capitalize transition-colors",d===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:d==="edit"?o.jsx("textarea",{"aria-label":"template content",value:a,onChange:x=>c(x.target.value),disabled:s,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Agent instructions - -...`}):o.jsx("div",{className:U("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:a.trim()?o.jsx(gS,{remarkPlugins:[FS],children:a}):o.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:r,disabled:s,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save template",disabled:!p,loading:s,children:"Save"})]})]})]})}function Ji(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function yO(){const{template:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{l(!0),s(null);try{const f=await e.listTemplates();n(f)}catch(f){s(Ji(f))}finally{l(!1)}},[e]);g.useEffect(()=>{a()},[a]);const c=g.useCallback(async f=>{l(!0),s(null);try{const p=await e.createTemplate(f);n(m=>[...m,p])}catch(p){s(Ji(p))}finally{l(!1)}},[e]),u=g.useCallback(async(f,p)=>{l(!0),s(null);try{const m=await e.updateTemplate(f,p);n(x=>x.map(w=>w.id===f?m:w))}catch(m){s(Ji(m))}finally{l(!1)}},[e]),h=g.useCallback(async f=>{l(!0),s(null);try{await e.deleteTemplate(f),n(p=>p.filter(m=>m.id!==f))}catch(p){s(Ji(p))}finally{l(!1)}},[e]),d=g.useCallback(async(f,p,m)=>{l(!0),s(null);try{await e.createAgentFromTemplate(f,p,m)}catch(x){s(Ji(x))}finally{l(!1)}},[e]);return{templates:t,error:r,busy:i,refresh:a,createTemplate:c,updateTemplate:u,deleteTemplate:h,createAgentFromTemplate:d}}function $S({projectId:e}){const t=yO(),{profile:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(!1),[a,c]=g.useState(null),[u,h]=g.useState(!1);async function d(p){if(!i){try{const m=await n.listProfiles();s(m)}catch{}l(!0)}c(p)}async function f(p,m,x){if(a){h(!0);try{a.mode==="create"?await t.createTemplate({name:p,content:m,defaultProfileId:x}):await t.updateTemplate(a.template.id,m),c(null)}finally{h(!1)}}}return o.jsxs(o.Fragment,{children:[a!==null&&o.jsx(_O,{template:a.mode==="edit"?a.template:null,profiles:r,onSave:f,onClose:()=>c(null),busy:u}),o.jsxs(ke,{title:"Templates",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Templates"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Me,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create template",disabled:t.busy,onClick:()=>void d({mode:"create"}),children:"New template"})]})]}),o.jsx("div",{className:"p-4",children:t.templates.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No templates yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.templates.map(p=>o.jsx("li",{className:"flex flex-col gap-2 py-3 first:pt-0 last:pb-0",children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"font-medium text-content",children:p.name}),o.jsxs("span",{className:"text-xs text-muted",children:["v",p.version]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit ${p.name}`,disabled:t.busy,onClick:()=>void d({mode:"edit",template:p}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"primary","aria-label":`create agent from ${p.name}`,disabled:t.busy,onClick:()=>void t.createAgentFromTemplate(e,p.id),children:"Create agent"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete template ${p.name}`,disabled:t.busy,onClick:()=>void t.deleteTemplate(p.id),className:"text-danger hover:text-danger",children:"Delete"})]})]})},p.id))})})]})]})}function bO({skill:e,onSave:t,onClose:n,busy:r=!1}){const[s,i]=g.useState(e?.name??""),[l,a]=g.useState(e?.contentMd??""),[c,u]=g.useState(e?.scope??"project"),[h,d]=g.useState("edit"),f=e!=null,p=s.trim().length>0&&l.trim().length>0&&!r;async function m(x){x.preventDefault(),p&&await t(s.trim(),l,c)}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"skill editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:f?`Edit skill — ${e.name}`:"New skill"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close skill editor",onClick:n,disabled:r,children:"✕"})]}),o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"se-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"se-name","aria-label":"skill name",placeholder:"My skill",value:s,onChange:x=>i(x.target.value),disabled:r,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"se-scope",className:"text-xs font-medium text-muted",children:"Scope"}),o.jsxs("select",{id:"se-scope","aria-label":"skill scope",value:c,onChange:x=>u(x.target.value),disabled:r||f,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"project",children:"Project"}),o.jsx("option",{value:"global",children:"Global"})]})]})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>o.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":h===x,onClick:()=>d(x),className:U("px-4 py-2 text-sm font-medium capitalize transition-colors",h===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:h==="edit"?o.jsx("textarea",{"aria-label":"skill content",value:l,onChange:x=>a(x.target.value),disabled:r,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Skill workflow - -...`}):o.jsx("div",{className:U("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:l.trim()?o.jsx(gS,{remarkPlugins:[FS],children:l}):o.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:n,disabled:r,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save skill",disabled:!p,loading:r,children:"Save"})]})]})]})}function Fo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function wO(e){const{skill:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState(!1),h=g.useCallback(async()=>{if(e){u(!0),a(null);try{const[x,w]=await Promise.all([t.listSkills(e,"global"),t.listSkills(e,"project")]);r(x),i(w)}catch(x){a(Fo(x))}finally{u(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=x=>x==="global"?r:i,f=g.useCallback(async x=>{u(!0),a(null);try{const w=await t.createSkill({...x,projectId:e});d(x.scope)(v=>[...v,w])}catch(w){a(Fo(w))}finally{u(!1)}},[t,e]),p=g.useCallback(async(x,w,v)=>{u(!0),a(null);try{const _=await t.updateSkill(e,x,w,v);d(x)(y=>y.map(b=>b.id===w?_:b))}catch(_){a(Fo(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async(x,w)=>{u(!0),a(null);try{await t.deleteSkill(e,x,w),d(x)(v=>v.filter(_=>_.id!==w))}catch(v){a(Fo(v))}finally{u(!1)}},[t,e]);return{globalSkills:n,projectSkills:s,error:l,busy:c,refresh:h,createSkill:f,updateSkill:p,deleteSkill:m}}function WS({projectId:e}){const t=wO(e),[n,r]=g.useState(null),[s,i]=g.useState(!1);async function l(c,u,h){if(n){i(!0);try{n.mode==="create"?await t.createSkill({name:c,content:u,scope:h}):await t.updateSkill(n.skill.scope,n.skill.id,u),r(null)}finally{i(!1)}}}function a(c,u){return o.jsx("div",{className:"p-4",children:u.length===0?o.jsxs("p",{className:"text-sm text-muted",children:["No ",c," skills yet."]}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.map(h=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[o.jsx("span",{className:"min-w-0 font-medium text-content",children:h.name}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit skill ${h.name}`,disabled:t.busy,onClick:()=>r({mode:"edit",skill:h}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete skill ${h.name}`,disabled:t.busy,onClick:()=>void t.deleteSkill(h.scope,h.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},h.id))})})}return o.jsxs(o.Fragment,{children:[n!==null&&o.jsx(bO,{skill:n.mode==="edit"?n.skill:null,onSave:l,onClose:()=>r(null),busy:s}),o.jsxs(ke,{title:"Skills",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Skills"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Me,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create skill",disabled:t.busy,onClick:()=>r({mode:"create"}),children:"New skill"})]})]}),o.jsx("div",{className:"border-b border-border px-4 pt-3",children:o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Project"})}),a("project",t.projectSkills),o.jsx("div",{className:"border-y border-border px-4 pt-3",children:o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Global"})}),a("global",t.globalSkills)]})]})}function Zu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function HS(){const{embedder:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{const[p,m]=await Promise.all([e.listEmbedderProfiles(),e.describeEmbedderEngines()]);n(p),s(m)}catch(p){l(Zu(p))}finally{c(!1)}},[e]);g.useEffect(()=>{u()},[u]);const h=g.useCallback(async p=>{c(!0),l(null);try{await e.saveEmbedderProfile(p),await u()}catch(m){l(Zu(m)),c(!1)}},[e,u]),d=g.useCallback(async p=>{c(!0),l(null);try{await e.deleteEmbedderProfile(p),await u()}catch(m){l(Zu(m)),c(!1)}},[e,u]),f=t.find(p=>p.strategy!=="none")??null;return{profiles:t,engines:r,active:f,error:i,busy:a,refresh:u,saveProfile:h,deleteProfile:d}}const US="http://localhost:11434/api/embeddings",qS="https://api.openai.com/v1/embeddings",ed=[{strategy:"none",key:"none",label:"None (naïve recall)"},{strategy:"localOnnx",key:"localOnnx",label:"Local ONNX"},{strategy:"localServer",key:"localServer",label:"Ollama (local server)"},{strategy:"api",key:"api",label:"API"},{strategy:"api",key:"custom",label:"Custom"}],Hs={id:"",name:"",model:"",endpoint:"",apiKeyEnv:"",dimension:"",onnxEngineId:""};function SO(e,t,n){if(n)return{id:n.id,name:n.name,model:n.model??"",endpoint:n.endpoint??"",apiKeyEnv:n.apiKeyEnv??"",dimension:String(n.dimension),onnxEngineId:e==="localOnnx"?t.find(r=>r.id===n.model)?.id??t[0]?.id??"":""};switch(e){case"localOnnx":{const r=t.find(s=>s.recommended)??t[0];return{...Hs,id:"onnx-local",name:r?.displayName??"Local ONNX",model:r?.id??"",dimension:r?String(r.dimension):"",onnxEngineId:r?.id??""}}case"localServer":return{...Hs,id:"ollama",name:"Ollama",endpoint:US,model:"nomic-embed-text",dimension:"768"};case"api":return{...Hs,id:"api",name:"API embedder",endpoint:qS,apiKeyEnv:"OPENAI_API_KEY",model:"text-embedding-3-small",dimension:"1536"};case"custom":return{...Hs,id:"custom",name:"Custom embedder"};default:return{...Hs}}}function kO(e,t){switch(e){case"none":return!0;case"localOnnx":return t.vectorOnnxEnabled;case"localServer":case"api":return t.vectorHttpEnabled}}function VS(){const e=HS(),[t,n]=g.useState("localOnnx"),[r,s]=g.useState(Hs),i=e.engines?.recommendedOnnx??[],l={vectorOnnxEnabled:e.engines?.vectorOnnxEnabled??!1,vectorHttpEnabled:e.engines?.vectorHttpEnabled??!1};g.useEffect(()=>{if(!e.engines)return;const _=ed.find(b=>b.key===t),y=e.active&&_&&e.active.strategy===_.strategy?e.active:null;s(SO(t,e.engines.recommendedOnnx,y))},[e.engines,e.active,t]);const c=ed.find(_=>_.key===t).strategy;function u(_){s(y=>({...y,..._}))}function h(_){const y=i.find(b=>b.id===_);u({onnxEngineId:_,model:y?.id??_,dimension:y?String(y.dimension):r.dimension})}const d=Number.parseInt(r.dimension,10),f=g.useMemo(()=>c==="none"?{ok:!0}:r.id.trim()?r.name.trim()?!Number.isFinite(d)||d<=0?{ok:!1,msg:"Dimension must be a positive number."}:(c==="localServer"||c==="api")&&!r.endpoint.trim()?{ok:!1,msg:"Endpoint is required."}:{ok:!0}:{ok:!1,msg:"Name is required."}:{ok:!1,msg:"Id is required."},[c,r,d]);function p(){return{id:r.id.trim(),name:r.name.trim(),strategy:c,dimension:d,model:r.model.trim()||void 0,endpoint:(c==="localServer"||c==="api")&&r.endpoint.trim()||void 0,apiKeyEnv:c==="api"&&r.apiKeyEnv.trim()||void 0}}async function m(){f.ok&&await e.saveProfile(p())}async function x(){for(const _ of e.profiles)await e.deleteProfile(_.id);n("none")}const w=U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),v=e.active!==null;return o.jsxs(ke,{title:"Memory / Embedder",className:"flex flex-col gap-0",children:[e.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[o.jsx("p",{className:"rounded-md border border-border bg-raised px-3 py-2 text-xs text-muted","data-testid":"embedder-restart-note",children:"The embedder change takes effect at the next app start."}),o.jsxs("p",{className:"text-xs text-faint","data-testid":"embedder-active",children:["Current:"," ",v?o.jsxs("span",{className:"text-content",children:["Vector — ",e.active.strategy,e.active.model?` ${e.active.model}`:""]}):o.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),o.jsxs("fieldset",{className:"flex flex-col gap-2","aria-label":"embedder strategy",children:[o.jsx("legend",{className:"mb-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Strategy"}),ed.map(_=>{const y=kO(_.strategy,l),b=_.key==="localOnnx";return o.jsxs("label",{className:U("flex items-center gap-2 rounded-md border px-3 py-2 text-sm",t===_.key?"border-primary bg-raised":"border-border",!y&&"opacity-50"),"data-testid":`embedder-strategy-${_.key}`,children:[o.jsx("input",{type:"radio",name:"embedder-strategy",value:_.key,checked:t===_.key,disabled:!y,onChange:()=>n(_.key),"aria-label":_.label}),o.jsx("span",{className:"text-content",children:_.label}),b&&o.jsx("span",{className:"rounded border border-primary/40 bg-primary/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-primary",children:"Recommended"}),!y&&o.jsx("span",{className:"text-[11px] text-faint",children:"not available in this build"})]},_.key)})]}),c!=="none"&&o.jsxs("div",{className:"flex flex-col gap-3",children:[c==="localOnnx"&&o.jsx(qt,{label:"ONNX model",children:({id:_})=>o.jsx("select",{id:_,"aria-label":"onnx model",className:w,value:r.onnxEngineId,disabled:e.busy,onChange:y=>h(y.target.value),children:i.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName,y.recommended?" — recommended":""," (dim"," ",y.dimension,", ~",y.approxSizeMb," MB)"]},y.id))})}),(c==="localServer"||c==="api")&&o.jsx(qt,{label:"Endpoint",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"endpoint",placeholder:c==="localServer"?US:qS,value:r.endpoint,disabled:e.busy,onChange:y=>u({endpoint:y.target.value})})}),c==="api"&&o.jsx(qt,{label:"API key environment variable",hint:"Name of the env var holding the key — never the key itself.",children:({id:_,describedBy:y})=>o.jsx(ce,{id:_,"aria-label":"api key env var",placeholder:"OPENAI_API_KEY","aria-describedby":y,value:r.apiKeyEnv,disabled:e.busy,onChange:b=>u({apiKeyEnv:b.target.value})})}),c!=="localOnnx"&&o.jsx(qt,{label:"Model",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"model",placeholder:"model name",value:r.model,disabled:e.busy,onChange:y=>u({model:y.target.value})})}),o.jsx(qt,{label:"Dimension",error:f.ok?void 0:f.msg,children:({id:_,describedBy:y})=>o.jsx(ce,{id:_,"aria-label":"dimension",type:"number",min:1,value:r.dimension,"aria-describedby":y,disabled:e.busy,onChange:b=>u({dimension:b.target.value})})}),o.jsx(qt,{label:"Profile id",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"profile id",placeholder:"my-embedder",value:r.id,disabled:e.busy,onChange:y=>u({id:y.target.value})})}),o.jsx(qt,{label:"Profile name",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"profile name",placeholder:"My embedder",value:r.name,disabled:e.busy,onChange:y=>u({name:y.target.value})})})]}),o.jsxs("div",{className:"flex items-center gap-2 border-t border-border pt-3",children:[e.busy&&o.jsx(Me,{size:14}),c!=="none"&&o.jsx(M,{type:"button",variant:"primary","aria-label":"save embedder",disabled:e.busy||!f.ok,onClick:()=>void m(),children:"Save"}),o.jsx(M,{type:"button","aria-label":"back to none",disabled:e.busy,onClick:()=>void x(),children:"Back to None"})]})]})]})}const CO=["user","feedback","project","reference"];function jO({entry:e,loadContent:t,resolveLinks:n,onCreate:r,onUpdate:s,onClose:i,busy:l=!1}){const a=e!=null,[c,u]=g.useState(e?.title??""),[h,d]=g.useState(e?.hook??""),[f,p]=g.useState(e?.type??"project"),[m,x]=g.useState(""),[w,v]=g.useState([]);g.useEffect(()=>{if(!e)return;let C=!1;return(async()=>{try{if(t){const S=await t(e.slug);C||x(S)}if(n){const S=await n(e.slug);C||v(S)}}catch{}})(),()=>{C=!0}},[e,t,n]);const _=h.trim().length>0&&m.trim().length>0&&!l&&(a||c.trim().length>0);async function y(C){C.preventDefault(),_&&(a?await s(e.slug,h.trim(),f,m):await r(c.trim(),h.trim(),f,m))}const b=U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"memory editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:a?`Edit note — ${e.title}`:"New note"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close memory editor",onClick:i,disabled:l,children:"✕"})]}),o.jsxs("form",{onSubmit:C=>void y(C),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a?o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Slug"}),o.jsx("code",{className:"truncate rounded-md border border-border bg-raised px-3 py-2 text-sm text-muted",children:e.slug})]}):o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"me-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"me-name","aria-label":"memory name",placeholder:"My note",value:c,onChange:C=>u(C.target.value),disabled:l,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"me-type",className:"text-xs font-medium text-muted",children:"Type"}),o.jsx("select",{id:"me-type","aria-label":"memory type",value:f,onChange:C=>p(C.target.value),disabled:l,className:b,children:CO.map(C=>o.jsx("option",{value:C,children:C},C))})]})]}),o.jsxs("div",{className:"flex shrink-0 flex-col gap-1 border-b border-border px-4 py-3",children:[o.jsx("label",{htmlFor:"me-description",className:"text-xs font-medium text-muted",children:"Description"}),o.jsx(ce,{id:"me-description","aria-label":"memory description",placeholder:"One-line hook",value:h,onChange:C=>d(C.target.value),disabled:l})]}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:[o.jsx("label",{htmlFor:"me-content",className:"mb-1 text-xs font-medium text-muted",children:"Content"}),o.jsx("textarea",{id:"me-content","aria-label":"memory content",value:m,onChange:C=>x(C.target.value),disabled:l,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Note - -Use [[other-slug]] to link…`}),a&&o.jsxs("div",{className:"mt-3 shrink-0",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Links"}),w.length===0?o.jsx("p",{className:"mt-1 text-sm text-muted",children:"No resolved links."}):o.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:w.map(C=>o.jsx("li",{className:"rounded-md border border-border bg-raised px-2 py-0.5 text-xs text-muted",children:C},C))})]})]}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:i,disabled:l,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save note",disabled:!_,loading:l,children:"Save"})]})]})]})}function $o(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NO(e){const{memory:t,system:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{if(e){c(!0),l(null);try{s(await t.readIndex(e))}catch(m){l($o(m))}finally{c(!1)}}},[t,e]);g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let m,x=!1;return n.onDomainEvent(w=>{w.type==="memorySaved"&&u()}).then(w=>{x?w():m=w}),()=>{x=!0,m?.()}},[u,n]);const h=g.useCallback(async m=>{c(!0),l(null);try{await t.createMemory({...m,projectId:e}),await u()}catch(x){l($o(x)),c(!1)}},[t,e,u]),d=g.useCallback(async(m,x,w,v)=>{c(!0),l(null);try{await t.updateMemory(e,m,x,w,v),await u()}catch(_){l($o(_)),c(!1)}},[t,e,u]),f=g.useCallback(async m=>{c(!0),l(null);try{await t.deleteMemory(e,m),await u()}catch(x){l($o(x)),c(!1)}},[t,e,u]),p=g.useCallback(m=>t.resolveLinks(e,m),[t,e]);return{entries:r,error:i,busy:a,refresh:u,createMemory:h,updateMemory:d,deleteMemory:f,resolveLinks:p}}function KS({projectId:e}){const t=NO(e),n=HS(),{memory:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState(!1),c=g.useCallback(async d=>(await r.getMemory(e,d)).content,[r,e]);async function u(d,f,p,m){a(!0);try{await t.createMemory({name:d,description:f,type:p,content:m}),i(null)}finally{a(!1)}}async function h(d,f,p,m){a(!0);try{await t.updateMemory(d,f,p,m),i(null)}finally{a(!1)}}return o.jsxs(o.Fragment,{children:[s!==null&&o.jsx(jO,{entry:s.mode==="edit"?s.entry:null,loadContent:c,resolveLinks:t.resolveLinks,onCreate:u,onUpdate:h,onClose:()=>i(null),busy:l}),o.jsxs(ke,{title:"Memory",className:"flex flex-col gap-0",children:[o.jsxs("p",{className:"border-b border-border px-4 py-2 text-xs text-faint","data-testid":"memory-tier",children:["Tier:"," ",n.active?o.jsxs("span",{className:"text-content",children:["Vector — ",n.active.strategy,n.active.model?` ${n.active.model}`:""]}):o.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Notes"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Me,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create memory",disabled:t.busy,onClick:()=>i({mode:"create"}),children:"New note"})]})]}),o.jsx("div",{className:"p-4",children:t.entries.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No memory notes yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.entries.map(d=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"min-w-0 truncate font-medium text-content",children:d.title}),o.jsx("span",{className:"shrink-0 rounded border border-border bg-raised px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted",children:d.type})]}),o.jsx("span",{className:"truncate text-xs text-muted",children:d.hook})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit memory ${d.title}`,disabled:t.busy,onClick:()=>i({mode:"edit",entry:d}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete memory ${d.title}`,disabled:t.busy,onClick:()=>void t.deleteMemory(d.slug),className:"text-danger hover:text-danger",children:"Delete"})]})]},d.slug))})})]})]})}const Nv=[{id:"readProject",label:"Lecture projet",tools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read"]},{id:"readTickets",label:"Lecture tickets",tools:["idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"]},{id:"delegation",label:"Délégation agents",tools:["idea_ask_agent","idea_launch_agent","idea_stop_agent"]},{id:"contextMemory",label:"Contexte et mémoire",tools:["idea_update_context","idea_context_propose","idea_memory_write"]},{id:"tickets",label:"Tickets",tools:["idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]},{id:"work",label:"Travail et exécution",tools:["idea_run_in_background","idea_workstate_set"]},{id:"skills",label:"Skills",tools:["idea_create_skill"]}],EO={idea_list_agents:"Lister les agents",idea_context_read:"Lire le contexte d'un agent",idea_memory_read:"Lire la mémoire projet",idea_skill_read:"Lire un skill",idea_workstate_read:"Lire l'état de travail",idea_ticket_read:"Lire un ticket",idea_ticket_list:"Lister les tickets",idea_ticket_read_carnet:"Lire le carnet d'un ticket",idea_sprint_list:"Lister les sprints",idea_ask_agent:"Déléguer à un agent",idea_launch_agent:"Lancer un agent",idea_stop_agent:"Arrêter un agent",idea_update_context:"Modifier le contexte d'un agent",idea_context_propose:"Proposer un contexte",idea_memory_write:"Écrire la mémoire projet",idea_workstate_set:"Écrire l'état de travail",idea_create_skill:"Créer un skill",idea_ticket_create:"Créer un ticket",idea_ticket_update:"Modifier un ticket",idea_ticket_update_status:"Modifier le statut d'un ticket",idea_ticket_update_priority:"Modifier la priorité d'un ticket",idea_ticket_update_carnet:"Modifier le carnet d'un ticket",idea_ticket_link:"Lier des tickets",idea_ticket_unlink:"Délier des tickets",idea_run_in_background:"Exécuter une commande en arrière-plan"};function PO(e){return EO[e]??e}function Wo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function AO(e){const{permission:t}=fe(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[l,a]=g.useState(!1),[c,u]=g.useState(null),h=g.useCallback(async()=>{if(t){i(!0),u(null);try{r(await t.getMcpToolPermissions(e))}catch(m){u(Wo(m))}finally{i(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=g.useCallback(async m=>{if(t){a(!0),u(null);try{r(await t.updateProjectMcpToolPermissions(e,m))}catch(x){throw u(Wo(x)),x}finally{a(!1)}}},[t,e]),f=g.useCallback(async(m,x)=>{if(t){a(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,x))}catch(w){throw u(Wo(w)),w}finally{a(!1)}}},[t,e]),p=g.useCallback(async m=>{if(t){a(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,null))}catch(x){throw u(Wo(x)),x}finally{a(!1)}}},[t,e]);return{doc:n,loading:s,busy:l,error:c,refresh:h,saveProjectDefault:d,saveAgentOverride:f,resetAgentOverride:p}}const TO=new Set(["readProject","readTickets"]);function LO(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function DO(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(r=>n.has(r))}function RO({projectId:e,agents:t}){const n=AO(e),[r,s]=g.useState({type:"project"}),i=g.useRef(!1);function l(u){i.current&&!window.confirm("Des modifications non enregistrées seront perdues. Continuer ?")||(i.current=!1,s(u))}if(n.loading&&!n.doc)return o.jsxs("div",{"data-testid":"mcp-tool-permissions-skeleton",className:"flex flex-col gap-3 p-4",children:[o.jsx("div",{className:"h-4 w-40 animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-32 w-full animate-pulse rounded bg-raised"})]});if(n.error&&!n.doc)return o.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),o.jsx(M,{size:"sm",onClick:()=>void n.refresh(),children:"Réessayer"})]});if(!n.doc)return null;const a=n.doc,c=r.type==="agent"?a.agents.find(u=>u.agentId===r.agentId)??null:null;return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4 md:flex-row",children:[o.jsxs("nav",{"aria-label":"cibles des permissions MCP",className:"flex w-full shrink-0 flex-col gap-2 md:w-56",children:[o.jsxs("button",{type:"button","aria-pressed":r.type==="project",onClick:()=>l({type:"project"}),className:U("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",r.type==="project"?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsx("span",{className:"font-medium text-content",children:"Défaut projet"}),o.jsx("span",{className:"text-xs text-muted",children:a.projectDefault?"Personnalisé":"Lecture seule"})]}),o.jsx("h4",{className:"mt-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun agent dans ce projet."}):o.jsx("ul",{className:"flex flex-col gap-1.5",children:t.map(u=>{const h=a.agents.some(f=>f.agentId===u.id),d=r.type==="agent"&&r.agentId===u.id;return o.jsx("li",{children:o.jsxs("button",{type:"button","aria-pressed":d,onClick:()=>l({type:"agent",agentId:u.id,agentName:u.name}),className:U("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",d?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsx("span",{className:"truncate font-medium text-content",children:u.name}),o.jsx("span",{className:U("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",h?"bg-warning/15 text-warning":"bg-primary/10 text-muted"),children:h?"Override":"Hérité"})]})},u.id)})})]}),o.jsx("div",{className:"min-w-0 flex-1",children:r.type==="project"?o.jsx(Ev,{targetKind:"project",title:"Tools MCP IdeA — Défaut projet",catalogue:a.catalogue,storedAllowed:a.projectDefault?.allowedTools??null,comparisonBaseline:a.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{i.current=u},onSaveProjectDefault:async u=>{await n.saveProjectDefault({allowedTools:u})}},"project"):o.jsx(Ev,{targetKind:"agent",title:`Tools MCP IdeA — ${r.agentName}`,catalogue:a.catalogue,storedAllowed:c?.policy.allowedTools??null,comparisonBaseline:a.projectDefault?.allowedTools??a.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{i.current=u},onSaveAgentOverride:async u=>{await n.saveAgentOverride(r.agentId,{allowedTools:u})},onResetOverride:async()=>{await n.resetAgentOverride(r.agentId)}},r.agentId)})]})}function Ev({targetKind:e,title:t,catalogue:n,storedAllowed:r,comparisonBaseline:s,busy:i,onDirtyChange:l,onSaveProjectDefault:a,onSaveAgentOverride:c,onResetOverride:u}){const h=r??s,[d,f]=g.useState(e==="project"||r!=null),[p,m]=g.useState(r!=null),[x,w]=g.useState(h),[v,_]=g.useState(h),[y,b]=g.useState(!1),[C,S]=g.useState(!1),[N,L]=g.useState(null),[A,k]=g.useState(()=>Object.fromEntries(Nv.map(re=>[re.id,TO.has(re.id)?e==="project":!0]))),D=e==="project"||d,R=D?x:s,E=D&&!DO(x,v);g.useEffect(()=>{l(E)},[E]),g.useEffect(()=>{if(!C)return;const re=window.setTimeout(()=>S(!1),2e3);return()=>window.clearTimeout(re)},[C]);const O=n.readOnlyTools.filter(re=>R.includes(re)).length,I=n.writeActionTools.filter(re=>R.includes(re)).length,W=g.useMemo(()=>new Set([...n.readOnlyTools,...n.writeActionTools]),[n]),G=g.useMemo(()=>Array.from(new Set([...R,...s])).filter(re=>!W.has(re)),[R,s,W]);function P(re){L(null),w(ee=>LO(ee,re))}function z(re){k(ee=>({...ee,[re]:!ee[re]}))}function j(){f(!0),w(s),_(s)}function se(){w(v),b(!1),L(null)}async function q(){if(L(null),e==="project"){if(x.some(ee=>n.writeActionTools.includes(ee)&&!v.includes(ee))&&!y){b(!0);return}b(!1);try{await a?.(x),_(x),S(!0)}catch(ee){L(td(ee))}return}try{await c?.(x),_(x),m(!0),S(!0)}catch(re){L(td(re))}}async function T(){L(null);try{await u?.(),f(!1),m(!1),w(s),_(s),S(!0)}catch(re){L(td(re))}}return o.jsx(ke,{title:t,className:"flex h-full flex-col",flush:!0,children:o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e==="agent"&&o.jsx("p",{className:"text-xs text-muted",children:d?"Override personnalisé":"Hérite du défaut projet"}),e==="agent"&&!d&&o.jsx(M,{size:"sm",onClick:j,disabled:i,children:"Créer un override"}),o.jsxs("div",{children:[o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Résumé effectif"}),o.jsxs("p",{className:"text-sm text-content",children:[O," lecture autorisés · ",I," écriture autorisé",I>1?"s":""]})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Détail des tools"}),Nv.map(re=>o.jsx(Pv,{group:re,expanded:A[re.id]??!0,onToggle:()=>z(re.id),catalogue:n,editable:D,targetKind:e,draftSet:x,displaySet:R,comparisonBaseline:s,onToggleTool:P},re.id)),G.length>0&&o.jsx(Pv,{group:{id:"unknown",label:"Tools inconnus",tools:G},expanded:A.unknown??!0,onToggle:()=>z("unknown"),catalogue:n,editable:!1,targetKind:e,draftSet:x,displaySet:R,comparisonBaseline:s,onToggleTool:P,unknown:!0})]}),y&&o.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning",children:[o.jsx("p",{children:"Ce tool sera autorisé pour tous les agents sans override. Confirmer cette modification ?"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>b(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"primary",onClick:()=>void q(),children:"Confirmer"})]})]}),N&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:N}),C&&o.jsx("p",{role:"status",className:"text-sm text-success",children:"Permissions enregistrées"}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[o.jsx("div",{children:E&&o.jsx("span",{className:"text-xs text-warning",children:"Modifications non enregistrées"})}),o.jsxs("div",{className:"flex gap-2",children:[e==="agent"&&p&&o.jsx(M,{size:"sm",variant:"ghost",disabled:i,onClick:()=>void T(),children:"Réinitialiser l'override"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:i||!E,onClick:se,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"primary",disabled:i||!D||!E,loading:i&&E,onClick:()=>void q(),children:"Enregistrer"})]})]})]})})}function Pv({group:e,expanded:t,onToggle:n,catalogue:r,editable:s,targetKind:i,displaySet:l,comparisonBaseline:a,onToggleTool:c,unknown:u}){const h=e.tools.filter(f=>l.includes(f)).length,d=e.tools.length;return o.jsxs("div",{className:"rounded-md border border-border",children:[o.jsxs("button",{type:"button","aria-expanded":t,"aria-label":`${e.label}, ${h} sur ${d} autorisé${d>1?"s":""}`,onClick:n,className:"flex min-h-[32px] w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-raised",children:[o.jsx("span",{className:"font-medium text-content",children:e.label}),o.jsxs("span",{className:"text-xs text-muted",children:[h,"/",d," autorisés"]})]}),t&&o.jsx("ul",{className:"flex flex-col divide-y divide-border border-t border-border",children:e.tools.map(f=>o.jsx(OO,{tool:f,isRead:r.readOnlyTools.includes(f),unknown:u,editable:s,checked:l.includes(f),status:MO(f,s,i,l,a,u),onToggle:()=>c(f)},f))})]})}function MO(e,t,n,r,s,i){if(i)return"unknown";if(n==="agent"&&!t)return"inherited";if(n==="agent"&&t){const l=r.includes(e),a=s.includes(e);return l&&!a?"added":!l&&a?"removed":l?"allowed":"denied"}return r.includes(e)?"allowed":"denied"}const IO={allowed:"Autorisé",denied:"Refusé",inherited:"Hérité",added:"Ajouté",removed:"Retiré",unknown:"Inconnu"};function OO({tool:e,isRead:t,unknown:n,editable:r,checked:s,status:i,onToggle:l}){const a=PO(e),c=`mcp-tool-${e}`;return o.jsxs("li",{className:"flex min-h-[32px] items-center gap-2 px-3 py-1.5",children:[o.jsx("input",{id:c,type:"checkbox",checked:s,disabled:!r||n,onChange:l,"aria-label":`${a}, ${e}`}),o.jsxs("label",{htmlFor:c,className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"font-mono text-xs text-content",children:e}),!n&&o.jsx("span",{className:U("rounded-full px-1.5 py-0.5 text-[10px] font-medium",t?"bg-primary/10 text-primary":"bg-warning/15 text-warning"),children:t?"Lecture":"Écriture"})]}),o.jsx("span",{className:"text-xs text-muted",children:a})]}),o.jsx("span",{className:U("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",i==="allowed"||i==="added"?"bg-success/15 text-success":i==="denied"||i==="removed"?"bg-danger/10 text-muted":i==="unknown"?"bg-danger/15 text-danger":"bg-primary/10 text-muted"),children:IO[i]})]})}function td(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Av={fallback:"ask",read:"none",write:"none",delete:"none",executeBash:"none"},GS=["read","write","delete","executeBash"];function ts(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function YS(e){if(!e)return{...Av};const t={...Av,fallback:e.fallback};for(const n of GS)t[n]=BO(e.rules,n);return t}function BO(e,t){const n=e.filter(r=>r.capability===t);return n.some(r=>r.effect==="deny")?"deny":n.some(r=>r.effect==="allow")?"allow":"none"}function Tv(e){const t=[];for(const n of GS){const r=e[n];r!=="none"&&t.push(zO(n,r))}return{fallback:e.fallback,rules:t}}function zO(e,t){return e==="executeBash"?{capability:e,effect:t,commands:[]}:{capability:e,effect:t,paths:["**"]}}function Ho(e){return e?e.rules.some(t=>{if(t.capability==="executeBash")return(t.commands??[]).length>0;const n=t.paths??[];return n.length!==1||n[0]!=="**"}):!1}function FO(e){const{agent:t,permission:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(null),[u,h]=g.useState({}),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useCallback(async()=>{f(!0),m(null);try{const[L,A,k]=await Promise.all([t.listAgents(e),n.getProjectPermissions(e),n.getProjectSystemPermissions(e)]),D=await Promise.all(L.map(async R=>{try{return[R.id,await n.resolveAgentSystemPermissions(e,R.id)]}catch{return[R.id,null]}}));s(L),l(A),c(k),h(Object.fromEntries(D.filter(R=>R[1]!==null)))}catch(L){m(ts(L))}finally{f(!1)}},[t,n,e]);g.useEffect(()=>{x()},[x]);const w=g.useMemo(()=>{const L=new Map((i?.agents??[]).map(k=>[k.agentId,k.permissions])),A=new Map((a?.agents??[]).map(k=>[k.agentId,k.permissions]));return r.map(k=>({agent:k,override:L.get(k.id)??null,systemOverride:A.get(k.id)??null,resolvedSystem:u[k.id]??null}))},[r,i,a,u]),v=g.useMemo(()=>YS(i?.projectDefaults??null),[i]),_=g.useCallback(async L=>{f(!0),m(null);try{l(await n.updateProjectPermissions(e,Tv(L)))}catch(A){m(ts(A))}finally{f(!1)}},[n,e]),y=g.useCallback(async()=>{f(!0),m(null);try{l(await n.updateProjectPermissions(e,null))}catch(L){m(ts(L))}finally{f(!1)}},[n,e]),b=g.useCallback(async(L,A)=>{f(!0),m(null);try{l(await n.updateAgentPermissions(e,L,Tv(A)))}catch(k){m(ts(k))}finally{f(!1)}},[n,e]),C=g.useCallback(async L=>{f(!0),m(null);try{l(await n.updateAgentPermissions(e,L,null))}catch(A){m(ts(A))}finally{f(!1)}},[n,e]),S=g.useCallback(async L=>{f(!0),m(null);try{const A=await n.updateProjectSystemPermissions(e,L);c(A),await x()}catch(A){m(ts(A))}finally{f(!1)}},[n,e,x]),N=g.useCallback(async(L,A)=>{f(!0),m(null);try{const k=await n.updateAgentSystemPermissions(e,L,A);c(k),await x()}catch(k){m(ts(k))}finally{f(!1)}},[n,e,x]);return{agents:r,rows:w,document:i,systemDocument:a,projectDraft:v,busy:d,error:p,refresh:x,saveProjectDefaults:_,clearProjectDefaults:y,saveAgentOverride:b,clearAgentOverride:C,saveProjectSystemPermissions:S,saveAgentSystemPermissions:N}}const zs=[{id:"system",label:"Système"},{id:"mcpTools",label:"Tools MCP IdeA"}],$O=[{key:"read",label:"Read"},{key:"write",label:"Write"},{key:"delete",label:"Delete"},{key:"executeBash",label:"Bash"}],WO={ask:"Ask",allow:"Allow",deny:"Deny"},nd={allow:"Autorisé",deny:"Interdit",ask:"Demande"};function XS({projectId:e}){const t=FO(e),[n,r]=g.useState({type:"project"}),[s,i]=g.useState("system"),l=n.type==="agent"?t.rows.find(w=>w.agent.id===n.agentId)??null:null,a=l?.override??t.document?.projectDefaults??null,c=n.type==="project"?t.systemDocument?.projectDefault??null:l?.systemOverride??t.systemDocument?.projectDefault??null,u=n.type==="project"?t.rows[0]?.resolvedSystem??null:l?.resolvedSystem??null,h=n.type==="project"?t.projectDraft:YS(l?.override??t.document?.projectDefaults??null),d=n.type==="project"?Ho(t.document?.projectDefaults):Ho(l?.override),f=t.document?.projectDefaults!=null;async function p(w){n.type==="project"?await t.saveProjectDefaults(w):await t.saveAgentOverride(n.agentId,w)}async function m(){n.type==="project"?await t.clearProjectDefaults():await t.clearAgentOverride(n.agentId)}async function x(w){n.type==="project"?await t.saveProjectSystemPermissions(w):await t.saveAgentSystemPermissions(n.agentId,w)}return o.jsxs(ke,{title:"Permissions",actions:o.jsx(M,{size:"sm",variant:"ghost",disabled:t.busy,onClick:()=>void t.refresh(),children:"Refresh"}),className:"flex min-h-0 flex-1 flex-col",flush:!0,children:[o.jsx("div",{role:"tablist","aria-label":"Permissions",className:"flex gap-1 border-b border-border px-4 pt-2",children:zs.map(w=>o.jsx("button",{type:"button",role:"tab",id:`permissions-tab-${w.id}`,"aria-selected":s===w.id,"aria-controls":`permissions-tabpanel-${w.id}`,tabIndex:s===w.id?0:-1,onClick:()=>i(w.id),onKeyDown:v=>{if(v.key!=="ArrowRight"&&v.key!=="ArrowLeft")return;v.preventDefault();const _=zs.findIndex(b=>b.id===s),y=v.key==="ArrowRight"?(_+1)%zs.length:(_-1+zs.length)%zs.length;i(zs[y].id)},className:U("min-h-[32px] rounded-t-md border-b-2 px-3 py-1.5 text-sm font-medium transition-colors",s===w.id?"border-primary text-content":"border-transparent text-muted hover:text-content"),children:w.label},w.id))}),t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{role:"tabpanel",id:"permissions-tabpanel-system","aria-labelledby":"permissions-tab-system",hidden:s!=="system",className:"flex flex-col gap-4 p-4",children:[o.jsx(Lv,{title:"Project defaults",subtitle:f?"Configured":"Native CLI behavior",active:n.type==="project",custom:Ho(t.document?.projectDefaults),onSelect:()=>r({type:"project"}),policy:t.document?.projectDefaults??null}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.busy&&o.jsx(Me,{size:14})]}),t.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):o.jsx("ul",{className:"flex flex-col gap-2",children:t.rows.map(w=>{const v=n.type==="agent"&&n.agentId===w.agent.id;return o.jsx("li",{children:o.jsx(Lv,{title:w.agent.name,subtitle:w.override?"Override":"Inherited",active:v,custom:Ho(w.override),onSelect:()=>r({type:"agent",agentId:w.agent.id,agentName:w.agent.name}),policy:w.override})},w.agent.id)})})]}),o.jsx(UO,{title:n.type==="project"?"Project defaults":`Override — ${n.agentName}`,draft:h,sourcePolicy:a,custom:d,canClear:n.type==="project"?t.document?.projectDefaults!=null:l?.override!=null,busy:t.busy,onSave:w=>void p(w),onClear:()=>void m()},n.type==="project"?"project":n.agentId),o.jsx(HO,{title:n.type==="project"?"Réseau — defaults projet":`Réseau — ${n.agentName}`,source:c,resolved:u,inherited:n.type==="agent"&&l?.systemOverride==null?t.systemDocument?.projectDefault??null:null,busy:t.busy,onSave:w=>void x(w)},`network-${n.type==="project"?"project":n.agentId}`)]}),o.jsx("div",{role:"tabpanel",id:"permissions-tabpanel-mcpTools","aria-labelledby":"permissions-tab-mcpTools",hidden:s!=="mcpTools",className:"flex min-h-0 flex-1 flex-col",children:s==="mcpTools"&&o.jsx(RO,{projectId:e,agents:t.agents})})]})}function Lv({title:e,subtitle:t,active:n,custom:r,policy:s,onSelect:i}){return o.jsxs("button",{type:"button",onClick:i,"aria-pressed":n,className:U("flex w-full min-w-0 items-center justify-between gap-3 rounded-md border px-3 py-2 text-left","transition-colors hover:border-border-strong hover:bg-raised",n?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e}),o.jsx("span",{className:"text-xs text-muted",children:t})]}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[r&&o.jsx("span",{className:"rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Custom"}),s&&o.jsx("span",{className:"rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary",children:WO[s.fallback]})]})]})}function HO({title:e,source:t,inherited:n,resolved:r,busy:s,onSave:i}){const l=t?.network??"",[a,c]=g.useState(l);g.useEffect(()=>{c(l)},[l]);const u=r?.control.mode==="readOnly",h=a!==l,d=r?.wanted??t?.network??n?.network??null,f=r?.effective??null,p=r?.runtimeLock.state==="locked",m=r?.runtimeControl.mode==="readOnly",x=r?.runtimeLock.reason??r?.runtimeControl.reason??null,w=r?.runtimeLock.state==="none"&&m;return o.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[o.jsxs("header",{className:"border-b border-border px-3 py-2.5",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-xs text-muted",children:"Politique voulue, état effectif et verrou runtime."})]}),o.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[o.jsxs("div",{className:"grid grid-cols-1 gap-2 text-xs sm:grid-cols-2",children:[o.jsx(Uo,{label:"Wanted",value:d?`Réseau ${nd[d].toLowerCase()}`:"Non configuré"}),o.jsx(Uo,{label:"Effective",value:f?`Réseau ${nd[f].toLowerCase()}`:"Indisponible"}),o.jsx(Uo,{label:"Runtime",value:p?"Runtime verrouillé":w?"Aucun runtime actif":m?"Runtime en lecture seule":"Runtime modifiable"}),o.jsx(Uo,{label:"Control",value:u?"Lecture seule":"Modifiable"})]}),u&&o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:r?.control.reason??"Cette configuration réseau est en lecture seule."}),!u&&w&&o.jsx("p",{className:"rounded-md border border-primary/30 bg-primary/10 px-3 py-2 text-xs text-primary",children:"Aucun runtime actif. La configuration sera appliquée au prochain lancement."}),!u&&p&&o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:x??"Le runtime actif expose un état réseau en lecture seule."}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Réseau"}),o.jsxs("select",{"aria-label":`${e} network`,value:a,disabled:s||u,onChange:v=>c(v.target.value),className:U("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"Non configuré"}),o.jsx("option",{value:"allow",children:"Réseau autorisé"}),o.jsx("option",{value:"deny",children:"Réseau interdit"}),o.jsx("option",{value:"ask",children:"Demande d'autorisation"})]})]}),n?.network&&!t?.network&&o.jsxs("p",{className:"text-xs text-muted",children:["Hérite du projet : Réseau ",nd[n.network].toLowerCase(),"."]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"Clear network",disabled:s||u||!t?.network,onClick:()=>i(null),children:"Clear"}),o.jsx(M,{size:"sm",variant:"primary","aria-label":"Save network",disabled:s||u||!h,loading:s&&h,onClick:()=>i(a?{network:a}:null),children:"Save"})]})]})]})}function Uo({label:e,value:t}){return o.jsxs("div",{className:"rounded-md border border-border/70 bg-raised px-3 py-2",children:[o.jsx("span",{className:"block text-[11px] font-medium uppercase text-faint",children:e}),o.jsx("span",{className:"text-xs text-content",children:t})]})}function UO({title:e,draft:t,sourcePolicy:n,custom:r,canClear:s,busy:i,onSave:l,onClear:a}){const[c,u]=g.useState(t),h=g.useRef(t);g.useEffect(()=>{u(p=>JSON.stringify(p)===JSON.stringify(h.current)?t:p),h.current=t},[t]);const d=g.useMemo(()=>JSON.stringify(c)!==JSON.stringify(t),[t,c]);function f(p,m){u(x=>({...x,[p]:m}))}return o.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[o.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-3 py-2.5",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:"truncate text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-xs text-muted",children:n?`${n.rules.length} rules`:"Not configured"})]}),r&&o.jsx("span",{className:"shrink-0 rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Advanced"})]}),o.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Fallback"}),o.jsxs("select",{"aria-label":`${e} fallback`,value:c.fallback,disabled:i,onChange:p=>u(m=>({...m,fallback:p.target.value})),className:U("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"ask",children:"Ask"}),o.jsx("option",{value:"allow",children:"Allow"}),o.jsx("option",{value:"deny",children:"Deny"})]})]}),o.jsx("div",{className:"grid grid-cols-1 gap-2",children:$O.map(p=>o.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:p.label}),o.jsx(qO,{value:c[p.key],disabled:i,label:p.label,onChange:m=>f(p.key,m)})]},p.key))}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:i||!s,onClick:a,children:"Clear"}),o.jsx(M,{size:"sm",variant:"primary",disabled:i||!d,loading:i&&d,onClick:()=>l(c),children:"Save"})]})]})]})}function qO({value:e,disabled:t,label:n,onChange:r}){const s=[{value:"none",label:"None"},{value:"allow",label:"Allow"},{value:"deny",label:"Deny"}];return o.jsx("div",{role:"group","aria-label":`${n} permission`,className:"grid grid-cols-3 overflow-hidden rounded-md border border-border",children:s.map(i=>o.jsx("button",{type:"button",disabled:t,"aria-pressed":e===i.value,onClick:()=>r(i.value),className:U("h-8 min-w-0 border-r border-border px-2 text-xs font-medium last:border-r-0","transition-colors disabled:cursor-not-allowed disabled:opacity-50",e===i.value?i.value==="deny"?"bg-danger/20 text-danger":i.value==="allow"?"bg-success/20 text-success":"bg-raised text-content":"bg-surface text-muted hover:bg-raised hover:text-content"),children:i.label},i.value))})}function Bp(e){return e.type.startsWith("issue")}function QS(e){return e.type.startsWith("sprint")}function VO(e){return e.replace(/[\s-]+/g,"").toUpperCase()}const KO=["open","inProgress","QA","closed"],GO=["low","medium","high","critical"],YO=["number","priority","status","title"],XO=["asc","desc"];function JS(e){return`tickets:listFilters:${e}`}function QO(e){return`tickets:pickerFilters:${e}`}function ZS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dv(e,t){if(!Array.isArray(e))return;const n=new Set(t),r=[];for(const s of e)typeof s=="string"&&n.has(s)&&!r.includes(s)&&r.push(s);return r.length>0?r:void 0}function JO(e){if(!ZS(e))return;const{field:t,direction:n}=e;if(typeof t=="string"&&YO.includes(t)&&typeof n=="string"&&XO.includes(n))return{field:t,direction:n}}function e0(e,t={}){if(!ZS(e))return{};const n={};typeof e.text=="string"&&e.text.length>0&&(n.text=e.text);const r=Dv(e.statuses,KO);r&&(n.statuses=r);const s=Dv(e.priorities,GO);if(s&&(n.priorities=s),typeof e.assignedAgentId=="string"&&e.assignedAgentId){const{validAgentIds:l}=t;(!l||l.has(e.assignedAgentId))&&(n.assignedAgentId=e.assignedAgentId)}const i=JO(e.sort);return i&&(n.sort=i),typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0&&(n.limit=e.limit),n}function ZO(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.assignedAgentId&&(t.assignedAgentId=e.assignedAgentId),e.sort&&(t.sort=e.sort),typeof e.limit=="number"&&(t.limit=e.limit),Object.keys(t).length>0?t:null}function eB(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.sort&&(t.sort=e.sort),Object.keys(t).length>0?t:null}function Rv(e,t,n){return e?e0(e.read(JS(t)),n):{}}function tB(e,t,n){if(!e)return;const r=ZO(n),s=JS(t);r?e.write(s,r):e.remove(s)}function Sr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function zp(e){const{ticket:t,system:n,uiPreferences:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(!1),[f,p]=g.useState(()=>Rv(r,e)),m=g.useRef(e);g.useEffect(()=>{m.current!==e&&(m.current=e,p(Rv(r,e)))},[e,r]),g.useEffect(()=>{tB(r,e,f)},[r,e,f]);const x=g.useMemo(()=>JSON.stringify(f),[f]),w=g.useCallback(async()=>{d(!0),u(null);try{i(await t.list(e,f))}catch(D){u(Sr(D))}finally{d(!1)}},[e,t,x]),v=g.useCallback(D=>{p(R=>{const E=R.statuses??[],O=E.includes(D)?E.filter(G=>G!==D):[...E,D],{statuses:I,...W}=R;return O.length>0?{...W,statuses:O}:W})},[]),_=g.useCallback(D=>{p(R=>{const E=R.priorities??[],O=E.includes(D)?E.filter(G=>G!==D):[...E,D],{priorities:I,...W}=R;return O.length>0?{...W,priorities:O}:W})},[]),y=g.useCallback(()=>{p(({statuses:D,priorities:R,...E})=>E)},[]),b=g.useCallback(async()=>{try{a(await t.listSprints(e))}catch(D){u(Sr(D))}},[e,t]),C=g.useCallback(async D=>{u(null);try{const R=await t.create(e,D);return await w(),R}catch(R){return u(Sr(R)),null}},[e,t,w]),S=g.useCallback(async(D,R)=>{u(null);try{const E=await t.read(e,D);return await t.setTicketSprint(e,D,R,E.version),await Promise.all([w(),b()]),!0}catch(E){return u(Sr(E)),!1}},[e,t,w,b]),N=g.useCallback(async D=>{u(null);try{const R=await t.createSprint(e,D);return await b(),R}catch(R){return u(Sr(R)),null}},[e,t,b]),L=g.useCallback(async(D,R)=>{u(null);try{const E=l.find(O=>O.id===D);return E?(await t.renameSprint(e,D,R,E.version),await b(),!0):!1}catch(E){return u(Sr(E)),!1}},[e,t,l,b]),A=g.useCallback(async(D,R)=>{u(null);const E=[...l].sort((G,P)=>G.order-P.order),O=E.findIndex(G=>G.id===D),I=R==="up"?O-1:O+1;if(O===-1||I<0||I>=E.length)return!1;const W=[...E];[W[O],W[I]]=[W[I],W[O]];try{return await t.reorderSprints(e,W.map(G=>G.id)),await b(),!0}catch(G){return u(Sr(G)),!1}},[e,t,l,b]),k=g.useCallback(async D=>{u(null);try{return await t.deleteSprint(e,D),await Promise.all([w(),b()]),!0}catch(R){return u(Sr(R)),!1}},[e,t,w,b]);return g.useEffect(()=>{w()},[w]),g.useEffect(()=>{b()},[b]),g.useEffect(()=>{if(!n)return;let D,R=!1;return n.onDomainEvent(E=>{Bp(E)&&w(),(QS(E)||E.type==="issueSprintChanged")&&b()}).then(E=>{R?E():D=E}),()=>{R=!0,D?.()}},[w,b,n]),{list:s,sprints:l,error:c,busy:h,query:f,setQuery:p,toggleStatus:v,togglePriority:_,clearFacets:y,refresh:w,create:C,assignSprint:S,createSprint:N,renameSprint:L,moveSprint:A,deleteSprint:k}}function t0(e){const{agent:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(!1);g.useEffect(()=>{let c=!1;return i(!1),t.listAgents(e).then(u=>{c||(r(u),i(!0))}).catch(()=>{c||(r([]),i(!0))}),()=>{c=!0}},[e,t]);const l=g.useMemo(()=>new Map(n.map(c=>[c.id,c.name])),[n]);return{agents:n,nameOf:c=>l.get(c)??`${c.slice(0,8)}…`,loaded:s}}const Lc=["open","inProgress","QA","closed"],Ni=["low","medium","high","critical"],n0=["relatesTo","blocks","blockedBy","duplicates","dependsOn"];function Fp(e){switch(e){case"open":return"Open";case"inProgress":return"In progress";case"QA":return"QA";case"closed":return"Closed"}}function Dc(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Mv(e){switch(e){case"relatesTo":return"relates to";case"blocks":return"blocks";case"blockedBy":return"blocked by";case"duplicates":return"duplicates";case"dependsOn":return"depends on"}}function nB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function rB(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function r0(e){return U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function so({status:e}){return o.jsx("span",{className:r0(nB(e)),children:Fp(e)})}function io({priority:e}){return o.jsx("span",{className:r0(rB(e)),children:Dc(e)})}function _i({ticketRef:e,onOpen:t,className:n}){const r=U("inline-flex shrink-0 items-center rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",n);return t?o.jsx("button",{type:"button","aria-label":`open ticket ${e}`,className:U(r,"transition-colors hover:bg-primary/15 hover:text-primary"),onClick:()=>t(e),children:e}):o.jsx("code",{className:r,children:e})}const sB=/#\d+/g;function iB(e,t){const n=[];let r=0,s=0;for(const i of e.matchAll(sB)){const l=i.index??0;l>r&&n.push(e.slice(r,l)),n.push(o.jsx(_i,{ticketRef:i[0],onOpen:t},`ref-${s++}-${l}`)),r=l+i[0].length}return r0||r.length>0;return o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"search tickets",placeholder:a,value:e,onChange:d=>t(d.target.value)}),o.jsxs("fieldset",{"aria-label":"filter by status",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Statut"}),Lc.map(d=>o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[o.jsx("input",{type:"checkbox","aria-label":`filter status ${Fp(d)}`,className:"accent-primary",checked:n.includes(d),onChange:()=>s(d)}),o.jsx(so,{status:d})]},d))]}),o.jsxs("fieldset",{"aria-label":"filter by priority",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Priorité"}),Ni.map(d=>o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[o.jsx("input",{type:"checkbox","aria-label":`filter priority ${Dc(d)}`,className:"accent-primary",checked:r.includes(d),onChange:()=>i(d)}),o.jsx(io,{priority:d})]},d))]}),u&&o.jsxs("div",{"aria-label":"sort tickets",className:"flex flex-wrap items-center gap-2",children:[o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted",children:["Trier par",o.jsxs("select",{"aria-label":"sort tickets by",className:lB,value:c?.field??"",onChange:d=>{const f=d.target.value;u(f===""?void 0:{field:f,direction:c?.direction??"asc"})},children:[o.jsx("option",{value:"",children:"Par défaut"}),oB.map(d=>o.jsx("option",{value:d,children:s0[d]},d))]})]}),c&&o.jsx(M,{size:"sm",variant:"ghost","aria-label":`sort direction ${c.direction==="asc"?"ascending":"descending"}`,onClick:()=>u({field:c.field,direction:c.direction==="asc"?"desc":"asc"}),children:c.direction==="asc"?"Croissant ↑":"Décroissant ↓"})]}),l&&h&&o.jsx("div",{children:o.jsx(M,{size:"sm",variant:"ghost","aria-label":"clear filters",onClick:l,children:"Effacer"})})]})}function Iv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Rc(e,t={}){const{initialQuery:n,excludeRefs:r,debounceMs:s=200,refreshOnEvents:i,persistenceKey:l}=t,{ticket:a,system:c,uiPreferences:u}=fe(),h=g.useRef(null);if(h.current===null){const V=l&&u?e0(u.read(l)):{};h.current={statuses:n?.statuses??V.statuses,priorities:n?.priorities??V.priorities,assignedAgentId:n?.assignedAgentId??V.assignedAgentId,text:n?.text??V.text,sort:n?.sort??V.sort}}const d=h.current,[f,p]=g.useState({statuses:d.statuses,priorities:d.priorities,assignedAgentId:d.assignedAgentId}),[m,x]=g.useState(d.text??""),[w,v]=g.useState(m),[_,y]=g.useState(d.sort),[b,C]=g.useState([]),[S,N]=g.useState(void 0),[L,A]=g.useState(!1),[k,D]=g.useState(null),[R,E]=g.useState(0),O=g.useCallback(()=>E(V=>V+1),[]),I=n?.limit,W=(r??[]).join(","),G=g.useMemo(()=>new Set(r??[]),[W]);g.useEffect(()=>{const V=setTimeout(()=>v(m),s);return()=>clearTimeout(V)},[m,s]),g.useEffect(()=>{if(!l||!u)return;const V=w.trim(),Y=eB({...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...V?{text:V}:{},..._?{sort:_}:{}});Y?u.write(l,Y):u.remove(l)},[l,u,f,w,_]);const P=g.useMemo(()=>JSON.stringify({facets:f,text:w.trim(),sort:_,limit:I}),[f,w,_,I]),z=g.useRef(0),j=g.useCallback(V=>{const Y=w.trim();return{...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...f.assignedAgentId?{assignedAgentId:f.assignedAgentId}:{},...Y?{text:Y}:{},..._?{sort:_}:{},...I?{limit:I}:{},...V?{cursor:V}:{}}},[f,w,_,I]);g.useEffect(()=>{const V=++z.current;A(!0),D(null),a.list(e,j()).then(Y=>{V===z.current&&(C(Y.items),N(Y.nextCursor))}).catch(Y=>{V===z.current&&(D(Iv(Y)),C([]),N(void 0))}).finally(()=>{V===z.current&&A(!1)})},[P,e,a,R]),g.useEffect(()=>{if(!i||!c)return;let V,Y=!1;return c.onDomainEvent(oe=>{(Bp(oe)||QS(oe))&&E(pe=>pe+1)}).then(oe=>{Y?oe():V=oe}),()=>{Y=!0,V?.()}},[i,c]);const se=g.useCallback(()=>{if(L||!S)return;const V=++z.current;A(!0),D(null),a.list(e,j(S)).then(Y=>{V===z.current&&(C(oe=>[...oe,...Y.items]),N(Y.nextCursor))}).catch(Y=>{V===z.current&&D(Iv(Y))}).finally(()=>{V===z.current&&A(!1)})},[L,S,a,e,j]),q=g.useCallback(V=>{p(Y=>{const oe=Y.statuses??[],pe=oe.includes(V)?oe.filter(Pe=>Pe!==V):[...oe,V];return{...Y,statuses:pe.length>0?pe:void 0}})},[]),T=g.useCallback(V=>{p(Y=>{const oe=Y.priorities??[],pe=oe.includes(V)?oe.filter(Pe=>Pe!==V):[...oe,V];return{...Y,priorities:pe.length>0?pe:void 0}})},[]),re=g.useCallback(()=>{p(V=>({...V,statuses:void 0,priorities:void 0}))},[]),ee=g.useCallback(async V=>{const Y=await a.read(e,V);return{ref:Y.ref,id:Y.id,number:Y.number,title:Y.title,status:Y.status,priority:Y.priority}},[a,e]);return{rows:g.useMemo(()=>G.size===0?b:b.filter(V=>!G.has(V.ref)),[b,G]),busy:L,error:k,text:m,setText:x,statuses:f.statuses??[],priorities:f.priorities??[],toggleStatus:q,togglePriority:T,clearFacets:re,sort:_,setSort:y,hasMore:S!==void 0,loadMore:se,refresh:O,resolve:ee}}const Ov='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function i0({open:e,projectId:t,title:n="Sélectionner un ticket",confirmLabel:r="Sélectionner",selectionMode:s="single",excludeRefs:i,initialQuery:l,persistFilters:a=!0,onSelect:c,onClose:u}){return e?o.jsx(aB,{projectId:t,title:n,confirmLabel:r,selectionMode:s,excludeRefs:i,initialQuery:l,persistFilters:a,onSelect:c,onClose:u}):null}function aB({projectId:e,title:t,confirmLabel:n,selectionMode:r,excludeRefs:s,initialQuery:i,persistFilters:l,onSelect:a,onClose:c}){const u=Rc(e,{initialQuery:i,excludeRefs:s,persistenceKey:l?QO(e):void 0}),h=g.useRef(null),[d,f]=g.useState(!1),[p,m]=g.useState(null),[x,w]=g.useState(()=>new Set),v=r==="multi";g.useEffect(()=>{const S=document.activeElement,N=h.current;N?.querySelector(Ov)?.focus();function A(k){if(k.key==="Escape"){k.preventDefault(),c();return}if(k.key!=="Tab"||!N)return;const D=Array.from(N.querySelectorAll(Ov)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(D.length===0)return;const R=D[0],E=D[D.length-1],O=document.activeElement;k.shiftKey&&O===R?(k.preventDefault(),E.focus()):!k.shiftKey&&O===E&&(k.preventDefault(),R.focus())}return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A),S?.focus?.()}},[c]);function _(S){return S&&typeof S=="object"&&"message"in S?String(S.message):String(S)}function y(S){w(N=>{const L=new Set(N);return L.has(S)?L.delete(S):L.add(S),L})}async function b(S){if(!d){f(!0),m(null);try{const N=await u.resolve(S);a(N),c()}catch(N){m(_(N)),f(!1)}}}async function C(){if(!(d||x.size===0)){f(!0),m(null);try{const S=await Promise.all(Array.from(x).map(N=>u.resolve(N)));a(S),c()}catch(S){m(_(S)),f(!1)}}}return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindowNested},onMouseDown:S=>{S.target===S.currentTarget&&c()},children:o.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-label":t,className:"flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:t}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close ticket picker",onClick:c,children:"Close"})]}),o.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:o.jsx($p,{text:u.text,onTextChange:u.setText,statuses:u.statuses,priorities:u.priorities,onToggleStatus:u.toggleStatus,onTogglePriority:u.togglePriority,onClearFacets:u.clearFacets,sort:u.sort,onSortChange:u.setSort})}),(u.error||p)&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??u.error}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[u.busy&&u.rows.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading tickets…"})]}):u.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No matching tickets."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.rows.map(S=>{const N=x.has(S.ref);return o.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:o.jsxs("button",{type:"button","aria-label":`select ticket ${S.ref}`,...v?{role:"checkbox","aria-checked":N}:{},disabled:d,onClick:()=>v?y(S.ref):void b(S.ref),className:U("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none","disabled:cursor-not-allowed disabled:opacity-60",v&&N&&"bg-raised"),children:[v&&o.jsx("span",{"aria-hidden":"true",className:U("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",N?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),o.jsx(_i,{ticketRef:S.ref,className:"mt-0.5"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:S.title}),o.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[o.jsx(so,{status:S.status}),o.jsx(io,{priority:S.priority})]})]})},S.ref)})}),u.hasMore&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:u.busy,onClick:()=>u.loadMore(),children:"Load more"})})]}),v&&o.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3",children:[o.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[x.size," sélectionné",x.size>1?"s":""]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel ticket selection",onClick:c,children:"Annuler"}),o.jsx(M,{size:"sm","aria-label":"confirm ticket selection",loading:d,disabled:x.size===0||d,onClick:()=>void C(),children:x.size>0?`${n} (${x.size})`:n})]})]})]})})}function cB({projectId:e,vm:t,onClose:n}){const r=Rc(e,{refreshOnEvents:!0}),s=r.rows,i=[...t.sprints].sort((x,w)=>x.order-w.order),[l,a]=g.useState(""),[c,u]=g.useState({}),[h,d]=g.useState(null),[f,p]=g.useState(null);async function m(x){x.preventDefault();const w=l.trim()||`Sprint ${i.length+1}`;await t.createSprint(w)&&a("")}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"manage sprints",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:"Manage sprints"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"Close"})]}),t.error&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-5 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex-1 overflow-auto p-5",children:[o.jsxs("form",{onSubmit:m,className:"mb-5 flex items-center gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsx(ce,{"aria-label":"new sprint name",placeholder:"Sprint name (optional)",value:l,onChange:x=>a(x.target.value),className:"max-w-xs"}),o.jsx(M,{type:"submit",size:"sm",disabled:t.busy,children:"Create sprint"})]}),o.jsx("div",{className:"mb-5",children:o.jsx($p,{text:r.text,onTextChange:r.setText,statuses:r.statuses,priorities:r.priorities,onToggleStatus:r.toggleStatus,onTogglePriority:r.togglePriority,onClearFacets:r.clearFacets,sort:r.sort,onSortChange:r.setSort})}),r.error&&o.jsx("p",{role:"alert",className:"mb-4 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),i.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No sprints yet."}):o.jsx("ul",{className:"flex flex-col gap-4",children:i.map((x,w)=>{const v=s.filter(y=>y.sprintId===x.id),_=c[x.id]??x.name;return o.jsxs("li",{"aria-label":`sprint row ${x.name}`,className:"rounded-md border border-border p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",x.order]}),o.jsx(ce,{"aria-label":`rename sprint ${x.name}`,value:_,disabled:t.busy,onChange:y=>u(b=>({...b,[x.id]:y.target.value})),className:"max-w-xs"}),o.jsx(M,{size:"sm","aria-label":`save sprint ${x.name}`,disabled:t.busy||_.trim()===""||_.trim()===x.name,onClick:async()=>{await t.renameSprint(x.id,_.trim())&&u(b=>{const{[x.id]:C,...S}=b;return S})},children:"Save"}),o.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} up`,disabled:t.busy||w===0,onClick:()=>void t.moveSprint(x.id,"up"),children:"↑"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} down`,disabled:t.busy||w===i.length-1,onClick:()=>void t.moveSprint(x.id,"down"),children:"↓"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete sprint ${x.name}`,disabled:t.busy,className:"text-danger hover:text-danger",onClick:()=>d({id:x.id,name:x.name}),children:"Delete"})]})]}),o.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[v.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No tickets in this sprint."}):o.jsx("ul",{className:"flex flex-col gap-1",children:v.map(y=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx(_i,{ticketRef:y.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:y.title}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(so,{status:y.status}),o.jsx(io,{priority:y.priority})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`remove ${y.ref} from sprint`,disabled:t.busy,onClick:()=>void t.assignSprint(y.ref,null),children:"Remove"})]},y.ref))}),o.jsx("div",{className:"mt-1",children:o.jsx(M,{size:"sm",variant:"ghost","aria-label":`add ticket to sprint ${x.name}`,disabled:t.busy,onClick:()=>p({id:x.id,name:x.name}),children:"Ajouter des tickets"})})]})]},x.id)})}),r.hasMore&&o.jsx("div",{className:"mt-4 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:r.busy,onClick:()=>r.loadMore(),children:"Load more tickets"})})]}),h&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"delete sprint confirmation",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Supprimer le sprint « ",h.name," » ?"]}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Les tickets de ce sprint ne seront pas supprimés : ils seront simplement désassignés et retourneront au backlog « Sans sprint »."}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete sprint",disabled:t.busy,onClick:()=>d(null),children:"Annuler"}),o.jsx(M,{size:"sm","aria-label":"confirm delete sprint",className:"text-danger hover:text-danger",disabled:t.busy,onClick:async()=>{await t.deleteSprint(h.id),d(null)},children:"Supprimer"})]})]})}),o.jsx(i0,{open:f!==null,projectId:e,title:f?`Ajouter des tickets au sprint « ${f.name} »`:"Ajouter des tickets",confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:s.filter(x=>x.sprintId===f?.id).map(x=>x.ref),onSelect:x=>{const w=Array.isArray(x)?x:[x];if(f)for(const v of w)t.assignSprint(v.ref,f.id)},onClose:()=>p(null)})]})}const Bv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function uB({open:e,projectId:t,selectedSprintId:n,title:r="Sélectionner un sprint",onSelect:s,onClose:i}){return e?o.jsx(hB,{projectId:t,selectedSprintId:n??null,title:r,onSelect:s,onClose:i}):null}function dB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function hB({projectId:e,selectedSprintId:t,title:n,onSelect:r,onClose:s}){const{ticket:i}=fe(),l=g.useRef(null),[a,c]=g.useState(null),[u,h]=g.useState(null);g.useEffect(()=>{let p=!1;return h(null),i.listSprints(e).then(m=>{p||c(m)}).catch(m=>{p||(h(dB(m)),c([]))}),()=>{p=!0}},[i,e]),g.useEffect(()=>{const p=document.activeElement,m=l.current;m?.querySelector(Bv)?.focus();function w(v){if(v.key==="Escape"){v.preventDefault(),s();return}if(v.key!=="Tab"||!m)return;const _=Array.from(m.querySelectorAll(Bv)).filter(S=>S.offsetParent!==null||S===document.activeElement);if(_.length===0)return;const y=_[0],b=_[_.length-1],C=document.activeElement;v.shiftKey&&C===y?(v.preventDefault(),b.focus()):!v.shiftKey&&C===b&&(v.preventDefault(),y.focus())}return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w),p?.focus?.()}},[s]);const d=a?[...a].sort((p,m)=>p.order-m.order):[];function f(p){r(p),s()}return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindowNested},onMouseDown:p=>{p.target===p.currentTarget&&s()},children:o.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":n,className:"flex max-h-[80vh] w-full max-w-sm flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:n}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close sprint picker",onClick:s,children:"Close"})]}),u&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:u}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[o.jsxs("ul",{className:"flex flex-col divide-y divide-border",children:[o.jsx("li",{className:"py-1.5 first:pt-0",children:o.jsx(zv,{label:"Sans sprint",ariaLabel:"select no sprint",selected:t===null,onClick:()=>f(null)})}),a===null?o.jsxs("li",{className:"flex items-center gap-2 py-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading sprints…"})]}):d.map(p=>o.jsx("li",{className:"py-1.5 last:pb-0",children:o.jsx(zv,{label:p.name,ariaLabel:`select sprint ${p.name}`,count:p.ticketCount,selected:t===p.id,onClick:()=>f(p)})},p.id))]}),a!==null&&d.length===0&&!u&&o.jsx("p",{className:"mt-2 text-sm text-muted",children:"No sprints yet."})]})]})})}function zv({label:e,ariaLabel:t,count:n,selected:r,onClick:s}){return o.jsxs("button",{type:"button",role:"option","aria-selected":r,"aria-label":t,onClick:s,className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none",r&&"bg-raised"),children:[o.jsx("span",{"aria-hidden":"true",className:U("flex h-4 w-4 shrink-0 items-center justify-center text-[10px] font-bold",r?"text-primary":"text-transparent"),children:"✓"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e}),n!==void 0&&o.jsx("span",{className:"shrink-0 rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:n})]})}const tf=U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function fB({projectId:e,onOpen:t}){const n=zp(e),{agents:r,nameOf:s,loaded:i}=t0(e);g.useEffect(()=>{if(!i)return;const N=n.query.assignedAgentId;if(N&&!r.some(L=>L.id===N)){const{assignedAgentId:L,...A}=n.query;n.setQuery(A)}},[i,r,n.query,n.setQuery]);const[l,a]=g.useState(!1),[c,u]=g.useState(!1),[h,d]=g.useState(""),[f,p]=g.useState("medium"),[m,x]=g.useState(null),[w,v]=g.useState(!1),_=n.list?.items??[],y=new Set(n.sprints.map(N=>N.id)),b=n.sprints.map(N=>({sprint:N,tickets:_.filter(L=>L.sprintId===N.id)})).filter(N=>N.tickets.length>0),C=_.filter(N=>!N.sprintId||!y.has(N.sprintId));async function S(N){if(N.preventDefault(),!h.trim())return;const L=await n.create({title:h.trim(),priority:f});L&&(m&&await n.assignSprint(L.ref,m.id),d(""),p("medium"),x(null),a(!1),t(L.ref))}return o.jsxs(ke,{title:"Tickets",actions:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>a(N=>!N),children:l?"Cancel":"New"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"manage sprints",onClick:()=>u(!0),children:"Sprints"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"})]}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),l&&o.jsxs("form",{onSubmit:S,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsx(ce,{"aria-label":"new ticket title",placeholder:"Ticket title",value:h,onChange:N=>d(N.target.value)}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("select",{"aria-label":"new ticket priority",className:tf,value:f,onChange:N=>p(N.target.value),children:Ni.map(N=>o.jsx("option",{value:N,children:Dc(N)},N))}),o.jsx(M,{type:"submit",size:"sm",disabled:!h.trim()||n.busy,children:"Create"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs text-muted",children:"Sprint"}),o.jsx(M,{type:"button",size:"sm",variant:"ghost","aria-label":"choose sprint for new ticket",disabled:n.busy,onClick:()=>v(!0),className:"border border-border",children:m?m.name:"Sans sprint"})]})]}),o.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[o.jsx($p,{text:n.query.text??"",onTextChange:N=>n.setQuery({...n.query,text:N||void 0}),statuses:n.query.statuses??[],priorities:n.query.priorities??[],onToggleStatus:n.toggleStatus,onTogglePriority:n.togglePriority,onClearFacets:n.clearFacets,sort:n.query.sort,onSortChange:N=>{const{sort:L,...A}=n.query;n.setQuery(N?{...A,sort:N}:A)}}),o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:o.jsxs("select",{"aria-label":"filter by assignee",className:tf,value:n.query.assignedAgentId??"",onChange:N=>n.setQuery({...n.query,assignedAgentId:N.target.value||void 0}),children:[o.jsx("option",{value:"",children:"All assignees"}),r.map(N=>o.jsx("option",{value:N.id,children:N.name},N.id))]})})]}),n.busy&&n.list===null?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading tickets…"})]}):_.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No tickets."}):o.jsxs("div",{className:"flex flex-col gap-4",children:[b.map(N=>o.jsx(Fv,{heading:N.sprint.name,count:N.tickets.length,tickets:N.tickets,sprints:n.sprints,onOpen:t,nameOf:s,onAssignSprint:n.assignSprint},N.sprint.id)),C.length>0&&o.jsx(Fv,{heading:"Sans sprint",count:C.length,tickets:C,sprints:n.sprints,onOpen:t,nameOf:s,onAssignSprint:n.assignSprint})]}),n.list?.nextCursor&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Load more"})}),c&&o.jsx(cB,{projectId:e,vm:n,onClose:()=>u(!1)}),o.jsx(uB,{open:w,projectId:e,selectedSprintId:m?.id??null,title:"Sprint du nouveau ticket",onSelect:N=>x(N),onClose:()=>v(!1)})]})}function Fv({heading:e,count:t,tickets:n,sprints:r,onOpen:s,nameOf:i,onAssignSprint:l}){return o.jsxs("section",{"aria-label":`sprint section ${e}`,children:[o.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t})]}),o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.map(a=>o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(_i,{ticketRef:a.ref,onOpen:s,className:"mt-0.5"}),o.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>s(a.ref),children:[o.jsx("span",{className:"block truncate text-sm font-medium text-content hover:underline",children:a.title}),a.assignedAgentIds.length>0&&o.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted",children:a.assignedAgentIds.map(i).join(", ")})]}),o.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[o.jsx(so,{status:a.status}),o.jsx(io,{priority:a.priority})]})]}),o.jsx("div",{className:"mt-1 pl-6",children:o.jsxs("select",{"aria-label":`sprint for ${a.ref}`,className:tf,value:a.sprintId??"",onChange:c=>l(a.ref,c.target.value||null),children:[o.jsx("option",{value:"",children:"— No sprint —"}),r.map(c=>o.jsx("option",{value:c.id,children:c.name},c.id))]})})]},a.ref))})]})}function qo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function pB(e){return!!e&&typeof e=="object"&&typeof e.message=="string"&&e.message.includes("version conflict")}function l0(e,t){const{ticket:n,system:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(0),w=g.useCallback(async()=>{p(!0),a(null);try{i(await n.read(e,t,!0)),u(!1),x(A=>A+1)}catch(A){a(qo(A))}finally{p(!1)}},[e,t,n]);g.useEffect(()=>{w()},[w]),g.useEffect(()=>{if(!r)return;let A,k=!1;return r.onDomainEvent(D=>{if(D.type==="issueDeleted"&&D.issueRef===t){d(!0);return}Bp(D)&&D.issueRef===t&&w()}).then(D=>{k?D():A=D}),()=>{k=!0,A?.()}},[w,r,t]);const v=g.useCallback(async(A,k)=>{if(!s)return!1;p(!0),a(null);try{const D=await A(s.version);return i({...D,carnet:k!==void 0?k:s.carnet}),u(!1),!0}catch(D){if(pB(D)){a("This ticket was modified elsewhere. It has been reloaded — re-apply your change.");try{i(await n.read(e,t,!0))}catch(R){a(qo(R))}u(!0),x(R=>R+1)}else a(qo(D));return!1}finally{p(!1)}},[s,n,e,t]),_=g.useCallback(A=>v(k=>n.update(e,t,{...A,expectedVersion:k})),[v,n,e,t]),y=g.useCallback(A=>v(k=>n.updateCarnet(e,t,A,k),A),[v,n,e,t]),b=g.useCallback((A,k)=>v(D=>n.link(e,t,A,k,D)),[v,n,e,t]),C=g.useCallback((A,k)=>v(D=>n.unlink(e,t,A,D,k)),[v,n,e,t]),S=g.useCallback((A,k)=>v(D=>n.assign(e,t,A,k,D)),[v,n,e,t]),N=g.useCallback(A=>v(k=>n.setTicketSprint(e,t,A,k)),[v,n,e,t]),L=g.useCallback(async()=>{p(!0),a(null);try{return await n.delete(e,t),!0}catch(A){return a(qo(A)),!1}finally{p(!1)}},[n,e,t]);return{ticket:s,error:l,conflict:c,deleted:h,busy:f,reloadCount:m,refresh:w,updateFields:_,saveCarnet:y,link:b,unlink:C,assign:S,setSprint:N,remove:L}}function Vo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function mB(e,t){const{ticket:n,profile:r}=fe(),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState([]),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef(null);w.current=l,g.useEffect(()=>{let b=!1;return(async()=>{try{const C=await r?.listProfiles()??[];b||i(C)}catch(C){b||x(Vo(C))}})(),()=>{b=!0}},[r]);const v=g.useCallback(async b=>{if(b){d(!0),x(null);try{const C=await n.openTicketChat(e,t,b);a(C.sessionId),u([])}catch(C){x(Vo(C))}finally{d(!1)}}},[n,e,t]),_=g.useCallback(async()=>{if(w.current){a(null),u([]);try{await n.closeTicketChat(e,t)}catch(b){x(Vo(b))}}},[n,e,t]),y=g.useCallback(async b=>{const C=b.trim();if(!l||!C||f)return;x(null),p(!0),u(N=>[...N,{role:"user",text:C},{role:"assistant",text:"",pending:!0}]);const S=N=>{u(L=>{const A=[...L],k=A.length-1;return k<0||A[k].role!=="assistant"?L:(N.kind==="textDelta"?A[k]={...A[k],text:A[k].text+N.text}:N.kind==="toolActivity"?A[k]={...A[k],text:`${A[k].text} -· ${N.label}`}:N.kind==="error"?A[k]={role:"assistant",text:`⚠️ ${N.message}`,pending:!1}:A[k]={role:"assistant",text:N.content,pending:!1},A)}),(N.kind==="final"||N.kind==="error")&&p(!1)};try{await n.sendTicketChat(l,C,S)}catch(N){x(Vo(N)),u(L=>{const A=[...L],k=A.length-1;return k>=0&&A[k].role==="assistant"&&A[k].pending&&(A[k]={...A[k],pending:!1}),A}),p(!1)}},[n,l,f]);return g.useEffect(()=>()=>{w.current&&n.closeTicketChat(e,t).catch(()=>{})},[n,e,t]),{profiles:s,sessionId:l,turns:c,opening:h,busy:f,error:m,open:v,close:_,send:y}}const gB=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function xB({projectId:e,ticketRef:t}){const n=mB(e,t),[r,s]=g.useState(""),[i,l]=g.useState(""),a=g.useRef(null);g.useEffect(()=>{const h=a.current;h&&(h.scrollTop=h.scrollHeight)},[n.turns]);const c=n.sessionId!==null;function u(){const h=i.trim();!h||n.busy||(n.send(h),l(""))}return o.jsxs("div",{className:"flex flex-col gap-3",children:[c?o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-xs text-muted",children:"Conversation ouverte — l'assistant peut lire le projet et éditer ce ticket."}),o.jsx(M,{size:"sm",variant:"ghost",disabled:n.busy,onClick:()=>void n.close(),children:"Fermer la conversation"})]}),o.jsx("div",{ref:a,className:"flex max-h-96 min-h-32 flex-col gap-2 overflow-auto rounded-md border border-border bg-raised/40 p-3",children:n.turns.length===0?o.jsx("p",{className:"m-auto text-xs text-muted",children:"Démarrez la conversation en décrivant ce que l'assistant doit faire sur ce ticket."}):n.turns.map((h,d)=>o.jsx("div",{className:U("flex",h.role==="user"?"justify-end":"justify-start"),children:o.jsxs("div",{className:U("max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm",h.role==="user"?"bg-primary/15 text-content":"bg-surface text-content"),children:[h.text,h.pending&&o.jsx("span",{className:"ml-1 inline-flex items-center align-middle text-muted",children:o.jsx(Me,{size:12})})]})},d))}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("textarea",{"aria-label":"message à l'assistant",className:U("min-h-10 flex-1 resize-none rounded-md bg-raised p-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),rows:2,placeholder:"Votre message…",value:i,disabled:n.busy,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),u())}}),o.jsx(M,{size:"sm",disabled:!i.trim()||n.busy,loading:n.busy,onClick:u,children:"Envoyer"})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("select",{"aria-label":"profil de l'assistant",className:gB,value:r,disabled:n.opening||n.profiles.length===0,onChange:h=>s(h.target.value),children:[o.jsx("option",{value:"",children:n.profiles.length===0?"Aucun profil disponible":"Choisir un profil IA…"}),n.profiles.map(h=>o.jsx("option",{value:h.id,children:h.name},h.id))]}),o.jsx(M,{size:"sm",disabled:!r||n.opening,loading:n.opening,onClick:()=>void n.open(r),children:"Ouvrir la conversation"})]}),n.error&&o.jsx("p",{role:"alert",className:"text-xs text-danger",children:n.error})]})}const Ko=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),$v=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");async function vB(e){return typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):!1}function Zi({title:e,hint:t,children:n}){return o.jsxs("section",{className:"flex flex-col gap-2 border-b border-border px-5 py-4",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:e}),t&&o.jsx("p",{className:"mt-0.5 text-xs text-muted",children:t})]}),n]})}function _B({projectId:e,ticketRef:t,onClose:n,onOpenRef:r}){const s=l0(e,t),{agents:i,nameOf:l}=t0(e),a=s.ticket,[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState("relatesTo"),[w,v]=g.useState(""),[_,y]=g.useState(!1),[b,C]=g.useState(!1),[S,N]=g.useState(!1),[L,A]=g.useState(!1),[k,D]=g.useState(!1);g.useEffect(()=>{s.deleted&&n()},[s.deleted,n]);const R=s.reloadCount,E=g.useRef(-1),O=g.useRef(null);g.useEffect(()=>{if(!a||E.current===R)return;E.current=R;const q=a.carnet??"",T=O.current;T===null||s.conflict?(u(a.title),d(a.description),p(q)):(u(ee=>ee===T.title?a.title:ee),d(ee=>ee===T.description?a.description:ee),p(ee=>ee===T.carnet?q:ee)),O.current={title:a.title,description:a.description,carnet:q}},[a,R,s.conflict]);const I=!!a&&(c!==a.title||h!==a.description),W=!!a&&f!==(a.carnet??""),G=I||W,P=i.filter(q=>!a?.assignedAgentIds.includes(q.id));function z(){G?C(!0):n()}async function j(){let q=!0;I&&(q=await s.updateFields({title:c,description:h})&&q),q&&W&&(q=await s.saveCarnet(f)&&q),C(!1),q&&n()}async function se(){if(!a)return;await vB(`Travaille sur le ticket ${a.ref} : ${a.title}`)&&(y(!0),window.setTimeout(()=>y(!1),1200))}return o.jsxs(Fh,{open:!0,title:`ticket ${t}`,size:"xl",onClose:z,children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(_i,{ticketRef:t}),a&&o.jsx(so,{status:a.status}),a&&o.jsx(io,{priority:a.priority}),o.jsx("span",{className:"truncate text-sm font-medium text-content",children:a?.title??t})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:!a,onClick:()=>void se(),title:"Copy a delegation prompt to hand this ticket to an agent",children:_?"Copied":"Delegation context"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!a||s.busy,onClick:()=>N(!0),className:"text-danger hover:text-danger",title:"Supprimer définitivement ce ticket",children:"Supprimer"})]})]}),s.conflict&&o.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-1 py-2 text-sm text-warning",children:"This ticket was modified elsewhere and reloaded. Re-apply your change."}),s.error&&!s.conflict&&o.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-1 py-2 text-sm text-danger",children:s.error}),s.busy&&!a?o.jsxs("div",{className:"flex items-center gap-2 py-5 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading ticket…"})]}):a?o.jsxs("div",{className:"-mx-4",children:[o.jsxs(Zi,{title:"Details",children:[o.jsx("label",{className:"text-xs font-medium text-muted",htmlFor:"td-title",children:"Title"}),o.jsx(ce,{id:"td-title",value:c,onChange:q=>u(q.target.value),disabled:s.busy}),o.jsx("label",{className:"mt-2 text-xs font-medium text-muted",htmlFor:"td-desc",children:"Description"}),o.jsx("textarea",{id:"td-desc",className:U($v,"min-h-24"),value:h,onChange:q=>d(q.target.value),disabled:s.busy}),h.trim()&&o.jsx("p",{className:"whitespace-pre-wrap break-words rounded-md bg-raised/40 px-3 py-2 text-xs text-muted",children:iB(h,r)}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsx(M,{size:"sm",disabled:!I||s.busy,loading:s.busy&&I,onClick:()=>void s.updateFields({title:c,description:h}),children:"Save changes"}),I&&o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>{u(a.title),d(a.description)},children:"Reset"})]})]}),o.jsx(Zi,{title:"Status & priority",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Status",o.jsx("select",{"aria-label":"ticket status",className:Ko,value:a.status,disabled:s.busy,onChange:q=>void s.updateFields({status:q.target.value}),children:Lc.map(q=>o.jsx("option",{value:q,children:Fp(q)},q))})]}),o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Priority",o.jsx("select",{"aria-label":"ticket priority",className:Ko,value:a.priority,disabled:s.busy,onChange:q=>void s.updateFields({priority:q.target.value}),children:Ni.map(q=>o.jsx("option",{value:q,children:Dc(q)},q))})]})]})}),o.jsxs(Zi,{title:"Carnet",hint:"Markdown notebook scoped to this ticket only — separate from project memory. Saving replaces the whole carnet.",children:[o.jsx("textarea",{"aria-label":"ticket carnet",className:U($v,"min-h-40 font-mono"),value:f,onChange:q=>p(q.target.value),disabled:s.busy}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(M,{size:"sm",disabled:!W||s.busy,loading:s.busy&&W,onClick:()=>void s.saveCarnet(f),children:"Save carnet"}),W&&o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>p(a.carnet??""),children:"Reset"})]})]}),o.jsxs(Zi,{title:"Linked tickets",children:[a.links.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No linked tickets."}):o.jsx("ul",{className:"flex flex-col gap-1",children:a.links.map(q=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"text-xs text-muted",children:Mv(q.kind)}),o.jsx(_i,{ticketRef:q.targetRef,onOpen:r}),o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>void s.unlink(q.targetRef,q.kind),children:"Remove"})]},`${q.kind}-${q.targetRef}`))}),o.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[o.jsx("select",{"aria-label":"link kind",className:Ko,value:m,disabled:s.busy,onChange:q=>x(q.target.value),children:n0.map(q=>o.jsx("option",{value:q,children:Mv(q)},q))}),o.jsx(M,{size:"sm","aria-label":"add link",disabled:s.busy,onClick:()=>A(!0),children:"Add link"})]})]}),o.jsxs(Zi,{title:"Assigned agents",hint:"Only agents known to this project can be assigned.",children:[a.assignedAgentIds.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No agents assigned."}):o.jsx("ul",{className:"flex flex-wrap gap-2",children:a.assignedAgentIds.map(q=>o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[l(q),o.jsx("button",{type:"button","aria-label":`unassign ${l(q)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:s.busy,onClick:()=>void s.assign(q,!1),children:"×"})]},q))}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsxs("select",{"aria-label":"assign agent",className:Ko,value:w,disabled:s.busy||P.length===0,onChange:q=>v(q.target.value),children:[o.jsx("option",{value:"",children:P.length===0?"No more agents":"Select an agent…"}),P.map(q=>o.jsx("option",{value:q.id,children:q.name},q.id))]}),o.jsx(M,{size:"sm",disabled:!w||s.busy,onClick:async()=>{await s.assign(w,!0)&&v("")},children:"Assign"})]})]}),o.jsx(i0,{open:L,projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...a.links.map(q=>q.targetRef)],onSelect:q=>{const T=Array.isArray(q)?q[0]:q;T&&s.link(T.ref,m),A(!1)},onClose:()=>A(!1)})]}):o.jsx("div",{className:"flex items-center justify-center py-10 text-sm text-muted",children:"Ticket not found."}),a&&o.jsx("div",{className:"pointer-events-none sticky bottom-0 z-10 -mx-4 -mb-4 flex justify-end px-4 pb-4 pt-2",children:o.jsx(M,{"aria-label":"ouvrir l'assistant IA",className:"pointer-events-auto shadow-lg",onClick:()=>D(!0),children:"🤖 Assistant IA"})}),o.jsx(Fh,{open:k,title:`Assistant IA — ${t}`,size:"lg",onClose:()=>D(!1),children:o.jsx(xB,{projectId:e,ticketRef:t})}),b&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"unsaved changes",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Modifications non sauvegardées"}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Vous avez des modifications non sauvegardées. Voulez-vous les sauvegarder avant de fermer ?"}),o.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel close",disabled:s.busy,onClick:()=>C(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close without saving",disabled:s.busy,onClick:n,className:"text-danger hover:text-danger",children:"Fermer sans sauvegarder"}),o.jsx(M,{size:"sm","aria-label":"save and close",loading:s.busy,disabled:s.busy,onClick:()=>void j(),children:"Sauvegarder"})]})]})}),S&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"confirmer la suppression",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Supprimer le ticket"}),o.jsxs("p",{className:"mt-2 text-sm text-muted",children:["Supprimer définitivement le ticket ",t," ? Cette action est irréversible."]}),o.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete",disabled:s.busy,onClick:()=>N(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger","aria-label":"confirm delete",loading:s.busy,disabled:s.busy,onClick:async()=>{await s.remove()&&N(!1)},children:"Supprimer"})]})]})})]})}function yB({projectId:e}){const[t,n]=g.useState(null);return o.jsxs(o.Fragment,{children:[o.jsx(fB,{projectId:e,onOpen:n}),t&&o.jsx(_B,{projectId:e,ticketRef:t,onClose:()=>n(null),onOpenRef:n},`${e}-${t}`)]})}function Wv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function o0({projectId:e}){const{project:t}=fe(),[n,r]=g.useState(""),[s,i]=g.useState(""),[l,a]=g.useState(!1),[c,u]=g.useState(null);g.useEffect(()=>{let f=!1;return a(!0),u(null),t.readProjectContext(e).then(p=>{f||(r(p),i(p))}).catch(p=>{f||u(Wv(p))}).finally(()=>{f||a(!1)}),()=>{f=!0}},[t,e]);async function h(){a(!0),u(null);try{await t.updateProjectContext(e,n),i(n)}catch(f){u(Wv(f))}finally{a(!1)}}const d=n!==s;return o.jsxs(ke,{title:"Project Context",className:"flex flex-col gap-0",children:[c&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:c}),o.jsx("div",{className:"border-b border-border px-4 py-2",children:o.jsx("code",{className:"text-xs text-muted",children:".ideai/CONTEXT.md"})}),o.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[o.jsx("textarea",{"aria-label":"project context",value:n,onChange:f=>r(f.target.value),rows:18,className:U("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:l}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l&&o.jsx(Me,{size:14}),o.jsx(M,{variant:"primary",disabled:l||!d,onClick:()=>void h(),children:"Save"})]})]})]})}function a0({panel:e,projectId:t,projectRoot:n,onOpenConversation:r}){switch(e){case"context":return o.jsx(o0,{projectId:t});case"work":return o.jsx(iT,{projectId:t,onOpenConversation:r});case"tickets":return o.jsx(yB,{projectId:t});case"agents":return o.jsx(_w,{projectId:t,projectRoot:n});case"templates":return o.jsx($S,{projectId:t});case"skills":return o.jsx(WS,{projectId:t});case"permissions":return o.jsx(XS,{projectId:t});case"memory":return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(KS,{projectId:t}),o.jsx(VS,{})]});case"git":return o.jsx(Dw,{projectId:t})}}const Hn={projects:"Projects",context:"Project context",work:"Work state",tickets:"Tickets",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Memory",git:"Git"};function Ar(e,t){return e[t]??"closed"}function ls(e,t){return typeof e=="object"&&e.dock===t}function Hv(e,t){return Object.keys(Hn).filter(n=>ls(Ar(e,n),t))}function bB(e){return Object.keys(Hn).filter(t=>Ar(e,t)==="floating")}function rd(e){return e==="detached"}function wB(e){return e!=="projects"&&e in Hn}function SB(e,t){let n=!1;const r={...e};for(const s of t){if(!s.visible||!wB(s.panel))continue;const i=s.panel;Ar(e,i)==="closed"&&(r[i]="detached",n=!0)}return n?r:e}const kB={projects:"md",context:"lg",work:"lg",tickets:"lg",agents:"lg",templates:"lg",skills:"lg",permissions:"md",memory:"lg",git:"lg"};function CB(e){return e.type==="backgroundTaskChanged"&&(e.state==="completed"||e.state==="failed"||e.state==="cancelled"||e.state==="delivered")}function jB(){const e=NL(),{system:t,window:n,focusedProject:r,git:s}=fe(),[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState({}),[d,f]=g.useState(340),[p,m]=g.useState(340),[x,w]=g.useState(null),[v,_]=g.useState(null),[y,b]=g.useState(null),[C,S]=g.useState([]),N=e.openTabs.find(B=>B.id===e.activeTabId)??null,[L,A]=g.useState(!1);g.useEffect(()=>{if(!N){A(!1);return}let B=!1;return s.branches(N.id).then(()=>{B||A(!0)}).catch(()=>{B||A(!1)}),()=>{B=!0}},[s,N?.id]);const{registry:k}=gp(),R=gA(k,{projectOpen:N!==null,gitRepository:L,agentSelected:!1,terminalFocused:!1,layoutCellFocused:!1});g.useEffect(()=>{_(null),b(null)},[N?.id]),g.useEffect(()=>{r?.setFocusedProject(N?{id:N.id,name:N.name,root:N.root}:null)},[r,N?.id,N?.name,N?.root]),g.useEffect(()=>{let B,he=!1;return t.onDomainEvent(ue=>{if(!CB(ue))return;const Ee={id:`${ue.taskId}-${ue.state}-${Date.now()}`,projectId:ue.projectId,agentId:ue.agentId,taskId:ue.taskId,state:ue.state};S(dt=>[...dt.slice(-2),Ee]),window.setTimeout(()=>{S(dt=>dt.filter(Rn=>Rn.id!==Ee.id))},7e3)}).then(ue=>{he?ue():B=ue}),()=>{he=!0,B?.()}},[t]);const E=v?.kind??"terminal",O=i.trim().length>0&&a.trim().length>0&&!e.busy;async function I(B){B.preventDefault(),O&&(await e.createProject(i.trim(),a.trim()),l(""),c(""))}async function W(){const B=await t.pickFolder();B!==null&&c(B)}function G(B,he){h(ue=>{const Ee={...ue};if(he==="floating")for(const dt of Object.keys(Ee))dt!==B&&Ee[dt]==="floating"&&delete Ee[dt];return Ee[B]=he,Ee})}function P(B){h(he=>{if(!(B in he))return he;const ue={...he};return delete ue[B],ue})}function z(){h(B=>{let he=!1;const ue={...B};for(const Ee of Object.keys(ue))ue[Ee]==="floating"&&(delete ue[Ee],he=!0);return he?ue:B})}function j(B){N&&n.openViewWindow(B).then(()=>G(B,"detached")).catch(()=>{})}g.useEffect(()=>{let B,he=!1;return n.onViewWindowClosed(({panel:ue})=>{h(Ee=>Ee[ue]==="detached"?(()=>{const dt={...Ee};return delete dt[ue],dt})():Ee)}).then(ue=>{he?ue():B=ue}),()=>{he=!0,B?.()}},[n]),g.useEffect(()=>{let B=!1;return n.listOpenViewWindows().then(he=>{B||h(ue=>SB(ue,he))}).catch(()=>{}),()=>{B=!0}},[n]);function se(B){b(B),z()}const q=["context","work","tickets","agents","templates","skills","permissions","memory","git","projects"];function T(B){const he=Ar(u,B),ue=[{id:"closed",label:"Fermé",active:he==="closed",onSelect:()=>P(B)},{id:"floating",label:"Flottant",active:he==="floating",onSelect:()=>G(B,"floating")},{id:"dock-left",label:"Ancré à gauche",active:ls(he,"left"),onSelect:()=>G(B,{dock:"left"})},{id:"dock-right",label:"Ancré à droite",active:ls(he,"right"),onSelect:()=>G(B,{dock:"right"})}];return B!=="projects"&&ue.push({id:"detached",label:"Fenêtre détachée",active:rd(he),disabled:!N,onSelect:()=>j(B)}),ue}const re=[{id:"panels",label:"Panneaux",items:[...q.map(B=>({id:B,label:Hn[B],active:Ar(u,B)!=="closed",onSelect:()=>{},submenu:T(B)})),...R.itemsFor("panels")]},...R.topLevelMenus,{id:"settings",label:"Paramètres",items:[...Tw.map(B=>({id:B,label:Aw[B],active:x===B,onSelect:()=>{w(B),z()}})),...R.itemsFor("settings")]}],ee=o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("form",{onSubmit:I,className:"flex flex-col gap-2",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"New project"}),o.jsx(ce,{"aria-label":"project name",placeholder:"Project name",value:i,onChange:B=>l(B.target.value)}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ce,{"aria-label":"project root",placeholder:"/absolute/project/root",value:a,onChange:B=>c(B.target.value),className:"flex-1"}),o.jsx(M,{type:"button","aria-label":"browse project folder",onClick:()=>void W(),disabled:e.busy,children:"Browse…"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{type:"submit",variant:"primary",disabled:!O,className:"flex-1",children:"Create project"}),o.jsx(M,{type:"button",onClick:()=>void e.refresh(),disabled:e.busy,children:"Refresh"})]})]}),o.jsx(ke,{title:"Known projects",children:e.projects.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No projects yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:e.projects.map(B=>o.jsxs("li",{className:"flex items-center justify-between gap-2 py-2 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"font-medium text-content",children:B.name}),o.jsx("code",{className:"truncate text-xs text-muted",children:B.root})]}),o.jsx(M,{size:"sm",onClick:()=>void e.openProject(B.id),children:"Open"})]},B.id))})})]});function Q(B){return B==="projects"?ee:N?o.jsx(a0,{panel:B,projectId:N.id,projectRoot:N.root,onOpenConversation:se}):o.jsx("p",{className:"text-sm text-muted",children:"Open a project to use this panel."})}const V=!N&&Ar(u,"projects")==="closed",Y=Hv(u,"left"),oe=Hv(u,"right"),pe=bB(u);function Pe({panel:B}){const he=Ar(u,B),ue=Hn[B],Ee="bg-raised text-content ring-1 ring-border-strong";return o.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(sr,{size:"sm",title:"Ancré à gauche","aria-label":`Ancré à gauche — ${ue}`,"aria-pressed":ls(he,"left"),className:U(ls(he,"left")&&Ee),onClick:()=>G(B,{dock:"left"}),children:"⇤"}),o.jsx(sr,{size:"sm",title:"Ancré à droite","aria-label":`Ancré à droite — ${ue}`,"aria-pressed":ls(he,"right"),className:U(ls(he,"right")&&Ee),onClick:()=>G(B,{dock:"right"}),children:"⇥"}),o.jsx(sr,{size:"sm",title:"Flottant","aria-label":`Flottant — ${ue}`,"aria-pressed":he==="floating",className:U(he==="floating"&&Ee),onClick:()=>G(B,"floating"),children:"□"}),B!=="projects"&&o.jsx(sr,{size:"sm",title:"Fenêtre détachée","aria-label":`Fenêtre détachée — ${ue}`,"aria-pressed":rd(he),disabled:!N,className:U(rd(he)&&Ee),onClick:()=>j(B),children:"↗"}),o.jsx(sr,{size:"sm",title:"Fermé","aria-label":`Fermé — ${ue}`,onClick:()=>P(B),children:"×"})]})}function $(B){return o.jsxs("section",{"aria-label":`${Hn[B]} panel`,className:"flex min-h-0 flex-1 flex-col border-b border-border last:border-b-0",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:Hn[B]}),o.jsx(Pe,{panel:B})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3",children:Q(B)})]},B)}return o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),o.jsx(EL,{items:e.openTabs.map(B=>({id:B.id,label:B.name})),activeTabId:e.activeTabId,onSelect:B=>e.activateTab(B),onClose:B=>void e.closeTab(B),projectsPanelOpen:Ar(u,"projects")!=="closed",onOpenProjectsPanel:()=>{w(null),G("projects","floating")}}),o.jsx(VP,{menus:re}),o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[Y.length>0&&o.jsx(dx,{side:"left",width:d,onResize:f,"aria-label":"left dock",children:Y.map($)}),o.jsx("main",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:x?o.jsx(gL,{section:x,onSectionChange:w,onClose:()=>w(null)}):N&&y?o.jsx(uT,{projectId:N.id,conversationId:y,onClose:()=>b(null)},`${N.id}-${y}`):N?o.jsxs(o.Fragment,{children:[o.jsx(HA,{projectId:N.id,onActiveLayoutChange:_}),E==="gitGraph"?o.jsx(jL,{projectId:N.id},`${N.id}-${v?.id??"default"}-graph`):o.jsx(IA,{projectId:N.id,cwd:N.root,layoutId:v?.id,onOpenConversation:se,onOpenPluginsSettings:()=>{w("plugins"),z()}},`${N.id}-${v?.id??"default"}`)]}):o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-xl",children:V?ee:o.jsx("p",{className:"text-sm text-muted",children:"Select or create a project to get started."})})})}),oe.length>0&&o.jsx(dx,{side:"right",width:p,onResize:m,"aria-label":"right dock",children:oe.map($)})]}),pe.map(B=>o.jsxs(Fh,{open:!0,title:Hn[B],size:kB[B],onClose:()=>P(B),children:[o.jsx("div",{className:"mb-3 flex justify-end border-b border-border pb-3",children:o.jsx(Pe,{panel:B})}),Q(B)]},B)),C.length>0&&o.jsx("div",{className:"fixed bottom-4 right-4 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",style:{zIndex:Sn.toast},children:C.map(B=>o.jsxs("button",{type:"button",className:"rounded-md border border-border bg-surface px-3 py-2 text-left shadow-lg hover:border-border-strong",onClick:()=>{e.openTabs.some(ue=>ue.id===B.projectId)&&e.activateTab(B.projectId),w(null),b(null),G("work","floating"),S(ue=>ue.filter(Ee=>Ee.id!==B.id))},children:[o.jsxs("span",{className:"block text-sm font-medium text-content",children:["Background task ",B.state]}),o.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted",children:[B.agentId.slice(0,8)," · ",B.taskId.slice(0,8)]})]},B.id))})]})}const NB=5;function EB(e){if(e.totalWorkCount===1)return"1 travail actif sera interrompu si vous quittez IdeA maintenant.";const t=[];return e.busyAgentCount>0&&t.push(e.busyAgentCount===1?"1 agent travaille encore":`${e.busyAgentCount} agents travaillent encore`),e.activeBackgroundTaskCount>0&&t.push(e.activeBackgroundTaskCount===1?"1 tâche de fond est encore active":`${e.activeBackgroundTaskCount} tâches de fond sont encore actives`),`${t.join(" et ")}. Ces travaux seront interrompus si vous quittez IdeA maintenant.`}function PB(e){return e.kind==="busyAgent"?`Agent ${e.agentName} — ${e.projectName}`:`Tâche de fond ${e.taskId.slice(0,8)} — ${e.projectName}`}function AB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Uv="app-exit-confirm-title",qv="app-exit-confirm-desc";function TB(){const{system:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{let p=!1,m;return e.onAppExitWorkGuard(x=>{n(x)}).then(x=>{p?x():m=x}).catch(()=>{}),()=>{p=!0,m?.()}},[e]),g.useEffect(()=>{t&&a.current?.focus()},[t!=null]);function u(){r||(n(null),l(null))}async function h(){s(!0),l(null);try{await e.confirmAppExit()}catch(p){l(AB(p))}finally{s(!1)}}if(g.useEffect(()=>{if(!t)return;function p(m){if(m.key==="Escape"){m.preventDefault(),u();return}if(m.key!=="Tab")return;const x=c.current?.querySelectorAll('button:not(:disabled), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(!x||x.length===0)return;const w=x[0],v=x[x.length-1];m.shiftKey&&document.activeElement===w?(m.preventDefault(),v.focus()):!m.shiftKey&&document.activeElement===v&&(m.preventDefault(),w.focus())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t!=null,r]),!t)return null;const d=t.details.slice(0,NB),f=t.details.length-d.length;return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.toast},children:o.jsxs("div",{ref:c,role:"alertdialog","aria-modal":"true","aria-labelledby":Uv,"aria-describedby":qv,onClick:p=>p.stopPropagation(),className:"flex w-full max-w-[520px] min-w-[440px] flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{id:Uv,className:"text-sm font-semibold text-content",children:"Du travail est encore en cours"}),o.jsx("p",{id:qv,className:"text-sm text-content",children:EB(t)}),o.jsx("p",{className:"text-sm text-muted",children:"Annulez la fermeture pour laisser les agents et les tâches se terminer."}),d.length>0&&o.jsxs("ul",{className:"flex flex-col gap-1 rounded-md bg-canvas p-2 text-xs text-muted",children:[d.map((p,m)=>o.jsx("li",{children:`• ${PB(p)}`},m)),f>0&&o.jsxs("li",{children:["+ ",f," autre",f>1?"s":""]})]}),i&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"IdeA n'a pas pu quitter correctement. Réessayez ou consultez les logs."}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",disabled:r,onClick:u,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger",disabled:r,loading:r,onClick:()=>void h(),children:r?"Fermeture…":"Quitter quand même"})]})]})})}function LB(){const{system:e,profile:t}=fe(),[n,r]=g.useState(null),[s,i]=g.useState(null),[l,a]=g.useState([]),[c,u]=g.useState(null);return g.useEffect(()=>{let h,d=!1;return e.onDomainEvent(f=>a(p=>[...p,f])).then(f=>{d?f():h=f}).catch(()=>{}),e.health("ui-boot").then(f=>r(f)).catch(f=>i(DB(f))),()=>{d=!0,h?.()}},[e]),g.useEffect(()=>{let h=!1;return t.firstRunState().then(d=>{h||u(d.isFirstRun)}).catch(()=>{h||u(!1)}),()=>{h=!0}},[t]),o.jsx(RP,{children:o.jsxs(cA,{children:[o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between border-b border-border px-6 py-3",children:[o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"IdeA"}),o.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"tauri"})]}),o.jsx(gw,{justify:"end",children:o.jsx("span",{className:"text-xs text-faint",children:n?o.jsxs(o.Fragment,{children:["backend ",o.jsx("span",{className:"text-success",children:"●"})," v",n.version," ·"," ",l.length," events"]}):s?o.jsx("span",{className:"text-danger",children:"backend unavailable"}):o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx(Me,{size:12})," checking…"]})})})]}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[s&&o.jsx(ke,{className:"mx-4 mt-4 border-danger/40",children:o.jsxs("p",{className:"text-sm text-danger",children:["Error: ",s]})}),c?o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-xl",children:o.jsx(Cw,{onDone:()=>u(!1)})})}):o.jsx(jB,{})]})]}),o.jsx(TB,{})]})})}function DB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const RB=new Set(Object.keys(Hn).filter(e=>e!=="projects"));function MB(e){const n=new URLSearchParams(e).get("panel");return!n||!RB.has(n)?null:{panel:n}}function IB({panel:e}){const{focusedProject:t}=fe(),[n,r]=g.useState(void 0);return g.useEffect(()=>{let s=!1,i;return t.getFocusedProject().then(l=>{s||r(l)}).catch(()=>{s||r(null)}),t.onFocusedProjectChanged(l=>{s||r(l)}).then(l=>{s?l():i=l}),()=>{s=!0,i?.()}},[t]),o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5",children:[o.jsx("h1",{className:"text-sm font-semibold text-content",children:Hn[e]}),n&&o.jsxs("span",{className:"truncate text-xs text-muted",children:["· ",n.name]})]}),o.jsx("main",{className:"min-h-0 flex-1 overflow-auto p-4",children:n?o.jsx(a0,{panel:e,projectId:n.id,projectRoot:n.root}):o.jsx(ke,{children:o.jsx("p",{className:"text-sm text-muted",children:"Ouvrez un projet dans la fenêtre principale pour afficher ce panneau."})})})]})}function OB(e){if(e&&typeof e=="object"&&"message"in e){const t=e;return{code:String(t.code??"ERROR"),message:String(t.message)}}return{code:"ERROR",message:String(e)}}function BB({session:e,onPaired:t}){const[n,r]=g.useState(""),[s,i]=g.useState(()=>Cx(iL())),[l,a]=g.useState(null),[c,u]=g.useState(!1),h=VO(n),d=s.trim(),f=h.length>0&&d.length>0,p=l?.code==="invalidName"?l.message:null,m=l&&!p?l.message:null;async function x(w){if(w.preventDefault(),!(!f||c)){u(!0),a(null);try{await e.pair(h,Cx(d)),t()}catch(v){a(OB(v))}finally{u(!1)}}}return o.jsx("div",{className:"flex h-full items-center justify-center overflow-y-auto bg-canvas p-4 sm:p-6",children:o.jsx(ke,{className:"w-full max-w-sm",children:o.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Appairer cet appareil"}),o.jsx("p",{className:"text-sm text-muted",children:"Saisissez le code affiché par le serveur IdeA pour connecter ce navigateur."})]}),o.jsx(qt,{label:"Code d'appairage",hint:"8 caractères : chiffres et lettres A-F",children:({id:w,describedBy:v})=>o.jsx(ce,{id:w,"aria-describedby":v,value:n,onChange:_=>r(_.target.value),placeholder:"p. ex. AB12CD34",autoFocus:!0,autoComplete:"one-time-code",inputMode:"text",autoCapitalize:"characters",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!m})}),o.jsx(qt,{label:"Nom de cet appareil",hint:"Pour le reconnaître dans la liste des appareils.",error:p??void 0,children:({id:w,describedBy:v})=>o.jsx(ce,{id:w,"aria-describedby":v,value:s,onChange:_=>i(_.target.value),maxLength:vp,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!p})}),m&&o.jsx("p",{role:"alert","data-testid":"pairing-error",className:"text-sm text-danger",children:m}),o.jsx(M,{type:"submit",disabled:c||!f,children:c?"Appairage…":"Appairer"})]})})})}const zB=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Ctrl-C",aria:"Ctrl-C (interrompre)",data:""},{label:"Ctrl-D",aria:"Ctrl-D (fin de saisie)",data:""},{label:"↑",aria:"Flèche haut",data:"\x1B[A"},{label:"↓",aria:"Flèche bas",data:"\x1B[B"},{label:"←",aria:"Flèche gauche",data:"\x1B[D"},{label:"→",aria:"Flèche droite",data:"\x1B[C"}];function FB({api:e,className:t}){return o.jsx("div",{role:"toolbar","aria-label":"Touches du terminal","data-testid":"terminal-key-bar",className:U("flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-raised/40 px-2 py-1.5",t),children:zB.map(n=>o.jsx(M,{size:"sm",variant:"secondary","aria-label":n.aria??n.label,disabled:!e,onPointerDown:r=>r.preventDefault(),onClick:()=>{e?.send(n.data),e?.focus()},className:"min-h-11 shrink-0 font-mono",children:n.label},n.label))})}function $B({projectId:e,agentId:t,cwd:n,nodeId:r,refitSignal:s}){const{agent:i}=fe(),[l,a]=g.useState(null),[c,u]=g.useState(null),h=g.useCallback((f,p)=>i.launchAgent(e,t,r?{...f,nodeId:r}:f,p),[i,e,t,r]),d=g.useCallback((f,p)=>i.reattach(f,p),[i]);return o.jsxs("div",{"data-testid":"web-agent-cell",className:"flex h-[60dvh] min-h-64 w-full flex-col overflow-hidden rounded-md border border-border sm:h-80",children:[o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(hp,{cwd:n,agentMode:!0,open:h,reattach:d,sessionId:l,onSessionId:a,onReady:u,refitSignal:s})}),o.jsx(FB,{api:c})]})}function WB(e){g.useEffect(()=>{const t=Bh();if(!t)return;let n=t.getConnectionState();return t.onConnectionStateChange(r=>{r==="connected"&&n==="reconnecting"&&e(),n=r})},[e])}function HB(){const[e,t]=g.useState(()=>Bh()?.getConnectionState()??null);return g.useEffect(()=>{const n=Bh();if(n)return t(n.getConnectionState()),n.onConnectionStateChange(t)},[]),e}function Mc(e){switch(e){case"open":return"Ouvert";case"inProgress":return"En cours";case"QA":return"QA";case"closed":return"Fermé"}}function lo(e){switch(e){case"low":return"Faible";case"medium":return"Moyenne";case"high":return"Haute";case"critical":return"Critique"}}function Vv(e){switch(e){case"relatesTo":return"en relation avec";case"blocks":return"bloque";case"blockedBy":return"bloqué par";case"duplicates":return"duplique";case"dependsOn":return"dépend de"}}function UB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function qB(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function c0(e){return U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function Wp({status:e}){return o.jsx("span",{className:c0(UB(e)),children:Mc(e)})}function Hp({priority:e}){return o.jsx("span",{className:c0(qB(e)),children:lo(e)})}const Kv=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),VB=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function KB({sprints:e,busy:t,error:n,onCancel:r,onCreate:s}){const[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState("medium"),[d,f]=g.useState("");async function p(m){m.preventDefault();const x=i.trim();x&&await s({title:x,priority:u,...a.trim()?{description:a.trim()}:{}},d||null)}return o.jsxs(ke,{title:"Nouveau ticket",actions:o.jsx(M,{size:"sm",variant:"ghost",onClick:r,children:"Annuler"}),children:[n&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n}),o.jsxs("form",{onSubmit:p,className:"flex flex-col gap-3",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),o.jsx(ce,{"aria-label":"Titre",value:i,onChange:m=>l(m.target.value),disabled:t,autoFocus:!0})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Priorité"}),o.jsx("select",{"aria-label":"Priorité",className:Kv,value:u,disabled:t,onChange:m=>h(m.target.value),children:Ni.map(m=>o.jsx("option",{value:m,children:lo(m)},m))})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Sprint"}),o.jsxs("select",{"aria-label":"Sprint",className:Kv,value:d,disabled:t,onChange:m=>f(m.target.value),children:[o.jsx("option",{value:"",children:"Sans sprint"}),e.map(m=>o.jsx("option",{value:m.id,children:m.name},m.id))]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),o.jsx("textarea",{"aria-label":"Description",className:U(VB,"min-h-20"),value:a,onChange:m=>c(m.target.value),disabled:t})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx(M,{type:"button",variant:"ghost",size:"sm",disabled:t,onClick:r,children:"Annuler"}),o.jsx(M,{type:"submit",size:"sm",disabled:!i.trim()||t,loading:t,children:"Créer"})]})]})]})}function u0({title:e,body:t,confirmLabel:n,busy:r=!1,onConfirm:s,onCancel:i}){const l=g.useRef(null);return g.useEffect(()=>{l.current?.focus()},[]),g.useEffect(()=>{function a(c){c.key==="Escape"&&i()}return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[i]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.toast},children:o.jsxs("div",{role:"alertdialog","aria-modal":"true","aria-label":e,onClick:a=>a.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:l,size:"sm",variant:"ghost",disabled:r,onClick:i,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger",loading:r,disabled:r,onClick:()=>void s(),children:n})]})]})})}function d0({projectId:e,title:t,confirmLabel:n="Ajouter",selectionMode:r,excludeRefs:s,onSelect:i,onClose:l}){const a=Rc(e,{excludeRefs:s}),c=r==="multi",[u,h]=g.useState(()=>new Set),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useRef(null);g.useEffect(()=>{x.current?.focus()},[]),g.useEffect(()=>{function b(C){C.key==="Escape"&&l()}return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[l]);function w(b){return b&&typeof b=="object"&&"message"in b?String(b.message):String(b)}function v(b){h(C=>{const S=new Set(C);return S.has(b)?S.delete(b):S.add(b),S})}async function _(b){if(!d){f(!0),m(null);try{i(await a.resolve(b)),l()}catch(C){m(w(C)),f(!1)}}}async function y(){if(!(d||u.size===0)){f(!0),m(null);try{const b=await Promise.all(Array.from(u).map(C=>a.resolve(C)));i(b),l()}catch(b){m(w(b)),f(!1)}}}return o.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":t,style:{zIndex:Sn.floatingWindowNested},children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[o.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:t}),o.jsx(M,{ref:x,size:"sm",variant:"ghost",onClick:l,children:"Fermer"})]}),o.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:o.jsx(ce,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:a.text,onChange:b=>a.setText(b.target.value),autoFocus:!0})}),(a.error||p)&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??a.error}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[a.busy&&a.rows.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Chargement des tickets…"})]}):a.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:a.rows.map(b=>{const C=u.has(b.ref);return o.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:o.jsxs("button",{type:"button","aria-label":`${b.ref}, ${b.title}`,...c?{role:"checkbox","aria-checked":C}:{},disabled:d,onClick:()=>c?v(b.ref):void _(b.ref),className:U("flex min-h-[40px] w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-60",c&&C&&"bg-raised"),children:[c&&o.jsx("span",{"aria-hidden":"true",className:U("flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",C?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:b.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:b.title}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(Wp,{status:b.status}),o.jsx(Hp,{priority:b.priority})]})]})},b.ref)})}),a.hasMore&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:a.busy,onClick:()=>a.loadMore(),children:"Charger plus"})})]}),c&&o.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]",children:[o.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[u.size," sélectionné",u.size>1?"s":""]}),o.jsxs(M,{size:"sm",loading:d,disabled:u.size===0||d,onClick:()=>void y(),children:[n," ",u.size>0?`(${u.size})`:""]})]})]})}const Fs=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Gv=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function $s({title:e,defaultOpen:t,children:n}){const[r,s]=g.useState(t);return o.jsxs("section",{className:"border-b border-border py-2 last:border-b-0",children:[o.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>s(i=>!i),className:"flex min-h-[32px] w-full items-center justify-between text-left text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{"aria-hidden":"true",children:r?"▾":"▸"})]}),r&&o.jsx("div",{className:"mt-2 flex flex-col gap-2",children:n})]})}function GB({projectId:e,ticketRef:t,nameOf:n,assignableAgents:r,sprints:s,onBack:i,onOpenRef:l}){const a=l0(e,t),c=a.ticket,[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState("relatesTo"),[v,_]=g.useState(""),[y,b]=g.useState(!1),[C,S]=g.useState(!1),[N,L]=g.useState(!1);g.useEffect(()=>{a.deleted&&i()},[a.deleted,i]);const A=a.reloadCount,k=g.useRef(-1),D=g.useRef(null);g.useEffect(()=>{if(!c||k.current===A)return;k.current=A;const P=c.carnet??"",z=D.current;z===null||a.conflict?(h(c.title),f(c.description),m(P)):(h(se=>se===z.title?c.title:se),f(se=>se===z.description?c.description:se),m(se=>se===z.carnet?P:se)),D.current={title:c.title,description:c.description,carnet:P}},[c,A,a.conflict]);const R=!!c&&(u!==c.title||d!==c.description),E=!!c&&p!==(c.carnet??""),O=R||E,I=r.filter(P=>!c?.assignedAgentIds.includes(P.id));function W(){O?S(!0):i()}async function G(){let P=!0;R&&(P=await a.updateFields({title:u,description:d})&&P),P&&E&&(P=await a.saveCarnet(p)&&P),S(!1),P&&i()}return o.jsxs(ke,{className:"flex flex-col",flush:!0,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:W,children:"← Tickets"}),o.jsx("code",{className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:t})]}),a.conflict&&o.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-4 py-2 text-sm text-warning",children:"Ce ticket a été modifié ailleurs et rechargé. Réappliquez votre modification."}),a.error&&!a.conflict&&o.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:a.error}),a.busy&&!c?o.jsxs("div",{className:"flex items-center gap-2 px-4 py-5 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Chargement du ticket…"})]}):c?o.jsxs("div",{className:"flex flex-col px-4 py-2",children:[o.jsxs("div",{className:"flex flex-col gap-1 border-b border-border pb-3",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),o.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[o.jsx(Wp,{status:c.status}),o.jsx(Hp,{priority:c.priority}),c.sprintId&&o.jsxs("span",{children:["· ",s.find(P=>P.id===c.sprintId)?.name??"Sprint"]})]})]}),o.jsxs($s,{title:"Résumé",defaultOpen:!0,children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),o.jsx("input",{"aria-label":"Titre",className:U(Fs,"w-full"),value:u,onChange:P=>h(P.target.value),disabled:a.busy})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),o.jsx("textarea",{"aria-label":"Description",className:U(Gv,"min-h-24"),value:d,onChange:P=>f(P.target.value),disabled:a.busy})]}),o.jsx("div",{children:o.jsx(M,{size:"sm",disabled:!R||a.busy,loading:a.busy&&R,onClick:()=>void a.updateFields({title:u,description:d}),children:"Enregistrer"})})]}),o.jsxs($s,{title:"Statut et priorité",defaultOpen:!0,children:[o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Statut"}),o.jsx("select",{"aria-label":"Statut",className:Fs,value:c.status,disabled:a.busy,onChange:P=>void a.updateFields({status:P.target.value}),children:Lc.map(P=>o.jsx("option",{value:P,children:Mc(P)},P))})]}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Priorité"}),o.jsx("select",{"aria-label":"Priorité",className:Fs,value:c.priority,disabled:a.busy,onChange:P=>void a.updateFields({priority:P.target.value}),children:Ni.map(P=>o.jsx("option",{value:P,children:lo(P)},P))})]}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Sprint"}),o.jsxs("select",{"aria-label":"Sprint",className:Fs,value:c.sprintId??"",disabled:a.busy,onChange:P=>void a.setSprint(P.target.value||null),children:[o.jsx("option",{value:"",children:"Sans sprint"}),s.map(P=>o.jsx("option",{value:P.id,children:P.name},P.id))]})]}),a.busy&&o.jsx(Me,{size:12})]}),o.jsxs($s,{title:"Carnet",defaultOpen:!0,children:[o.jsx("textarea",{"aria-label":"Carnet",className:U(Gv,"min-h-32 font-mono"),value:p,onChange:P=>m(P.target.value),disabled:a.busy}),o.jsx("div",{children:o.jsx(M,{size:"sm",disabled:!E||a.busy,loading:a.busy&&E,onClick:()=>void a.saveCarnet(p),children:"Enregistrer le carnet"})})]}),o.jsxs($s,{title:"Agents assignés",defaultOpen:!1,children:[c.assignedAgentIds.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun agent assigné."}):o.jsx("ul",{className:"flex flex-wrap gap-2",children:c.assignedAgentIds.map(P=>o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[n(P),o.jsx("button",{type:"button","aria-label":`Désassigner ${n(P)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:a.busy,onClick:()=>void a.assign(P,!1),children:"×"})]},P))}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("select",{"aria-label":"Assigner un agent",className:Fs,value:v,disabled:a.busy||I.length===0,onChange:P=>_(P.target.value),children:[o.jsx("option",{value:"",children:I.length===0?"Aucun autre agent":"Choisir un agent…"}),I.map(P=>o.jsx("option",{value:P.id,children:P.name},P.id))]}),o.jsx(M,{size:"sm",disabled:!v||a.busy,onClick:async()=>{await a.assign(v,!0)&&_("")},children:"Assigner"})]})]}),o.jsxs($s,{title:"Liens",defaultOpen:!1,children:[c.links.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun ticket lié."}):o.jsx("ul",{className:"flex flex-col gap-1",children:c.links.map(P=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"text-xs text-muted",children:Vv(P.kind)}),o.jsx("button",{type:"button",className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content hover:text-primary",onClick:()=>l(P.targetRef),children:P.targetRef}),o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:()=>void a.unlink(P.targetRef,P.kind),children:"Retirer"})]},`${P.kind}-${P.targetRef}`))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("select",{"aria-label":"Type de lien",className:Fs,value:x,disabled:a.busy,onChange:P=>w(P.target.value),children:n0.map(P=>o.jsx("option",{value:P,children:Vv(P)},P))}),o.jsx(M,{size:"sm",disabled:a.busy,onClick:()=>L(!0),children:"+ Lier"})]})]}),o.jsxs($s,{title:"Zone dangereuse",defaultOpen:!1,children:[o.jsxs("p",{className:"text-xs text-muted",children:["Le ticket ",t," sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés."]}),o.jsx("div",{children:o.jsx(M,{size:"sm",variant:"danger",disabled:a.busy,onClick:()=>b(!0),children:"Supprimer"})})]})]}):o.jsx("p",{className:"px-4 py-5 text-sm text-muted",children:"Ticket introuvable."}),N&&c&&o.jsx(d0,{projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...c.links.map(P=>P.targetRef)],onSelect:P=>{const z=Array.isArray(P)?P[0]:P;z&&a.link(z.ref,x)},onClose:()=>L(!1)}),y&&o.jsx(u0,{title:"Supprimer ce ticket ?",body:`Le ticket ${t} sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés.`,confirmLabel:"Supprimer",busy:a.busy,onCancel:()=>b(!1),onConfirm:async()=>{await a.remove()&&b(!1)}}),C&&o.jsx("div",{role:"alertdialog","aria-modal":"true","aria-label":"Modifications non enregistrées",className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",children:o.jsxs("div",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:"Des modifications ne sont pas enregistrées."}),o.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:()=>S(!1),children:"Continuer l'édition"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:i,children:"Ignorer"}),o.jsx(M,{size:"sm",loading:a.busy,disabled:a.busy,onClick:()=>void G(),children:"Enregistrer et quitter"})]})]})})]})}function YB(e){const t=eo(e),n=g.useMemo(()=>(t.state?.agents??[]).map(i=>({id:i.agentId,name:i.name})),[t.state]),r=g.useMemo(()=>new Map(n.map(i=>[i.id,i.name])),[n]);return{agents:n,nameOf:i=>r.get(i)??`${i.slice(0,8)}…`,loaded:t.state!==null}}const Go=U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Yv={number:"Numéro",priority:"Priorité",status:"Statut",title:"Titre"};function XB({projectId:e,focusSprintId:t=null}){const n=zp(e),r=YB(e),[s,i]=g.useState({type:"list"}),[l,a]=g.useState(t);if(s.type==="detail")return o.jsx(GB,{projectId:e,ticketRef:s.ref,nameOf:r.nameOf,assignableAgents:r.agents,sprints:n.sprints,onBack:()=>i({type:"list"}),onOpenRef:x=>i({type:"detail",ref:x})},s.ref);if(s.type==="create")return o.jsx(KB,{sprints:n.sprints,busy:n.busy,error:n.error,onCancel:()=>i({type:"list"}),onCreate:async(x,w)=>{const v=await n.create(x);v&&(w&&await n.assignSprint(v.ref,w),i({type:"detail",ref:v.ref}))}});const c=n.list?.items??[],u=!!n.query.text||(n.query.statuses?.length??0)>0||(n.query.priorities?.length??0)>0||!!n.query.assignedAgentId||!!l,h=new Set(n.sprints.map(x=>x.id)),f=(l?n.sprints.filter(x=>x.id===l):n.sprints).map(x=>({sprint:x,tickets:c.filter(w=>w.sprintId===x.id)})).filter(x=>x.tickets.length>0),p=l?[]:c.filter(x=>!x.sprintId||!h.has(x.sprintId));function m(){n.setQuery({}),a(null)}return o.jsxs(ke,{className:"flex flex-col",title:"Tickets",actions:o.jsx(M,{size:"sm",onClick:()=>i({type:"create"}),children:"+ Ticket"}),children:[n.error&&o.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[o.jsx("span",{children:n.error}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),children:"Réessayer"})]}),l&&o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 rounded-md border border-border bg-raised/50 px-3 py-2 text-xs text-muted",children:[o.jsxs("span",{children:["Filtré sur le sprint « ",n.sprints.find(x=>x.id===l)?.name??l," »"]}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>a(null),children:"Voir tous les tickets"})]}),o.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:n.query.text??"",onChange:x=>n.setQuery({...n.query,text:x.target.value||void 0})}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("select",{"aria-label":"Filtrer par statut",className:Go,value:n.query.statuses?.[0]??"",onChange:x=>n.setQuery({...n.query,statuses:x.target.value?[x.target.value]:void 0}),children:[o.jsx("option",{value:"",children:"Tous les statuts"}),Lc.map(x=>o.jsx("option",{value:x,children:Mc(x)},x))]}),o.jsxs("select",{"aria-label":"Filtrer par priorité",className:Go,value:n.query.priorities?.[0]??"",onChange:x=>n.setQuery({...n.query,priorities:x.target.value?[x.target.value]:void 0}),children:[o.jsx("option",{value:"",children:"Toutes les priorités"}),Ni.map(x=>o.jsx("option",{value:x,children:lo(x)},x))]}),o.jsxs("select",{"aria-label":"Filtrer par agent assigné",className:Go,value:n.query.assignedAgentId??"",onChange:x=>n.setQuery({...n.query,assignedAgentId:x.target.value||void 0}),children:[o.jsx("option",{value:"",children:"Tous les agents"}),r.agents.map(x=>o.jsx("option",{value:x.id,children:x.name},x.id))]}),o.jsxs("select",{"aria-label":"Trier les tickets",className:Go,value:n.query.sort?.field??"",onChange:x=>{const w=x.target.value,{sort:v,..._}=n.query;n.setQuery(w?{..._,sort:{field:w,direction:"asc"}}:_)},children:[o.jsx("option",{value:"",children:"Tri par défaut"}),Object.keys(Yv).map(x=>o.jsx("option",{value:x,children:Yv[x]},x))]})]})]}),n.busy&&n.list===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des tickets…"]}):c.length===0&&!u?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket dans ce projet."}),o.jsx(M,{size:"sm",onClick:()=>i({type:"create"}),children:"Créer un ticket"})]}):c.length===0?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond aux filtres."}),o.jsx(M,{size:"sm",variant:"ghost",onClick:m,children:"Réinitialiser les filtres"})]}):o.jsxs("div",{className:"flex flex-col gap-4","data-testid":"web-ticket-list",children:[f.map(x=>o.jsx(Xv,{heading:x.sprint.name,tickets:x.tickets,sprints:n.sprints,nameOf:r.nameOf,onOpen:w=>i({type:"detail",ref:w})},x.sprint.id)),p.length>0&&o.jsx(Xv,{heading:"Sans sprint",tickets:p,sprints:n.sprints,nameOf:r.nameOf,onOpen:x=>i({type:"detail",ref:x})})]}),n.list?.nextCursor&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Charger plus"})})]})}function Xv({heading:e,tickets:t,sprints:n,nameOf:r,onOpen:s}){const i=l=>l?n.find(a=>a.id===l)?.name:void 0;return o.jsxs("section",{"aria-label":`Tickets — ${e}`,children:[o.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t.length})]}),o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(l=>{const a=i(l.sprintId),c=l.assignedAgentIds.map(r).join(", ");return o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>s(l.ref),"aria-label":`${l.ref}, ${l.title}, statut ${Mc(l.status)}, priorité ${lo(l.priority)}`,className:"flex w-full min-w-0 flex-col items-start gap-0.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-raised",children:[o.jsxs("span",{className:"flex w-full min-w-0 items-baseline gap-2",children:[o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:l.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:l.title})]}),o.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[o.jsx(Wp,{status:l.status}),o.jsx(Hp,{priority:l.priority}),a&&o.jsxs("span",{children:["· ",a]}),c&&o.jsxs("span",{children:["· ",c]})]})]})},l.ref)})})]})}function QB({projectId:e,onViewSprintTickets:t}){const n=zp(e),r=Rc(e,{refreshOnEvents:!0}),[s,i]=g.useState(!1),[l,a]=g.useState(""),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState(null),[m,x]=g.useState(null),w=[...n.sprints].sort((_,y)=>_.order-y.order);async function v(_){_.preventDefault();const y=l.trim();if(!y)return;await n.createSprint(y)&&(a(""),i(!1))}return o.jsxs(ke,{title:"Sprints",actions:o.jsx(M,{size:"sm",onClick:()=>i(_=>!_),children:"+ Sprint"}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),s&&o.jsxs("form",{onSubmit:v,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Nom du sprint"}),o.jsx(ce,{"aria-label":"Nom du sprint",value:l,onChange:_=>a(_.target.value),autoFocus:!0})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(!1),children:"Annuler"}),o.jsx(M,{type:"submit",size:"sm",disabled:!l.trim()||n.busy,children:"Créer"})]})]}),n.busy&&n.sprints.length===0?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des sprints…"]}):w.length===0?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun sprint."}),o.jsx(M,{size:"sm",onClick:()=>i(!0),children:"Créer un sprint"})]}):o.jsx("ul",{className:"flex flex-col gap-3",children:w.map((_,y)=>o.jsx(JB,{sprint:_,index:y,lastIndex:w.length-1,tickets:r.rows.filter(b=>b.sprintId===_.id),vm:n,renaming:c===_.id,renameDraft:h,onStartRename:()=>{u(_.id),d(_.name)},onRenameDraftChange:d,onCancelRename:()=>u(null),onSaveRename:async()=>{await n.renameSprint(_.id,h.trim())&&u(null)},onViewTickets:()=>t(_.id),onAddTickets:()=>x({id:_.id,name:_.name}),onRequestDelete:()=>p({id:_.id,name:_.name})},_.id))}),f&&o.jsx(u0,{title:`Supprimer le sprint « ${f.name} » ?`,body:"Les tickets de ce sprint seront conservés et passeront en « Sans sprint ».",confirmLabel:"Supprimer",busy:n.busy,onCancel:()=>p(null),onConfirm:async()=>{await n.deleteSprint(f.id),p(null)}}),m&&o.jsx(d0,{projectId:e,title:`Ajouter des tickets au sprint « ${m.name} »`,confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:r.rows.filter(_=>_.sprintId===m.id).map(_=>_.ref),onSelect:_=>{const y=Array.isArray(_)?_:[_];for(const b of y)n.assignSprint(b.ref,m.id)},onClose:()=>x(null)})]})}function JB({sprint:e,index:t,lastIndex:n,tickets:r,vm:s,renaming:i,renameDraft:l,onStartRename:a,onRenameDraftChange:c,onCancelRename:u,onSaveRename:h,onViewTickets:d,onAddTickets:f,onRequestDelete:p}){return o.jsxs("li",{className:"rounded-md border border-border p-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",e.order]}),!i&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e.name})]}),i?o.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":`Renommer le sprint ${e.name}`,value:l,onChange:m=>c(m.target.value),disabled:s.busy}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:u,children:"Annuler"}),o.jsx(M,{size:"sm",disabled:s.busy||!l.trim()||l.trim()===e.name,onClick:()=>void h(),children:"Enregistrer"})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"mt-1 text-xs text-muted",children:[e.ticketCount," ticket",e.ticketCount>1?"s":""]}),r.length>0&&o.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:r.map(m=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:m.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:m.title}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Retirer ${m.ref} du sprint ${e.name}`,disabled:s.busy,onClick:()=>void s.assignSprint(m.ref,null),children:"Retirer du sprint"})]},m.ref))}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:d,children:"Voir tickets"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:f,children:"Ajouter tickets"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Renommer ${e.name}`,disabled:s.busy,onClick:a,children:"Renommer"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Monter ${e.name}`,disabled:s.busy||t===0,onClick:()=>void s.moveSprint(e.id,"up"),children:"Monter"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Descendre ${e.name}`,disabled:s.busy||t===n,onClick:()=>void s.moveSprint(e.id,"down"),children:"Descendre"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Supprimer ${e.name}`,disabled:s.busy,className:"text-danger hover:text-danger",onClick:p,children:"Supprimer"})]})]})]})}function ZB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function e4({projects:e,openId:t,onOpen:n,onCreate:r,onRefresh:s}){const[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState(!1),[d,f]=g.useState(null),p=i.trim().length>0&&a.trim().length>0&&!u;async function m(x){if(x.preventDefault(),!!p){h(!0),f(null);try{const w=await r(i.trim(),a.trim());l(""),c(""),n(w.id)}catch(w){f(ZB(w))}finally{h(!1)}}}return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Projets"}),o.jsx(M,{variant:"ghost",size:"sm",onClick:s,children:"Rafraîchir"})]}),o.jsx(ke,{title:"Nouveau projet",children:o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"Nom du projet",placeholder:"Nom du projet",value:i,onChange:x=>l(x.target.value)}),o.jsx(ce,{"aria-label":"Chemin du projet",placeholder:"/chemin/absolu/du/projet",value:a,onChange:x=>c(x.target.value)}),o.jsx("p",{className:"text-xs text-muted",children:"Saisir un chemin absolu accessible depuis le serveur IdeA."}),d&&o.jsx("p",{role:"alert",className:"text-xs text-danger",children:d}),o.jsx(M,{type:"submit",variant:"primary",disabled:!p,loading:u,children:"Créer le projet"})]})}),e===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des projets…"]}):e.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun projet."}):o.jsx("ul",{className:"flex flex-col gap-2","data-testid":"web-project-list",children:e.map(x=>o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>n(x.id),"aria-pressed":t===x.id,className:"flex w-full flex-col items-start rounded-md border border-border bg-raised px-3 py-2 text-left transition-colors hover:border-primary aria-pressed:border-primary",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:x.name}),o.jsx("span",{className:"text-xs text-faint",children:x.root})]})},x.id))})]})}function h0({title:e,entries:t,note:n,onClose:r}){const s=g.useRef(null);return g.useEffect(()=>{s.current?.focus()},[]),g.useEffect(()=>{function i(l){l.key==="Escape"&&r()}return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[r]),o.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":e,style:{zIndex:Sn.floatingWindowNested},children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[o.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:e}),o.jsx(M,{ref:s,size:"sm",variant:"ghost",onClick:r,children:"Fermer"})]}),n&&o.jsx("p",{className:"shrink-0 border-b border-border px-4 py-2 text-xs text-muted",children:n}),o.jsx("ul",{className:"min-h-0 flex-1 overflow-auto px-2 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:t.map(i=>o.jsx("li",{children:o.jsxs("button",{type:"button",disabled:i.disabled,title:i.hint,"aria-current":i.active?"true":void 0,onClick:()=>{i.disabled||i.onSelect()},className:U("flex min-h-[44px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-50 disabled:hover:bg-transparent",i.active&&"bg-raised font-medium text-content"),children:[o.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-primary",children:i.active?"●":""}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:i.label}),i.secondaryLabel&&o.jsx("span",{className:"shrink-0 text-xs text-muted",children:i.secondaryLabel})]})},i.id))})]})}function va(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const t4=["context","work","tickets","sprints","agents","templates","skills","permissions","memory","git","projects"],Qv={context:"Contexte projet",work:"Travail",tickets:"Tickets",sprints:"Sprints",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Mémoire",git:"Git",projects:"Projets"};function n4(){const{project:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState("projects"),[u,h]=g.useState(null),d=t?.find(x=>x.id===i)?.root??null,f=g.useCallback(async()=>{s(null);try{n(await e.listProjects())}catch(x){s(va(x))}},[e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async x=>{s(null),l(null);try{await e.openProject(x),l(x),c("work")}catch(w){s(va(w))}},[e]),m=g.useCallback(async(x,w)=>{s(null);try{const v=await e.createProject(x,w);return await f(),v}catch(v){throw s(va(v)),v}},[e,f]);return o.jsxs("div",{"data-testid":"web-workspace",className:"flex h-full flex-col gap-4 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:[o.jsx(i4,{}),o.jsx(r4,{activePanel:a,hasProject:!!i,onSelect:c}),r&&o.jsx(ke,{className:"border-danger/40",children:o.jsx("p",{className:"text-sm text-danger",children:r})}),a==="projects"?o.jsx(e4,{projects:t,openId:i,onOpen:x=>void p(x),onCreate:m,onRefresh:()=>void f()}):i?o.jsx(s4,{panel:a,projectId:i,root:d,focusSprintId:u,onViewSprintTickets:x=>{h(x),c("tickets")}}):o.jsx("p",{className:"text-sm text-muted",children:"Ouvrir un projet pour utiliser ce panneau."})]})}function r4({activePanel:e,hasProject:t,onSelect:n}){const[r,s]=g.useState(!1);return o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>s(!0),children:["Panneaux : ",Qv[e]]}),r&&o.jsx(h0,{title:"Panneaux",note:t?void 0:"Ouvrir un projet pour utiliser ce panneau.",onClose:()=>s(!1),entries:t4.map(i=>{const l=i!=="projects"&&!t;return{id:i,label:Qv[i],active:i===e,disabled:l,hint:l?"Ouvrir un projet pour utiliser ce panneau.":void 0,onSelect:()=>{n(i),s(!1)}}})})]})}function s4({panel:e,projectId:t,root:n,focusSprintId:r,onViewSprintTickets:s}){switch(e){case"context":return o.jsx(o0,{projectId:t});case"work":return o.jsx(l4,{projectId:t,root:n});case"tickets":return o.jsx(XB,{projectId:t,focusSprintId:r});case"sprints":return o.jsx(QB,{projectId:t,onViewSprintTickets:s});case"agents":return o.jsx(_w,{projectId:t,projectRoot:n??""});case"templates":return o.jsx($S,{projectId:t});case"skills":return o.jsx(WS,{projectId:t});case"permissions":return o.jsx(XS,{projectId:t});case"memory":return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(KS,{projectId:t}),o.jsx(VS,{})]});case"git":return o.jsx(Dw,{projectId:t})}}function i4(){return HB()!=="reconnecting"?null:o.jsxs("div",{role:"status","data-testid":"web-reconnect-banner",className:"flex items-center gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:[o.jsx(Me,{size:12}),"Connexion perdue — reconnexion en cours…"]})}function l4({projectId:e,root:t}){const n=eo(e);WB(n.refresh);const[r,s]=g.useState(null),[i,l]=g.useState(0),a=g.useCallback(()=>l(f=>f+1),[]),c=n.state?.agents??[],[u,h]=g.useState(new Set);g.useEffect(()=>{const f=new Set(c.filter(p=>(p.backgroundTasks??[]).length>0).map(p=>p.agentId));h(p=>{const m=new Set([...p].filter(x=>f.has(x)));return m.size===p.size?p:m})},[c]);const d=g.useCallback(f=>{h(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return o.jsxs(ke,{className:"mt-2",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[o.jsxs("h3",{className:"text-sm font-semibold",children:["État live",o.jsx("span",{className:"ml-2 rounded bg-canvas px-1.5 py-0.5 text-[0.6rem] uppercase text-muted",children:"read-only"})]}),o.jsx(M,{variant:"ghost",size:"sm",loading:n.busy,onClick:()=>void n.refresh(),children:"Rafraîchir"})]}),n.error&&o.jsx("p",{role:"alert",className:"mb-2 text-xs text-danger",children:n.error}),n.busy&&n.state===null?o.jsx("p",{className:"text-xs text-muted",children:"Chargement de l'état…"}):c.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun agent actif."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"web-workstate",children:c.map(f=>o.jsx(o4,{agent:f,open:r===f.agentId,onToggleOpen:()=>{s(p=>p===f.agentId?null:f.agentId),a()},onRefresh:n.refresh,bgExpanded:u.has(f.agentId),onToggleBgExpanded:()=>d(f.agentId)},f.agentId))}),t&&r&&o.jsxs("div",{className:"mt-3",children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-muted",children:"Agent"}),o.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{s(null),a()},children:"Fermer"})]}),o.jsx($B,{projectId:e,agentId:r,cwd:t,refitSignal:i},r)]})]})}function o4({agent:e,open:t,onToggleOpen:n,onRefresh:r,bgExpanded:s,onToggleBgExpanded:i}){const l=e.live!==void 0,a=e.busy?.state==="busy",c=[...e.inbox??[]].sort((h,d)=>h.createdAtMs-d.createdAtMs),u=[...e.backgroundTasks??[]].sort((h,d)=>d.updatedAtMs-h.updatedAtMs||h.taskId.localeCompare(d.taskId));return o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between sm:gap-2",children:[o.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:e.name}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-xs",children:[o.jsx("span",{className:U("rounded-full px-2 py-0.5 font-medium",l?"bg-success/15 text-success":"bg-raised text-muted"),children:l?"Live":"Offline"}),o.jsx("span",{className:U("rounded-full px-2 py-0.5 font-medium",a?"bg-warning/15 text-warning":"bg-raised text-muted"),children:a?"Busy":"Idle"}),o.jsx(M,{variant:"ghost",size:"sm","aria-pressed":t,onClick:n,children:t?"Fermer":"Ouvrir"})]})]}),c.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),o.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:c.map(h=>o.jsxs("li",{className:"flex min-w-0 items-start gap-2 text-xs text-muted",children:[o.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium",children:h.kind}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:h.body})]},h.id))})]}),u.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsxs("button",{type:"button","aria-expanded":s,"aria-controls":`web-bg-tasks-${e.agentId}`,"aria-label":s?`Masquer les background tasks de ${e.name}`:`Afficher les background tasks de ${e.name}`,onClick:i,className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-faint hover:text-muted",children:[o.jsx("span",{"aria-hidden":"true",children:s?"▾":"▸"}),"Background tasks",o.jsx("span",{className:"rounded-full bg-raised px-1.5 py-0.5 font-medium normal-case tracking-normal text-muted",children:u.length})]}),s&&o.jsx("ul",{id:`web-bg-tasks-${e.agentId}`,"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:u.map(h=>o.jsx(u4,{task:h,onRefresh:r},h.taskId))})]})]})}const a4={running:"Running",completed:"Completed",failed:"Failed",cancelled:"Cancelled",pending:"Pending",delivered:"Delivered"};function c4(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function u4({task:e,onRefresh:t}){const{workState:n}=fe(),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=e.status==="running"||e.status==="pending",c=e.status==="failed"||e.status==="cancelled";async function u(h){s(!0),l(null);try{await h(e.taskId),await t()}catch(d){l(va(d))}finally{s(!1)}}return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:U("shrink-0 rounded-full px-1.5 py-0.5 font-medium",c4(e.status)),children:a4[e.status]}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:e.kind})]}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:!a||r,loading:r,onClick:()=>void u(h=>n.cancelBackgroundTask(h)),children:"Cancel"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!c||r,loading:r,onClick:()=>void u(h=>n.retryBackgroundTask(h)),children:"Retry"})]})]}),i&&o.jsx("p",{role:"alert",className:"mt-1 text-danger",children:i})]})}const Yo={aiProfiles:"Profils IA",devices:"Appareils"};function d4({session:e}={}){const t=e??uw(),[n,r]=g.useState(()=>t.isPaired()),[s,i]=g.useState(!1),[l,a]=g.useState(null),[c,u]=g.useState(!1);g.useEffect(()=>t.onUnauthorized(()=>{a(null),u(!1),r(!1)}),[t]);async function h(){if(!s){i(!0);try{await t.logout()}finally{ox(),i(!1),a(null),u(!1),r(!1)}}}const d=g.useCallback(()=>{t.forget(),ox(),a(null),u(!1),r(!1)},[t]);return o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{"data-testid":"web-header",className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:px-6",children:[o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("h1",{className:"text-base font-semibold tracking-tight sm:text-lg",children:"IdeA"}),o.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"web"})]}),n&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(M,{variant:"ghost",size:"sm","aria-pressed":c,onClick:()=>u(!0),children:"Paramètres"}),o.jsx(M,{variant:"ghost",size:"sm",loading:s,onClick:()=>void h(),children:"Se déconnecter"})]})]}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:n?l==="aiProfiles"?o.jsx(Jv,{title:Yo.aiProfiles,onBack:()=>a(null),children:o.jsx(jw,{})}):l==="devices"?o.jsx(Jv,{title:Yo.devices,onBack:()=>a(null),children:o.jsx(Pw,{onSessionEnded:d})}):o.jsx(n4,{}):o.jsx(BB,{session:t,onPaired:()=>r(!0)})}),c&&o.jsx(h0,{title:"Paramètres",onClose:()=>u(!1),entries:[{id:"aiProfiles",label:Yo.aiProfiles,active:l==="aiProfiles",onSelect:()=>{a("aiProfiles"),u(!1)}},{id:"devices",label:Yo.devices,active:l==="devices",onSelect:()=>{a("devices"),u(!1)}},{id:"deployment",label:"Déploiement",active:!1,disabled:!0,secondaryLabel:"Desktop uniquement",hint:"Desktop uniquement",onSelect:()=>{}}]})]})}function Jv({title:e,onBack:t,children:n}){return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2 pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))]",children:[o.jsx(M,{variant:"ghost",size:"sm",onClick:t,children:"← Retour"}),o.jsx("span",{className:"text-sm font-medium text-content",children:e})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:o.jsx("div",{className:"mx-auto w-full max-w-xl",children:n})})]})}const f0=document.getElementById("root");if(!f0)throw new Error("missing #root element");const Zv=MB(window.location.search);window.__IDEA_TRANSPORT__="http";const h4=hw()==="http";sd.createRoot(f0).render(o.jsx(T0.StrictMode,{children:o.jsx(hP,{children:h4?o.jsx(d4,{}):Zv?o.jsx(IB,{panel:Zv.panel}):o.jsx(LB,{})})})); diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-CMN3FneO.js b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-CMN3FneO.js deleted file mode 100644 index 2dd714b..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-CMN3FneO.js +++ /dev/null @@ -1,128 +0,0 @@ -var p0=Object.defineProperty;var m0=(e,t,n)=>t in e?p0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var X=(e,t,n)=>m0(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var _a=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function nf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var e_={exports:{}},lc={},t_={exports:{}},Se={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ql=Symbol.for("react.element"),g0=Symbol.for("react.portal"),x0=Symbol.for("react.fragment"),v0=Symbol.for("react.strict_mode"),_0=Symbol.for("react.profiler"),y0=Symbol.for("react.provider"),b0=Symbol.for("react.context"),w0=Symbol.for("react.forward_ref"),S0=Symbol.for("react.suspense"),k0=Symbol.for("react.memo"),C0=Symbol.for("react.lazy"),Up=Symbol.iterator;function j0(e){return e===null||typeof e!="object"?null:(e=Up&&e[Up]||e["@@iterator"],typeof e=="function"?e:null)}var n_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},r_=Object.assign,s_={};function yi(e,t,n){this.props=e,this.context=t,this.refs=s_,this.updater=n||n_}yi.prototype.isReactComponent={};yi.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};yi.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function i_(){}i_.prototype=yi.prototype;function rf(e,t,n){this.props=e,this.context=t,this.refs=s_,this.updater=n||n_}var sf=rf.prototype=new i_;sf.constructor=rf;r_(sf,yi.prototype);sf.isPureReactComponent=!0;var qp=Array.isArray,l_=Object.prototype.hasOwnProperty,lf={current:null},o_={key:!0,ref:!0,__self:!0,__source:!0};function a_(e,t,n){var r,s={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)l_.call(t,r)&&!o_.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,q=P[se];if(0>>1;ses(ee,j))Qs(V,ee)?(P[se]=V,P[Q]=j,se=Q):(P[se]=ee,P[re]=j,se=re);else if(Qs(V,j))P[se]=V,P[Q]=j,se=Q;else break e}}return z}function s(P,z){var j=P.sortIndex-z.sortIndex;return j!==0?j:P.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,a=l.now();e.unstable_now=function(){return l.now()-a}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,x=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(P){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=P)r(u),z.sortIndex=z.expirationTime,t(c,z);else break;z=n(u)}}function b(P){if(x=!1,y(P),!m)if(n(c)!==null)m=!0,W(C);else{var z=n(u);z!==null&&G(b,z.startTime-P)}}function C(P,z){m=!1,x&&(x=!1,v(L),L=-1),p=!0;var j=f;try{for(y(z),d=n(c);d!==null&&(!(d.expirationTime>z)||P&&!D());){var se=d.callback;if(typeof se=="function"){d.callback=null,f=d.priorityLevel;var q=se(d.expirationTime<=z);z=e.unstable_now(),typeof q=="function"?d.callback=q:d===n(c)&&r(c),y(z)}else r(c);d=n(c)}if(d!==null)var T=!0;else{var re=n(u);re!==null&&G(b,re.startTime-z),T=!1}return T}finally{d=null,f=j,p=!1}}var S=!1,N=null,L=-1,A=5,k=-1;function D(){return!(e.unstable_now()-kP||125se?(P.sortIndex=j,t(u,P),n(c)===null&&P===n(u)&&(x?(v(L),L=-1):x=!0,G(b,j-se))):(P.sortIndex=q,t(c,P),m||p||(m=!0,W(C))),P},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(P){var z=f;return function(){var j=f;f=z;try{return P.apply(this,arguments)}finally{f=j}}}})(f_);h_.exports=f_;var B0=h_.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var z0=g,an=B0;function J(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),id=Object.prototype.hasOwnProperty,F0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Kp={},Gp={};function $0(e){return id.call(Gp,e)?!0:id.call(Kp,e)?!1:F0.test(e)?Gp[e]=!0:(Kp[e]=!0,!1)}function W0(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function H0(e,t,n,r){if(t===null||typeof t>"u"||W0(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function zt(e,t,n,r,s,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var wt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wt[e]=new zt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wt[t]=new zt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wt[e]=new zt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wt[e]=new zt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){wt[e]=new zt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wt[e]=new zt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wt[e]=new zt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wt[e]=new zt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wt[e]=new zt(e,5,!1,e.toLowerCase(),null,!1,!1)});var af=/[\-:]([a-z])/g;function cf(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(af,cf);wt[t]=new zt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(af,cf);wt[t]=new zt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(af,cf);wt[t]=new zt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wt[e]=new zt(e,1,!1,e.toLowerCase(),null,!1,!1)});wt.xlinkHref=new zt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wt[e]=new zt(e,1,!1,e.toLowerCase(),null,!0,!0)});function uf(e,t,n,r){var s=wt.hasOwnProperty(t)?wt[t]:null;(s!==null?s.type!==0:r||!(2a||s[l]!==i[a]){var c=` -`+s[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=a);break}}}finally{Bc=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?el(e):""}function U0(e){switch(e.tag){case 5:return el(e.type);case 16:return el("Lazy");case 13:return el("Suspense");case 19:return el("SuspenseList");case 0:case 2:case 15:return e=zc(e.type,!1),e;case 11:return e=zc(e.type.render,!1),e;case 1:return e=zc(e.type,!0),e;default:return""}}function cd(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case qs:return"Fragment";case Us:return"Portal";case ld:return"Profiler";case df:return"StrictMode";case od:return"Suspense";case ad:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case g_:return(e.displayName||"Context")+".Consumer";case m_:return(e._context.displayName||"Context")+".Provider";case hf:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ff:return t=e.displayName||null,t!==null?t:cd(e.type)||"Memo";case kr:t=e._payload,e=e._init;try{return cd(e(t))}catch{}}return null}function q0(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return cd(t);case 8:return t===df?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Hr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function v_(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function V0(e){var t=v_(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function co(e){e._valueTracker||(e._valueTracker=V0(e))}function __(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=v_(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ya(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function ud(e,t){var n=t.checked;return Ke({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xp(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Hr(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function y_(e,t){t=t.checked,t!=null&&uf(e,"checked",t,!1)}function dd(e,t){y_(e,t);var n=Hr(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?hd(e,t.type,n):t.hasOwnProperty("defaultValue")&&hd(e,t.type,Hr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Qp(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function hd(e,t,n){(t!=="number"||ya(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var tl=Array.isArray;function ri(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=uo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sl(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var cl={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},K0=["Webkit","ms","Moz","O"];Object.keys(cl).forEach(function(e){K0.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),cl[t]=cl[e]})});function k_(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||cl.hasOwnProperty(e)&&cl[e]?(""+t).trim():t+"px"}function C_(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=k_(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var G0=Ke({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function md(e,t){if(t){if(G0[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(J(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(J(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(J(61))}if(t.style!=null&&typeof t.style!="object")throw Error(J(62))}}function gd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var xd=null;function pf(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var vd=null,si=null,ii=null;function em(e){if(e=Gl(e)){if(typeof vd!="function")throw Error(J(280));var t=e.stateNode;t&&(t=dc(t),vd(e.stateNode,e.type,t))}}function j_(e){si?ii?ii.push(e):ii=[e]:si=e}function N_(){if(si){var e=si,t=ii;if(ii=si=null,em(e),t)for(e=0;e>>=0,e===0?32:31-(ik(e)/lk|0)|0}var ho=64,fo=4194304;function nl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ka(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,l=n&268435455;if(l!==0){var a=l&~s;a!==0?r=nl(a):(i&=l,i!==0&&(r=nl(i)))}else l=n&~s,l!==0?r=nl(l):i!==0&&(r=nl(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Vl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Pn(t),e[t]=n}function uk(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=dl),cm=" ",um=!1;function K_(e,t){switch(e){case"keyup":return Bk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function G_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Vs=!1;function Fk(e,t){switch(e){case"compositionend":return G_(t);case"keypress":return t.which!==32?null:(um=!0,cm);case"textInput":return e=t.data,e===cm&&um?null:e;default:return null}}function $k(e,t){if(Vs)return e==="compositionend"||!wf&&K_(e,t)?(e=q_(),Zo=_f=Tr=null,Vs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=pm(n)}}function J_(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?J_(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Z_(){for(var e=window,t=ya();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ya(e.document)}return t}function Sf(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Xk(e){var t=Z_(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&J_(n.ownerDocument.documentElement,n)){if(r!==null&&Sf(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=mm(n,i);var l=mm(n,r);s&&l&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Ks=null,kd=null,fl=null,Cd=!1;function gm(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Cd||Ks==null||Ks!==ya(r)||(r=Ks,"selectionStart"in r&&Sf(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),fl&&Pl(fl,r)||(fl=r,r=Na(kd,"onSelect"),0Xs||(e.current=Td[Xs],Td[Xs]=null,Xs--)}function Ie(e,t){Xs++,Td[Xs]=e.current,e.current=t}var Ur={},Tt=Vr(Ur),Gt=Vr(!1),xs=Ur;function di(e,t){var n=e.type.contextTypes;if(!n)return Ur;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Yt(e){return e=e.childContextTypes,e!=null}function Pa(){ze(Gt),ze(Tt)}function Sm(e,t,n){if(Tt.current!==Ur)throw Error(J(168));Ie(Tt,t),Ie(Gt,n)}function ay(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(J(108,q0(e)||"Unknown",s));return Ke({},n,r)}function Aa(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ur,xs=Tt.current,Ie(Tt,e),Ie(Gt,Gt.current),!0}function km(e,t,n){var r=e.stateNode;if(!r)throw Error(J(169));n?(e=ay(e,t,xs),r.__reactInternalMemoizedMergedChildContext=e,ze(Gt),ze(Tt),Ie(Tt,e)):ze(Gt),Ie(Gt,n)}var rr=null,hc=!1,Zc=!1;function cy(e){rr===null?rr=[e]:rr.push(e)}function a1(e){hc=!0,cy(e)}function Kr(){if(!Zc&&rr!==null){Zc=!0;var e=0,t=Ae;try{var n=rr;for(Ae=1;e>=l,s-=l,ir=1<<32-Pn(t)+s|n<L?(A=N,N=null):A=N.sibling;var k=f(v,N,y[L],b);if(k===null){N===null&&(N=A);break}e&&N&&k.alternate===null&&t(v,N),_=i(k,_,L),S===null?C=k:S.sibling=k,S=k,N=A}if(L===y.length)return n(v,N),Fe&&ns(v,L),C;if(N===null){for(;LL?(A=N,N=null):A=N.sibling;var D=f(v,N,k.value,b);if(D===null){N===null&&(N=A);break}e&&N&&D.alternate===null&&t(v,N),_=i(D,_,L),S===null?C=D:S.sibling=D,S=D,N=A}if(k.done)return n(v,N),Fe&&ns(v,L),C;if(N===null){for(;!k.done;L++,k=y.next())k=d(v,k.value,b),k!==null&&(_=i(k,_,L),S===null?C=k:S.sibling=k,S=k);return Fe&&ns(v,L),C}for(N=r(v,N);!k.done;L++,k=y.next())k=p(N,v,L,k.value,b),k!==null&&(e&&k.alternate!==null&&N.delete(k.key===null?L:k.key),_=i(k,_,L),S===null?C=k:S.sibling=k,S=k);return e&&N.forEach(function(R){return t(v,R)}),Fe&&ns(v,L),C}function w(v,_,y,b){if(typeof y=="object"&&y!==null&&y.type===qs&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case ao:e:{for(var C=y.key,S=_;S!==null;){if(S.key===C){if(C=y.type,C===qs){if(S.tag===7){n(v,S.sibling),_=s(S,y.props.children),_.return=v,v=_;break e}}else if(S.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===kr&&Nm(C)===S.type){n(v,S.sibling),_=s(S,y.props),_.ref=Mi(v,S,y),_.return=v,v=_;break e}n(v,S);break}else t(v,S);S=S.sibling}y.type===qs?(_=fs(y.props.children,v.mode,b,y.key),_.return=v,v=_):(b=oa(y.type,y.key,y.props,null,v.mode,b),b.ref=Mi(v,_,y),b.return=v,v=b)}return l(v);case Us:e:{for(S=y.key;_!==null;){if(_.key===S)if(_.tag===4&&_.stateNode.containerInfo===y.containerInfo&&_.stateNode.implementation===y.implementation){n(v,_.sibling),_=s(_,y.children||[]),_.return=v,v=_;break e}else{n(v,_);break}else t(v,_);_=_.sibling}_=ou(y,v.mode,b),_.return=v,v=_}return l(v);case kr:return S=y._init,w(v,_,S(y._payload),b)}if(tl(y))return m(v,_,y,b);if(Ai(y))return x(v,_,y,b);yo(v,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,_!==null&&_.tag===6?(n(v,_.sibling),_=s(_,y),_.return=v,v=_):(n(v,_),_=lu(y,v.mode,b),_.return=v,v=_),l(v)):n(v,_)}return w}var fi=fy(!0),py=fy(!1),Da=Vr(null),Ra=null,Zs=null,Nf=null;function Ef(){Nf=Zs=Ra=null}function Pf(e){var t=Da.current;ze(Da),e._currentValue=t}function Rd(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function oi(e,t){Ra=e,Nf=Zs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Kt=!0),e.firstContext=null)}function bn(e){var t=e._currentValue;if(Nf!==e)if(e={context:e,memoizedValue:t,next:null},Zs===null){if(Ra===null)throw Error(J(308));Zs=e,Ra.dependencies={lanes:0,firstContext:e}}else Zs=Zs.next=e;return t}var cs=null;function Af(e){cs===null?cs=[e]:cs.push(e)}function my(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Af(t)):(n.next=s.next,s.next=n),t.interleaved=n,hr(e,r)}function hr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Cr=!1;function Tf(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function gy(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ar(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Br(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ne&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,hr(e,n)}return s=r.interleaved,s===null?(t.next=t,Af(r)):(t.next=s.next,s.next=t),r.interleaved=t,hr(e,n)}function ta(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,gf(e,n)}}function Em(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ma(e,t,n,r){var s=e.updateQueue;Cr=!1;var i=s.firstBaseUpdate,l=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var c=a,u=c.next;c.next=null,l===null?i=u:l.next=u,l=c;var h=e.alternate;h!==null&&(h=h.updateQueue,a=h.lastBaseUpdate,a!==l&&(a===null?h.firstBaseUpdate=u:a.next=u,h.lastBaseUpdate=c))}if(i!==null){var d=s.baseState;l=0,h=u=c=null,a=i;do{var f=a.lane,p=a.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=e,x=a;switch(f=t,p=n,x.tag){case 1:if(m=x.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=x.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Ke({},d,f);break e;case 2:Cr=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},h===null?(u=h=p,c=d):h=h.next=p,l|=f;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;f=a,a=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(h===null&&(c=d),s.baseState=c,s.firstBaseUpdate=u,s.lastBaseUpdate=h,t=s.shared.interleaved,t!==null){s=t;do l|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);ys|=l,e.lanes=l,e.memoizedState=d}}function Pm(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=tu.transition;tu.transition={};try{e(!1),t()}finally{Ae=n,tu.transition=r}}function Dy(){return wn().memoizedState}function h1(e,t,n){var r=Fr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ry(e))My(t,n);else if(n=my(e,t,n,r),n!==null){var s=Ot();An(n,e,r,s),Iy(n,t,r)}}function f1(e,t,n){var r=Fr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ry(e))My(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,a=i(l,n);if(s.hasEagerState=!0,s.eagerState=a,Dn(a,l)){var c=t.interleaved;c===null?(s.next=s,Af(t)):(s.next=c.next,c.next=s),t.interleaved=s;return}}catch{}finally{}n=my(e,t,s,r),n!==null&&(s=Ot(),An(n,e,r,s),Iy(n,t,r))}}function Ry(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function My(e,t){pl=Oa=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Iy(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,gf(e,n)}}var Ba={readContext:bn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},p1={readContext:bn,useCallback:function(e,t){return Fn().memoizedState=[e,t===void 0?null:t],e},useContext:bn,useEffect:Tm,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ra(4194308,4,Ey.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ra(4194308,4,e,t)},useInsertionEffect:function(e,t){return ra(4,2,e,t)},useMemo:function(e,t){var n=Fn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=h1.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Fn();return e={current:e},t.memoizedState=e},useState:Am,useDebugValue:zf,useDeferredValue:function(e){return Fn().memoizedState=e},useTransition:function(){var e=Am(!1),t=e[0];return e=d1.bind(null,e[1]),Fn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,s=Fn();if(Fe){if(n===void 0)throw Error(J(407));n=n()}else{if(n=t(),xt===null)throw Error(J(349));_s&30||yy(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Tm(wy.bind(null,r,i,e),[e]),r.flags|=2048,Ol(9,by.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Fn(),t=xt.identifierPrefix;if(Fe){var n=lr,r=ir;n=(r&~(1<<32-Pn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ml++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[Wn]=t,e[Ll]=r,Vy(e,t,!1,!1),t.stateNode=e;e:{switch(l=gd(n,r),n){case"dialog":Oe("cancel",e),Oe("close",e),s=r;break;case"iframe":case"object":case"embed":Oe("load",e),s=r;break;case"video":case"audio":for(s=0;sgi&&(t.flags|=128,r=!0,Ii(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ia(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ii(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Fe)return Ct(t),null}else 2*et()-i.renderingStartTime>gi&&n!==1073741824&&(t.flags|=128,r=!0,Ii(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=et(),t.sibling=null,n=Ue.current,Ie(Ue,r?n&1|2:n&1),t):(Ct(t),null);case 22:case 23:return qf(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?rn&1073741824&&(Ct(t),t.subtreeFlags&6&&(t.flags|=8192)):Ct(t),null;case 24:return null;case 25:return null}throw Error(J(156,t.tag))}function w1(e,t){switch(Cf(t),t.tag){case 1:return Yt(t.type)&&Pa(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return pi(),ze(Gt),ze(Tt),Rf(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Df(t),null;case 13:if(ze(Ue),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(J(340));hi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ze(Ue),null;case 4:return pi(),null;case 10:return Pf(t.type._context),null;case 22:case 23:return qf(),null;case 24:return null;default:return null}}var wo=!1,Pt=!1,S1=typeof WeakSet=="function"?WeakSet:Set,ae=null;function ei(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ye(e,t,r)}else n.current=null}function Hd(e,t,n){try{n()}catch(r){Ye(e,t,r)}}var Wm=!1;function k1(e,t){if(jd=Ca,e=Z_(),Sf(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,a=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||s!==0&&d.nodeType!==3||(a=l+s),d!==i||r!==0&&d.nodeType!==3||(c=l+r),d.nodeType===3&&(l+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===s&&(a=l),f===i&&++h===r&&(c=l),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=a===-1||c===-1?null:{start:a,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Nd={focusedElem:e,selectionRange:n},Ca=!1,ae=t;ae!==null;)if(t=ae,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ae=e;else for(;ae!==null;){t=ae;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var x=m.memoizedProps,w=m.memoizedState,v=t.stateNode,_=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:jn(t.type,x),w);v.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(J(163))}}catch(b){Ye(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,ae=e;break}ae=t.return}return m=Wm,Wm=!1,m}function ml(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Hd(t,n,i)}s=s.next}while(s!==r)}}function mc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ud(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Yy(e){var t=e.alternate;t!==null&&(e.alternate=null,Yy(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Wn],delete t[Ll],delete t[Ad],delete t[l1],delete t[o1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xy(e){return e.tag===5||e.tag===3||e.tag===4}function Hm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xy(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function qd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ea));else if(r!==4&&(e=e.child,e!==null))for(qd(e,t,n),e=e.sibling;e!==null;)qd(e,t,n),e=e.sibling}function Vd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Vd(e,t,n),e=e.sibling;e!==null;)Vd(e,t,n),e=e.sibling}var _t=null,Nn=!1;function vr(e,t,n){for(n=n.child;n!==null;)Qy(e,t,n),n=n.sibling}function Qy(e,t,n){if(qn&&typeof qn.onCommitFiberUnmount=="function")try{qn.onCommitFiberUnmount(oc,n)}catch{}switch(n.tag){case 5:Pt||ei(n,t);case 6:var r=_t,s=Nn;_t=null,vr(e,t,n),_t=r,Nn=s,_t!==null&&(Nn?(e=_t,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):_t.removeChild(n.stateNode));break;case 18:_t!==null&&(Nn?(e=_t,n=n.stateNode,e.nodeType===8?Jc(e.parentNode,n):e.nodeType===1&&Jc(e,n),Nl(e)):Jc(_t,n.stateNode));break;case 4:r=_t,s=Nn,_t=n.stateNode.containerInfo,Nn=!0,vr(e,t,n),_t=r,Nn=s;break;case 0:case 11:case 14:case 15:if(!Pt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&Hd(n,t,l),s=s.next}while(s!==r)}vr(e,t,n);break;case 1:if(!Pt&&(ei(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Ye(n,t,a)}vr(e,t,n);break;case 21:vr(e,t,n);break;case 22:n.mode&1?(Pt=(r=Pt)||n.memoizedState!==null,vr(e,t,n),Pt=r):vr(e,t,n);break;default:vr(e,t,n)}}function Um(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new S1),t.forEach(function(r){var s=D1.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Cn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=l),r&=~i}if(r=s,r=et()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*j1(r/1960))-r,10e?16:e,Lr===null)var r=!1;else{if(e=Lr,Lr=null,$a=0,Ne&6)throw Error(J(331));var s=Ne;for(Ne|=4,ae=e.current;ae!==null;){var i=ae,l=i.child;if(ae.flags&16){var a=i.deletions;if(a!==null){for(var c=0;cet()-Hf?hs(e,0):Wf|=n),Xt(e,t)}function ib(e,t){t===0&&(e.mode&1?(t=fo,fo<<=1,!(fo&130023424)&&(fo=4194304)):t=1);var n=Ot();e=hr(e,t),e!==null&&(Vl(e,t,n),Xt(e,n))}function L1(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ib(e,n)}function D1(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(J(314))}r!==null&&r.delete(t),ib(e,n)}var lb;lb=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Gt.current)Kt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Kt=!1,y1(e,t,n);Kt=!!(e.flags&131072)}else Kt=!1,Fe&&t.flags&1048576&&uy(t,La,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;sa(e,t),e=t.pendingProps;var s=di(t,Tt.current);oi(t,n),s=If(null,t,r,e,s,n);var i=Of();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Yt(r)?(i=!0,Aa(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Tf(t),s.updater=pc,t.stateNode=s,s._reactInternals=t,Id(t,r,e,n),t=zd(null,t,r,!0,i,n)):(t.tag=0,Fe&&i&&kf(t),Mt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(sa(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=M1(r),e=jn(r,e),s){case 0:t=Bd(null,t,r,e,n);break e;case 1:t=zm(null,t,r,e,n);break e;case 11:t=Om(null,t,r,e,n);break e;case 14:t=Bm(null,t,r,jn(r.type,e),n);break e}throw Error(J(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),Bd(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),zm(e,t,r,s,n);case 3:e:{if(Hy(t),e===null)throw Error(J(387));r=t.pendingProps,i=t.memoizedState,s=i.element,gy(e,t),Ma(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=mi(Error(J(423)),t),t=Fm(e,t,r,n,s);break e}else if(r!==s){s=mi(Error(J(424)),t),t=Fm(e,t,r,n,s);break e}else for(sn=Or(t.stateNode.containerInfo.firstChild),ln=t,Fe=!0,En=null,n=py(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(hi(),r===s){t=fr(e,t,n);break e}Mt(e,t,r,n)}t=t.child}return t;case 5:return xy(t),e===null&&Dd(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,l=s.children,Ed(r,s)?l=null:i!==null&&Ed(r,i)&&(t.flags|=32),Wy(e,t),Mt(e,t,l,n),t.child;case 6:return e===null&&Dd(t),null;case 13:return Uy(e,t,n);case 4:return Lf(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=fi(t,null,r,n):Mt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),Om(e,t,r,s,n);case 7:return Mt(e,t,t.pendingProps,n),t.child;case 8:return Mt(e,t,t.pendingProps.children,n),t.child;case 12:return Mt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,l=s.value,Ie(Da,r._currentValue),r._currentValue=l,i!==null)if(Dn(i.value,l)){if(i.children===s.children&&!Gt.current){t=fr(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){l=i.child;for(var c=a.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=ar(-1,n&-n),c.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Rd(i.return,n,t),a.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(J(341));l.lanes|=n,a=l.alternate,a!==null&&(a.lanes|=n),Rd(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Mt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,oi(t,n),s=bn(s),r=r(s),t.flags|=1,Mt(e,t,r,n),t.child;case 14:return r=t.type,s=jn(r,t.pendingProps),s=jn(r.type,s),Bm(e,t,r,s,n);case 15:return Fy(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),sa(e,t),t.tag=1,Yt(r)?(e=!0,Aa(t)):e=!1,oi(t,n),Oy(t,r,s),Id(t,r,s,n),zd(null,t,r,!0,e,n);case 19:return qy(e,t,n);case 22:return $y(e,t,n)}throw Error(J(156,t.tag))};function ob(e,t){return R_(e,t)}function R1(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vn(e,t,n,r){return new R1(e,t,n,r)}function Kf(e){return e=e.prototype,!(!e||!e.isReactComponent)}function M1(e){if(typeof e=="function")return Kf(e)?1:0;if(e!=null){if(e=e.$$typeof,e===hf)return 11;if(e===ff)return 14}return 2}function $r(e,t){var n=e.alternate;return n===null?(n=vn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function oa(e,t,n,r,s,i){var l=2;if(r=e,typeof e=="function")Kf(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case qs:return fs(n.children,s,i,t);case df:l=8,s|=8;break;case ld:return e=vn(12,n,t,s|2),e.elementType=ld,e.lanes=i,e;case od:return e=vn(13,n,t,s),e.elementType=od,e.lanes=i,e;case ad:return e=vn(19,n,t,s),e.elementType=ad,e.lanes=i,e;case x_:return xc(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case m_:l=10;break e;case g_:l=9;break e;case hf:l=11;break e;case ff:l=14;break e;case kr:l=16,r=null;break e}throw Error(J(130,e==null?e:typeof e,""))}return t=vn(l,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function fs(e,t,n,r){return e=vn(7,e,r,t),e.lanes=n,e}function xc(e,t,n,r){return e=vn(22,e,r,t),e.elementType=x_,e.lanes=n,e.stateNode={isHidden:!1},e}function lu(e,t,n){return e=vn(6,e,null,t),e.lanes=n,e}function ou(e,t,n){return t=vn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function I1(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=$c(0),this.expirationTimes=$c(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=$c(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Gf(e,t,n,r,s,i,l,a,c){return e=new I1(e,t,n,a,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=vn(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tf(i),e}function O1(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(db)}catch(e){console.error(e)}}db(),d_.exports=cn;var W1=d_.exports,Jm=W1;sd.createRoot=Jm.createRoot,sd.hydrateRoot=Jm.hydrateRoot;/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var hb=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,U1=(e,t)=>{for(var n in t)hb(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,r)=>{for(var s=r>1?void 0:r?H1(t,n):t,i=e.length-1,l;i>=0;i--)(l=e[i])&&(s=(r?l(t,n,s):l(s))||s);return r&&s&&hb(t,n,s),s},ie=(e,t)=>(n,r)=>t(n,r,e),Zm="Terminal input",Qd={get:()=>Zm,set:e=>Zm=e},eg="Too much output to announce, navigate to rows manually to read",Jd={get:()=>eg,set:e=>eg=e};function q1(e){return e.replace(/\r?\n/g,"\r")}function V1(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function K1(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function G1(e,t,n,r){if(e.stopPropagation(),e.clipboardData){let s=e.clipboardData.getData("text/plain");fb(s,t,n,r)}}function fb(e,t,n,r){e=q1(e),e=V1(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function pb(e,t,n){let r=n.getBoundingClientRect(),s=e.clientX-r.left-10,i=e.clientY-r.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${s}px`,t.style.top=`${i}px`,t.style.zIndex="1000",t.focus()}function tg(e,t,n,r,s){pb(e,t,n),s&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function jr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function wc(e,t=0,n=e.length){let r="";for(let s=t;s65535?(i-=65536,r+=String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):r+=String.fromCharCode(i)}return r}var Y1=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,s=0;if(this._interim){let i=e.charCodeAt(s++);56320<=i&&i<=57343?t[r++]=(this._interim-55296)*1024+i-56320+65536:(t[r++]=this._interim,t[r++]=i),this._interim=0}for(let i=s;i=n)return this._interim=l,r;let a=e.charCodeAt(i);56320<=a&&a<=57343?t[r++]=(l-55296)*1024+a-56320+65536:(t[r++]=l,t[r++]=a);continue}l!==65279&&(t[r++]=l)}return r}},X1=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,s,i,l,a,c=0,u=0;if(this.interim[0]){let f=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,x;for(;(x=this.interim[++m]&63)&&m<4;)p<<=6,p|=x;let w=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,v=w-m;for(;u=n)return 0;if(x=e[u++],(x&192)!==128){u--,f=!0;break}else this.interim[m++]=x,p<<=6,p|=x&63}f||(w===2?p<128?u--:t[r++]=p:w===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let h=n-4,d=u;for(;d=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(c=(s&31)<<6|i&63,c<128){d--;continue}t[r++]=c}else if((s&240)===224){if(d>=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,r;if(l=e[d++],(l&192)!==128){d--;continue}if(c=(s&15)<<12|(i&63)<<6|l&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((s&248)===240){if(d>=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,r;if(l=e[d++],(l&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,this.interim[2]=l,r;if(a=e[d++],(a&192)!==128){d--;continue}if(c=(s&7)<<18|(i&63)<<12|(l&63)<<6|a&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},mb="",Dr=" ",Xl=class gb{constructor(){this.fg=0,this.bg=0,this.extended=new Ua}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new gb;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Ua=class xb{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new xb(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},yn=class vb extends Xl{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Ua,this.combinedData=""}static fromCharData(t){let n=new vb;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?jr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let s=t[1].charCodeAt(1);56320<=s&&s<=57343?this.content=(r-55296)*1024+s-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ng="di$target",Zd="di$dependencies",au=new Map;function Q1(e){return e[Zd]||[]}function vt(e){if(au.has(e))return au.get(e);let t=function(n,r,s){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");J1(t,n,s)};return t._id=e,au.set(e,t),t}function J1(e,t,n){t[ng]===t?t[Zd].push({id:e,index:n}):(t[Zd]=[{id:e,index:n}],t[ng]=t)}var Ft=vt("BufferService"),_b=vt("CoreMouseService"),Ns=vt("CoreService"),Z1=vt("CharsetService"),Jf=vt("InstantiationService"),yb=vt("LogService"),$t=vt("OptionsService"),bb=vt("OscLinkService"),eC=vt("UnicodeService"),Ql=vt("DecorationService"),eh=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],s=this._optionsService.rawOptions.linkHandler,i=new yn,l=n.getTrimmedLength(),a=-1,c=-1,u=!1;for(let h=0;hs?s.activate(m,x,f):tC(m,x),hover:(m,x)=>s?.hover?.(m,x,f),leave:(m,x)=>s?.leave?.(m,x,f)})}u=!1,i.hasExtendedAttrs()&&i.extended.urlId?(c=h,a=i.extended.urlId):(c=-1,a=-1)}}t(r)}};eh=Qe([ie(0,Ft),ie(1,$t),ie(2,bb)],eh);function tC(e,t){if(confirm(`Do you want to navigate to ${t}? - -WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Sc=vt("CharSizeService"),mr=vt("CoreBrowserService"),Zf=vt("MouseService"),gr=vt("RenderService"),nC=vt("SelectionService"),wb=vt("CharacterJoinerService"),Si=vt("ThemeService"),Sb=vt("LinkProviderService"),rC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?rg.isErrorNoTelemetry(e)?new rg(e.message+` - -`+e.stack):new Error(e.message+` - -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},sC=new rC;function aa(e){iC(e)||sC.onUnexpectedError(e)}var th="Canceled";function iC(e){return e instanceof lC?!0:e instanceof Error&&e.name===th&&e.message===th}var lC=class extends Error{constructor(){super(th),this.name=this.message}};function oC(e){return new Error(`Illegal argument: ${e}`)}var rg=class nh extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof nh)return t;let n=new nh;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},rh=class kb extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,kb.prototype)}};function Zt(e,t=0){return e[e.length-(1+t)]}var aC;(e=>{function t(i){return i<0}e.isLessThan=t;function n(i){return i<=0}e.isLessThanOrEqual=n;function r(i){return i>0}e.isGreaterThan=r;function s(i){return i===0}e.isNeitherLessOrGreaterThan=s,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(aC||={});function cC(e,t){let n=this,r=!1,s;return function(){return r||(r=!0,t||(s=e.apply(n,arguments))),s}}var Cb;(e=>{function t(b){return b&&typeof b=="object"&&typeof b[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*s(b){yield b}e.single=s;function i(b){return t(b)?b:s(b)}e.wrap=i;function l(b){return b||n}e.from=l;function*a(b){for(let C=b.length-1;C>=0;C--)yield b[C]}e.reverse=a;function c(b){return!b||b[Symbol.iterator]().next().done===!0}e.isEmpty=c;function u(b){return b[Symbol.iterator]().next().value}e.first=u;function h(b,C){let S=0;for(let N of b)if(C(N,S++))return!0;return!1}e.some=h;function d(b,C){for(let S of b)if(C(S))return S}e.find=d;function*f(b,C){for(let S of b)C(S)&&(yield S)}e.filter=f;function*p(b,C){let S=0;for(let N of b)yield C(N,S++)}e.map=p;function*m(b,C){let S=0;for(let N of b)yield*C(N,S++)}e.flatMap=m;function*x(...b){for(let C of b)yield*C}e.concat=x;function w(b,C,S){let N=S;for(let L of b)N=C(N,L);return N}e.reduce=w;function*v(b,C,S=b.length){for(C<0&&(C+=b.length),S<0?S+=b.length:S>b.length&&(S=b.length);C1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function uC(...e){return $e(()=>ws(e))}function $e(e){return{dispose:cC(()=>{e()})}}var jb=class Nb{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ws(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Nb.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};jb.DISABLE_DISPOSED_WARNING=!1;var Wr=jb,be=class{constructor(){this._store=new Wr,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};be.None=Object.freeze({dispose(){}});var xi=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},or=typeof window=="object"?window:globalThis,sh=class ih{constructor(t){this.element=t,this.next=ih.Undefined,this.prev=ih.Undefined}};sh.Undefined=new sh(void 0);var We=sh,sg=class{constructor(){this._first=We.Undefined,this._last=We.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===We.Undefined}clear(){let e=this._first;for(;e!==We.Undefined;){let t=e.next;e.prev=We.Undefined,e.next=We.Undefined,e=t}this._first=We.Undefined,this._last=We.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new We(e);if(this._first===We.Undefined)this._first=n,this._last=n;else if(t){let s=this._last;this._last=n,n.prev=s,s.next=n}else{let s=this._first;this._first=n,n.next=s,s.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==We.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==We.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==We.Undefined&&e.next!==We.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===We.Undefined&&e.next===We.Undefined?(this._first=We.Undefined,this._last=We.Undefined):e.next===We.Undefined?(this._last=this._last.prev,this._last.next=We.Undefined):e.prev===We.Undefined&&(this._first=this._first.next,this._first.prev=We.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==We.Undefined;)yield e.element,e=e.next}},dC=globalThis.performance&&typeof globalThis.performance.now=="function",hC=class Eb{static create(t){return new Eb(t)}constructor(t){this._now=dC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},yt;(e=>{e.None=()=>be.None;function t(R,E){return d(R,()=>{},0,void 0,!0,void 0,E)}e.defer=t;function n(R){return(E,O=null,I)=>{let W=!1,G;return G=R(P=>{if(!W)return G?G.dispose():W=!0,E.call(O,P)},null,I),W&&G.dispose(),G}}e.once=n;function r(R,E,O){return u((I,W=null,G)=>R(P=>I.call(W,E(P)),null,G),O)}e.map=r;function s(R,E,O){return u((I,W=null,G)=>R(P=>{E(P),I.call(W,P)},null,G),O)}e.forEach=s;function i(R,E,O){return u((I,W=null,G)=>R(P=>E(P)&&I.call(W,P),null,G),O)}e.filter=i;function l(R){return R}e.signal=l;function a(...R){return(E,O=null,I)=>{let W=uC(...R.map(G=>G(P=>E.call(O,P))));return h(W,I)}}e.any=a;function c(R,E,O,I){let W=O;return r(R,G=>(W=E(W,G),W),I)}e.reduce=c;function u(R,E){let O,I={onWillAddFirstListener(){O=R(W.fire,W)},onDidRemoveLastListener(){O?.dispose()}},W=new ne(I);return E?.add(W),W.event}function h(R,E){return E instanceof Array?E.push(R):E&&E.add(R),R}function d(R,E,O=100,I=!1,W=!1,G,P){let z,j,se,q=0,T,re={leakWarningThreshold:G,onWillAddFirstListener(){z=R(Q=>{q++,j=E(j,Q),I&&!se&&(ee.fire(j),j=void 0),T=()=>{let V=j;j=void 0,se=void 0,(!I||q>1)&&ee.fire(V),q=0},typeof O=="number"?(clearTimeout(se),se=setTimeout(T,O)):se===void 0&&(se=0,queueMicrotask(T))})},onWillRemoveListener(){W&&q>0&&T?.()},onDidRemoveLastListener(){T=void 0,z.dispose()}},ee=new ne(re);return P?.add(ee),ee.event}e.debounce=d;function f(R,E=0,O){return e.debounce(R,(I,W)=>I?(I.push(W),I):[W],E,void 0,!0,void 0,O)}e.accumulate=f;function p(R,E=(I,W)=>I===W,O){let I=!0,W;return i(R,G=>{let P=I||!E(G,W);return I=!1,W=G,P},O)}e.latch=p;function m(R,E,O){return[e.filter(R,E,O),e.filter(R,I=>!E(I),O)]}e.split=m;function x(R,E=!1,O=[],I){let W=O.slice(),G=R(j=>{W?W.push(j):z.fire(j)});I&&I.add(G);let P=()=>{W?.forEach(j=>z.fire(j)),W=null},z=new ne({onWillAddFirstListener(){G||(G=R(j=>z.fire(j)),I&&I.add(G))},onDidAddFirstListener(){W&&(E?setTimeout(P):P())},onDidRemoveLastListener(){G&&G.dispose(),G=null}});return I&&I.add(z),z.event}e.buffer=x;function w(R,E){return(O,I,W)=>{let G=E(new _);return R(function(P){let z=G.evaluate(P);z!==v&&O.call(I,z)},void 0,W)}}e.chain=w;let v=Symbol("HaltChainable");class _{constructor(){this.steps=[]}map(E){return this.steps.push(E),this}forEach(E){return this.steps.push(O=>(E(O),O)),this}filter(E){return this.steps.push(O=>E(O)?O:v),this}reduce(E,O){let I=O;return this.steps.push(W=>(I=E(I,W),I)),this}latch(E=(O,I)=>O===I){let O=!0,I;return this.steps.push(W=>{let G=O||!E(W,I);return O=!1,I=W,G?W:v}),this}evaluate(E){for(let O of this.steps)if(E=O(E),E===v)break;return E}}function y(R,E,O=I=>I){let I=(...z)=>P.fire(O(...z)),W=()=>R.on(E,I),G=()=>R.removeListener(E,I),P=new ne({onWillAddFirstListener:W,onDidRemoveLastListener:G});return P.event}e.fromNodeEventEmitter=y;function b(R,E,O=I=>I){let I=(...z)=>P.fire(O(...z)),W=()=>R.addEventListener(E,I),G=()=>R.removeEventListener(E,I),P=new ne({onWillAddFirstListener:W,onDidRemoveLastListener:G});return P.event}e.fromDOMEventEmitter=b;function C(R){return new Promise(E=>n(R)(E))}e.toPromise=C;function S(R){let E=new ne;return R.then(O=>{E.fire(O)},()=>{E.fire(void 0)}).finally(()=>{E.dispose()}),E.event}e.fromPromise=S;function N(R,E){return R(O=>E.fire(O))}e.forward=N;function L(R,E,O){return E(O),R(I=>E(I))}e.runAndSubscribe=L;class A{constructor(E,O){this._observable=E,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{E.addObserver(this)},onDidRemoveLastListener:()=>{E.removeObserver(this)}};this.emitter=new ne(I),O&&O.add(this.emitter)}beginUpdate(E){this._counter++}handlePossibleChange(E){}handleChange(E,O){this._hasChanged=!0}endUpdate(E){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function k(R,E){return new A(R,E).emitter.event}e.fromObservable=k;function D(R){return(E,O,I)=>{let W=0,G=!1,P={beginUpdate(){W++},endUpdate(){W--,W===0&&(R.reportChanges(),G&&(G=!1,E.call(O)))},handlePossibleChange(){},handleChange(){G=!0}};R.addObserver(P),R.reportChanges();let z={dispose(){R.removeObserver(P)}};return I instanceof Wr?I.add(z):Array.isArray(I)&&I.push(z),z}}e.fromObservableLight=D})(yt||={});var lh=class oh{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${oh._idPool++}`,oh.all.add(this)}start(t){this._stopWatch=new hC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};lh.all=new Set,lh._idPool=0;var fC=lh,pC=-1,Pb=class Ab{constructor(t,n,r=(Ab._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,n){let r=this.threshold;if(r<=0||n{let i=this._stacks.get(t.value)||0;this._stacks.set(t.value,i-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[r,s]of this._stacks)(!t||n{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let a=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new vC(`${l}. HINT: Stack shows most frequent listener (${a[1]}-times)`,a[0]);return(this._options?.onListenerError||aa)(c),be.None}if(this._disposed)return be.None;t&&(e=e.bind(t));let r=new cu(e),s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=gC.create(),s=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof cu?(this._deliveryQueue??=new wC,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let i=$e(()=>{s?.(),this._removeListener(r)});return n instanceof Wr?n.add(i):Array.isArray(n)&&n.push(i),i},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*yC<=t.length){let s=0;for(let i=0;i0}},wC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},ah=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ne,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ne,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(r,t),this._onDidChangeZoomLevel.fire(r)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToFullScreen.set(r,t),this._onDidChangeFullscreen.fire(r)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};ah.INSTANCE=new ah;var ep=ah;function SC(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}ep.INSTANCE.onDidChangeZoomLevel;function kC(e){return ep.INSTANCE.getZoomFactor(e)}ep.INSTANCE.onDidChangeFullscreen;var ki=typeof navigator=="object"?navigator.userAgent:"",ch=ki.indexOf("Firefox")>=0,CC=ki.indexOf("AppleWebKit")>=0,tp=ki.indexOf("Chrome")>=0,jC=!tp&&ki.indexOf("Safari")>=0;ki.indexOf("Electron/")>=0;ki.indexOf("Android")>=0;var uu=!1;if(typeof or.matchMedia=="function"){let e=or.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=or.matchMedia("(display-mode: fullscreen)");uu=e.matches,SC(or,e,({matches:n})=>{uu&&t.matches||(uu=n)})}var ni="en",uh=!1,dh=!1,ca=!1,Lb=!1,Co,ua=ni,ig=ni,NC,tr,ps=globalThis,nn;typeof ps.vscode<"u"&&typeof ps.vscode.process<"u"?nn=ps.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(nn=process);var EC=typeof nn?.versions?.electron=="string",PC=EC&&nn?.type==="renderer";if(typeof nn=="object"){uh=nn.platform==="win32",dh=nn.platform==="darwin",ca=nn.platform==="linux",ca&&nn.env.SNAP&&nn.env.SNAP_REVISION,nn.env.CI||nn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Co=ni,ua=ni;let e=nn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Co=t.userLocale,ig=t.osLocale,ua=t.resolvedLanguage||ni,NC=t.languagePack?.translationsConfigFile}catch{}Lb=!0}else typeof navigator=="object"&&!PC?(tr=navigator.userAgent,uh=tr.indexOf("Windows")>=0,dh=tr.indexOf("Macintosh")>=0,(tr.indexOf("Macintosh")>=0||tr.indexOf("iPad")>=0||tr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ca=tr.indexOf("Linux")>=0,tr?.indexOf("Mobi")>=0,ua=globalThis._VSCODE_NLS_LANGUAGE||ni,Co=navigator.language.toLowerCase(),ig=Co):console.error("Unable to resolve platform.");var Db=uh,Kn=dh,AC=ca,lg=Lb,Gn=tr,_r=ua,TC;(e=>{function t(){return _r}e.value=t;function n(){return _r.length===2?_r==="en":_r.length>=3?_r[0]==="e"&&_r[1]==="n"&&_r[2]==="-":!1}e.isDefaultVariant=n;function r(){return _r==="en"}e.isDefault=r})(TC||={});var LC=typeof ps.postMessage=="function"&&!ps.importScripts;(()=>{if(LC){let e=[];ps.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let r=0,s=e.length;r{let r=++t;e.push({id:r,callback:n}),ps.postMessage({vscodeScheduleAsyncWork:r},"*")}}return e=>setTimeout(e)})();var DC=!!(Gn&&Gn.indexOf("Chrome")>=0);Gn&&Gn.indexOf("Firefox")>=0;!DC&&Gn&&Gn.indexOf("Safari")>=0;Gn&&Gn.indexOf("Edg/")>=0;Gn&&Gn.indexOf("Android")>=0;var Ls=typeof navigator=="object"?navigator:{};lg||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ls&&Ls.clipboard&&Ls.clipboard.writeText,lg||Ls&&Ls.clipboard&&Ls.clipboard.readText;var np=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},du=new np,og=new np,ag=new np,RC=new Array(230),Rb;(e=>{function t(a){return du.keyCodeToStr(a)}e.toString=t;function n(a){return du.strToKeyCode(a)}e.fromString=n;function r(a){return og.keyCodeToStr(a)}e.toUserSettingsUS=r;function s(a){return ag.keyCodeToStr(a)}e.toUserSettingsGeneral=s;function i(a){return og.strToKeyCode(a)||ag.strToKeyCode(a)}e.fromUserSettings=i;function l(a){if(a>=98&&a<=113)return null;switch(a){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return du.keyCodeToStr(a)}e.toElectronAccelerator=l})(Rb||={});var MC=class Mb{constructor(t,n,r,s,i){this.ctrlKey=t,this.shiftKey=n,this.altKey=r,this.metaKey=s,this.keyCode=i}equals(t){return t instanceof Mb&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",r=this.altKey?"1":"0",s=this.metaKey?"1":"0";return`K${t}${n}${r}${s}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new IC([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},IC=class{constructor(e){if(e.length===0)throw oC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t{function t(n){return n===e.None||n===e.Cancelled||n instanceof qC?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:yt.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Ib})})(UC||={});var qC=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Ib:(this._emitter||(this._emitter=new ne),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},rp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new rh("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new rh("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},VC=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new rh("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=$e(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},KC;(e=>{async function t(r){let s,i=await Promise.all(r.map(l=>l.then(a=>a,a=>{s||(s=a)})));if(typeof s<"u")throw s;return i}e.settled=t;function n(r){return new Promise(async(s,i)=>{try{await r(s,i)}catch(l){i(l)}})}e.withAsyncBody=n})(KC||={});var hg=class fn{static fromArray(t){return new fn(n=>{n.emitMany(t)})}static fromPromise(t){return new fn(async n=>{n.emitMany(await t)})}static fromPromises(t){return new fn(async n=>{await Promise.all(t.map(async r=>n.emitOne(await r)))})}static merge(t){return new fn(async n=>{await Promise.all(t.map(async r=>{for await(let s of r)n.emitOne(s)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new ne,queueMicrotask(async()=>{let r={emitOne:s=>this.emitOne(s),emitMany:s=>this.emitMany(s),reject:s=>this.reject(s)};try{await Promise.resolve(t(r)),this.resolve()}catch(s){this.reject(s)}finally{r.emitOne=void 0,r.emitMany=void 0,r.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new fn(async r=>{for await(let s of t)r.emitOne(n(s))})}map(t){return fn.map(this,t)}static filter(t,n){return new fn(async r=>{for await(let s of t)n(s)&&r.emitOne(s)})}filter(t){return fn.filter(this,t)}static coalesce(t){return fn.filter(t,n=>!!n)}coalesce(){return fn.coalesce(this)}static async toPromise(t){let n=[];for await(let r of t)n.push(r);return n}toPromise(){return fn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};hg.EMPTY=hg.fromArray([]);var{getWindow:Un,getWindowId:GC,onDidRegisterWindow:YC}=function(){let e=new Map,t={window:or,disposables:new Wr};e.set(or.vscodeWindowId,t);let n=new ne,r=new ne,s=new ne;function i(l,a){return(typeof l=="number"?e.get(l):void 0)??(a?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:s.event,onDidUnregisterWindow:r.event,registerWindow(l){if(e.has(l.vscodeWindowId))return be.None;let a=new Wr,c={window:l,disposables:a.add(new Wr)};return e.set(l.vscodeWindowId,c),a.add($e(()=>{e.delete(l.vscodeWindowId),r.fire(l)})),a.add(me(l,ht.BEFORE_UNLOAD,()=>{s.fire(l)})),n.fire(c),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(l){return l.vscodeWindowId},hasWindow(l){return e.has(l)},getWindowById:i,getWindow(l){let a=l;if(a?.ownerDocument?.defaultView)return a.ownerDocument.defaultView.window;let c=l;return c?.view?c.view.window:or},getDocument(l){return Un(l).document}}}(),XC=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function me(e,t,n,r){return new XC(e,t,n,r)}var fg=function(e,t,n,r){return me(e,t,n,r)},sp,QC=class extends VC{constructor(e){super(),this.defaultTarget=e&&Un(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},pg=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){aa(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,s=i=>{n.set(i,!1);let l=e.get(i)??[];for(t.set(i,l),e.set(i,[]),r.set(i,!0);l.length>0;)l.sort(pg.sort),l.shift().execute();r.set(i,!1)};sp=(i,l,a=0)=>{let c=GC(i),u=new pg(l,a),h=e.get(c);return h||(h=[],e.set(c,h)),h.push(u),n.get(c)||(n.set(c,!0),i.requestAnimationFrame(()=>s(c))),u}})();function JC(e){let t=e.getBoundingClientRect(),n=Un(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var ht={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},ZC=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Wt(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Wt(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Wt(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Wt(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Wt(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Wt(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Wt(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Wt(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Wt(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Wt(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Wt(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Wt(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Wt(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Wt(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Wt(e){return typeof e=="number"?`${e}px`:e}function vl(e){return new ZC(e)}var Ob=class{constructor(){this._hooks=new Wr,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=s;let i=e;try{e.setPointerCapture(t),this._hooks.add($e(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{i=Un(e)}this._hooks.add(me(i,ht.POINTER_MOVE,l=>{if(l.buttons!==n){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(me(i,ht.POINTER_UP,l=>this.stopMonitoring(!0)))}};function ej(e,t,n){let r=null,s=null;if(typeof n.value=="function"?(r="value",s=n.value,s.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(r="get",s=n.get),!s)throw new Error("not supported");let i=`$memoize$${t}`;n[r]=function(...l){return this.hasOwnProperty(i)||Object.defineProperty(this,i,{configurable:!1,enumerable:!1,writable:!1,value:s.apply(this,l)}),this[i]}}var zn;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(zn||={});var sl=class Nt extends be{constructor(){super(),this.dispatched=!1,this.targets=new sg,this.ignoreTargets=new sg,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(yt.runAndSubscribe(YC,({window:t,disposables:n})=>{n.add(me(t.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),n.add(me(t.document,"touchend",r=>this.onTouchEnd(t,r))),n.add(me(t.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:or,disposables:this._store}))}static addTarget(t){if(!Nt.isTouchDevice())return be.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.targets.push(t);return $e(n)}static ignoreTarget(t){if(!Nt.isTouchDevice())return be.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.ignoreTargets.push(t);return $e(n)}static isTouchDevice(){return"ontouchstart"in or||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,s=t.targetTouches.length;r=Nt.HOLD_DELAY&&Math.abs(c.initialPageX-Zt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Zt(c.rollingPageY))<30){let h=this.newGestureEvent(zn.Contextmenu,c.initialTarget);h.pageX=Zt(c.rollingPageX),h.pageY=Zt(c.rollingPageY),this.dispatchEvent(h)}else if(s===1){let h=Zt(c.rollingPageX),d=Zt(c.rollingPageY),f=Zt(c.rollingTimestamps)-c.rollingTimestamps[0],p=h-c.rollingPageX[0],m=d-c.rollingPageY[0],x=[...this.targets].filter(w=>c.initialTarget instanceof Node&&w.contains(c.initialTarget));this.inertia(t,x,r,Math.abs(p)/f,p>0?1:-1,h,Math.abs(m)/f,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(zn.End,c.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let r=document.createEvent("CustomEvent");return r.initEvent(t,!1,!0),r.initialTarget=n,r.tapCount=0,r}dispatchEvent(t){if(t.type===zn.Tap){let n=new Date().getTime(),r=0;n-this._lastSetTapCountTime>Nt.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===zn.Change||t.type===zn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(t.initialTarget))return;let n=[];for(let r of this.targets)if(r.contains(t.initialTarget)){let s=0,i=t.initialTarget;for(;i&&i!==r;)s++,i=i.parentElement;n.push([s,r])}n.sort((r,s)=>r[0]-s[0]);for(let[r,s]of n)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,s,i,l,a,c,u){this.handle=sp(t,()=>{let h=Date.now(),d=h-r,f=0,p=0,m=!0;s+=Nt.SCROLL_FRICTION*d,a+=Nt.SCROLL_FRICTION*d,s>0&&(m=!1,f=i*s*d),a>0&&(m=!1,p=c*a*d);let x=this.newGestureEvent(zn.Change);x.translationX=f,x.translationY=p,n.forEach(w=>w.dispatchEvent(x)),m||this.inertia(t,n,h,s,i,l+f,a,c,u+p)})}onTouchMove(t){let n=Date.now();for(let r=0,s=t.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(i.pageX),l.rollingPageY.push(i.pageY),l.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};sl.SCROLL_FRICTION=-.005,sl.HOLD_DELAY=700,sl.CLEAR_TAP_COUNT_TIME=400,Qe([ej],sl,"isTouchDevice",1);var tj=sl,ip=class extends be{onclick(e,t){this._register(me(e,ht.CLICK,n=>t(new jo(Un(e),n))))}onmousedown(e,t){this._register(me(e,ht.MOUSE_DOWN,n=>t(new jo(Un(e),n))))}onmouseover(e,t){this._register(me(e,ht.MOUSE_OVER,n=>t(new jo(Un(e),n))))}onmouseleave(e,t){this._register(me(e,ht.MOUSE_LEAVE,n=>t(new jo(Un(e),n))))}onkeydown(e,t){this._register(me(e,ht.KEY_DOWN,n=>t(new cg(n))))}onkeyup(e,t){this._register(me(e,ht.KEY_UP,n=>t(new cg(n))))}oninput(e,t){this._register(me(e,ht.INPUT,t))}onblur(e,t){this._register(me(e,ht.BLUR,t))}onfocus(e,t){this._register(me(e,ht.FOCUS,t))}onchange(e,t){this._register(me(e,ht.CHANGE,t))}ignoreGesture(e){return tj.ignoreTarget(e)}},mg=11,nj=class extends ip{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=mg+"px",this.domNode.style.height=mg+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Ob),this._register(fg(this.bgDomNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(fg(this.domNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new QC),this._pointerdownScheduleRepeatTimer=this._register(new rp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Un(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},rj=class hh{constructor(t,n,r,s,i,l,a){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,r=r|0,s=s|0,i=i|0,l=l|0,a=a|0),this.rawScrollLeft=s,this.rawScrollTop=a,n<0&&(n=0),s+n>r&&(s=r-n),s<0&&(s=0),i<0&&(i=0),a+i>l&&(a=l-i),a<0&&(a=0),this.width=n,this.scrollWidth=r,this.scrollLeft=s,this.height=i,this.scrollHeight=l,this.scrollTop=a}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new hh(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new hh(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let r=this.width!==t.width,s=this.scrollWidth!==t.scrollWidth,i=this.scrollLeft!==t.scrollLeft,l=this.height!==t.height,a=this.scrollHeight!==t.scrollHeight,c=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:r,scrollWidthChanged:s,scrollLeftChanged:i,heightChanged:l,scrollHeightChanged:a,scrollTopChanged:c}}},sj=class extends be{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new rj(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;t?r=new xg(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):r=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=xg.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},gg=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function hu(e,t){let n=t-e;return function(r){return e+n*oj(r)}}function ij(e,t,n){return function(r){return r2.5*r){let s,i;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},cj=140,Bb=class extends ip{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new aj(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Ob),this._shouldRender=!0,this.domNode=vl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(me(this.domNode.domNode,ht.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new nj(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=vl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof n=="number"&&this.slider.setWidth(n),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(me(this.slider.domNode,ht.POINTER_DOWN,s=>{s.button===0&&(s.preventDefault(),this._sliderPointerDown(s))})),this.onclick(this.slider.domNode,s=>{s.leftButton&&s.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),s=this._sliderPointerPosition(e);n<=s&&s<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,n=e.offsetY;else{let s=JC(this.domNode.domNode);t=e.pageX-s.left,n=e.pageY-s.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,s=>{let i=this._sliderOrthogonalPointerPosition(s),l=Math.abs(i-n);if(Db&&l>cj){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let a=this._sliderPointerPosition(s)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},zb=class ph{constructor(t,n,r,s,i,l){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(r),this._arrowSize=Math.round(t),this._visibleSize=s,this._scrollSize=i,this._scrollPosition=l,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ph(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,r,s,i){let l=Math.max(0,r-t),a=Math.max(0,l-2*n),c=s>0&&s>r;if(!c)return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(r*a/s))),h=(a-u)/(s-r),d=i*h;return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=ph._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,r=this._scrollPosition;return n0&&Math.abs(t.deltaY)>0)return 1;let r=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(r+=.25),n){let s=Math.abs(t.deltaX),i=Math.abs(t.deltaY),l=Math.abs(n.deltaX),a=Math.abs(n.deltaY),c=Math.max(Math.min(s,l),1),u=Math.max(Math.min(i,a),1),h=Math.max(s,l),d=Math.max(i,a);h%c===0&&d%u===0&&(r-=.5)}return Math.min(Math.max(r,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};mh.INSTANCE=new mh;var pj=mh,mj=class extends ip{constructor(e,t,n){super(),this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ne),this.onWillScroll=this._onWillScroll.event,this._options=xj(t),this._scrollable=n,this._register(this._scrollable.onScroll(s=>{this._onWillScroll.fire(s),this._onDidScroll(s),this._onScroll.fire(s)}));let r={onMouseWheel:s=>this._onMouseWheel(s),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new dj(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new uj(this._scrollable,this._options,r)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=vl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=vl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=vl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,s=>this._onMouseOver(s)),this.onmouseleave(this._listenOnDomNode,s=>this._onMouseLeave(s)),this._hideTimeout=this._register(new rp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ws(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Kn&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new dg(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ws(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new dg(n))};this._mouseWheelToDispose.push(me(this._listenOnDomNode,ht.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=pj.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let s=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+s===0?i=s=0:Math.abs(s)>=Math.abs(i)?i=0:s=0),this._options.flipAxes&&([s,i]=[i,s]);let l=!Kn&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||l)&&!i&&(i=s,s=0),e.browserEvent&&e.browserEvent.altKey&&(i=i*this._options.fastScrollSensitivity,s=s*this._options.fastScrollSensitivity);let a=this._scrollable.getFutureScrollPosition(),c={};if(s){let u=vg*s,h=a.scrollTop-(u<0?Math.floor(u):Math.ceil(u));this._verticalScrollbar.writeScrollPosition(c,h)}if(i){let u=vg*i,h=a.scrollLeft-(u<0?Math.floor(u):Math.ceil(u));this._horizontalScrollbar.writeScrollPosition(c,h)}c=this._scrollable.validateScrollPosition(c),(a.scrollLeft!==c.scrollLeft||a.scrollTop!==c.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(c):this._scrollable.setScrollPositionNow(c),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?" left":"",s=t?" top":"",i=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${s}`),this._topLeftShadowDomNode.setClassName(`shadow${i}${s}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),hj)}},gj=class extends mj{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function xj(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Kn&&(t.className+=" mac"),t}var gh=class extends be{constructor(e,t,n,r,s,i,l,a){super(),this._bufferService=n,this._optionsService=l,this._renderService=a,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new sj({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:u=>sp(r.window,u)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new gj(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(s.onProtocolChange(u=>{this._scrollableElement.updateOptions({handleMouseWheel:!(u&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(yt.runAndSubscribe(i.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=i.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register($e(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register($e(()=>this._styleElement.remove())),this._register(yt.runAndSubscribe(i.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${i.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${i.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${i.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(u=>this._handleScroll(u)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};gh=Qe([ie(2,Ft),ie(3,mr),ie(4,_b),ie(5,Si),ie(6,$t),ie(7,gr)],gh);var xh=class extends be{constructor(e,t,n,r,s){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=s,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(i=>this._removeDecoration(i))),this._register($e(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};xh=Qe([ie(1,Ft),ie(2,mr),ie(3,Ql),ie(4,gr)],xh);var vj=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||"full"]&&t<=e.endBufferLine+this._linePadding[n||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},In={full:0,left:0,center:0,right:0},yr={full:0,left:0,center:0,right:0},Bi={full:0,left:0,center:0,right:0},qa=class extends be{constructor(e,t,n,r,s,i,l,a){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=s,this._optionsService=i,this._themeService=l,this._coreBrowserService=a,this._colorZoneStore=new vj,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register($e(()=>this._canvas?.remove()));let c=this._canvas.getContext("2d");if(c)this._ctx=c;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);yr.full=this._canvas.width,yr.left=e,yr.center=t,yr.right=e,this._refreshDrawHeightConstants(),Bi.full=1,Bi.left=1,Bi.center=1+yr.left,Bi.right=1+yr.left+yr.center}_refreshDrawHeightConstants(){In.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);In.left=t,In.center=t,In.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Bi[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-In[e.position||"full"]/2),yr[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+In[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};qa=Qe([ie(2,Ft),ie(3,Ql),ie(4,gr),ie(5,$t),ie(6,Si),ie(7,mr)],qa);var K;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(K||={});var da;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(da||={});var Fb;(e=>e.ST=`${K.ESC}\\`)(Fb||={});var vh=class{constructor(e,t,n,r,s,i){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=s,this._renderService=i,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let n;t.start+=this._dataAlreadySent.length,this._isComposing?n=this._textarea.value.substring(t.start,this._compositionPosition.start):n=this._textarea.value.substring(t.start),n.length>0&&this._coreService.triggerDataEvent(n,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,"");this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};vh=Qe([ie(2,Ft),ie(3,$t),ie(4,Ns),ie(5,gr)],vh);var pt=0,mt=0,gt=0,Ge=0,_g={css:"#00000000",rgba:0},rt;(e=>{function t(s,i,l,a){return a!==void 0?`#${Qr(s)}${Qr(i)}${Qr(l)}${Qr(a)}`:`#${Qr(s)}${Qr(i)}${Qr(l)}`}e.toCss=t;function n(s,i,l,a=255){return(s<<24|i<<16|l<<8|a)>>>0}e.toRgba=n;function r(s,i,l,a){return{css:e.toCss(s,i,l,a),rgba:e.toRgba(s,i,l,a)}}e.toColor=r})(rt||={});var Be;(e=>{function t(c,u){if(Ge=(u.rgba&255)/255,Ge===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,d=u.rgba>>16&255,f=u.rgba>>8&255,p=c.rgba>>24&255,m=c.rgba>>16&255,x=c.rgba>>8&255;pt=p+Math.round((h-p)*Ge),mt=m+Math.round((d-m)*Ge),gt=x+Math.round((f-x)*Ge);let w=rt.toCss(pt,mt,gt),v=rt.toRgba(pt,mt,gt);return{css:w,rgba:v}}e.blend=t;function n(c){return(c.rgba&255)===255}e.isOpaque=n;function r(c,u,h){let d=ha.ensureContrastRatio(c.rgba,u.rgba,h);if(d)return rt.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=r;function s(c){let u=(c.rgba|255)>>>0;return[pt,mt,gt]=ha.toChannels(u),{css:rt.toCss(pt,mt,gt),rgba:u}}e.opaque=s;function i(c,u){return Ge=Math.round(u*255),[pt,mt,gt]=ha.toChannels(c.rgba),{css:rt.toCss(pt,mt,gt,Ge),rgba:rt.toRgba(pt,mt,gt,Ge)}}e.opacity=i;function l(c,u){return Ge=c.rgba&255,i(c,Ge*u/255)}e.multiplyOpacity=l;function a(c){return[c.rgba>>24&255,c.rgba>>16&255,c.rgba>>8&255]}e.toColorRGB=a})(Be||={});var He;(e=>{let t,n;try{let s=document.createElement("canvas");s.width=1,s.height=1;let i=s.getContext("2d",{willReadFrequently:!0});i&&(t=i,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function r(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return pt=parseInt(s.slice(1,2).repeat(2),16),mt=parseInt(s.slice(2,3).repeat(2),16),gt=parseInt(s.slice(3,4).repeat(2),16),rt.toColor(pt,mt,gt);case 5:return pt=parseInt(s.slice(1,2).repeat(2),16),mt=parseInt(s.slice(2,3).repeat(2),16),gt=parseInt(s.slice(3,4).repeat(2),16),Ge=parseInt(s.slice(4,5).repeat(2),16),rt.toColor(pt,mt,gt,Ge);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let i=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(i)return pt=parseInt(i[1]),mt=parseInt(i[2]),gt=parseInt(i[3]),Ge=Math.round((i[5]===void 0?1:parseFloat(i[5]))*255),rt.toColor(pt,mt,gt,Ge);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=s,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[pt,mt,gt,Ge]=t.getImageData(0,0,1,1).data,Ge!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rt.toRgba(pt,mt,gt,Ge),css:s}}e.toColor=r})(He||={});var Rt;(e=>{function t(r){return n(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=t;function n(r,s,i){let l=r/255,a=s/255,c=i/255,u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),h=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);return u*.2126+h*.7152+d*.0722}e.relativeLuminance2=n})(Rt||={});var ha;(e=>{function t(l,a){if(Ge=(a&255)/255,Ge===1)return a;let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=l>>24&255,f=l>>16&255,p=l>>8&255;return pt=d+Math.round((c-d)*Ge),mt=f+Math.round((u-f)*Ge),gt=p+Math.round((h-p)*Ge),rt.toRgba(pt,mt,gt)}e.blend=t;function n(l,a,c){let u=Rt.relativeLuminance(l>>8),h=Rt.relativeLuminance(a>>8);if(Zn(u,h)>8));if(m>8));return m>w?p:x}return p}let d=s(l,a,c),f=Zn(u,Rt.relativeLuminance(d>>8));if(f>8));return f>m?d:p}return d}}e.ensureContrastRatio=n;function r(l,a,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=a>>24&255,p=a>>16&255,m=a>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x0||p>0||m>0);)f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),m-=Math.max(0,Math.ceil(m*.1)),x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));return(f<<24|p<<16|m<<8|255)>>>0}e.reduceLuminance=r;function s(l,a,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=a>>24&255,p=a>>16&255,m=a>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x>>0}e.increaseLuminance=s;function i(l){return[l>>24&255,l>>16&255,l>>8&255,l&255]}e.toChannels=i})(ha||={});function Qr(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Zn(e,t){return e1){let h=this._getJoinedRanges(r,l,i,t,s);for(let d=0;d1){let u=this._getJoinedRanges(r,l,i,t,s);for(let h=0;h=k,G=E,P=this._workCell;if(f.length>0&&E===f[0][0]&&W){let B=f.shift(),he=this._isCellInSelection(B[0],t);for(_=B[0]+1;_=B[1],W?(I=!0,P=new _j(this._workCell,e.translateToString(!0,B[0],B[1]),B[1]-B[0]),G=B[1]-1,O=P.getWidth()):k=B[1]}let z=this._isCellInSelection(E,t),j=n&&E===i,se=R&&E>=u&&E<=h,q=!1;this._decorationService.forEachDecorationAtCell(E,t,void 0,B=>{q=!0});let T=P.getChars()||Dr;if(T===" "&&(P.isUnderline()||P.isOverline())&&(T=" "),A=O*a-c.get(T,P.isBold(),P.isItalic()),!x)x=this._document.createElement("span");else if(w&&(z&&L||!z&&!L&&P.bg===y)&&(z&&L&&p.selectionForeground||P.fg===b)&&P.extended.ext===C&&se===S&&A===N&&!j&&!I&&!q&&W){P.isInvisible()?v+=Dr:v+=T,w++;continue}else w&&(x.textContent=v),x=this._document.createElement("span"),w=0,v="";if(y=P.bg,b=P.fg,C=P.extended.ext,S=se,N=A,L=z,I&&i>=E&&i<=G&&(i=E),!this._coreService.isCursorHidden&&j&&this._coreService.isCursorInitialized){if(D.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&D.push("xterm-cursor-blink"),D.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(s)switch(s){case"outline":D.push("xterm-cursor-outline");break;case"block":D.push("xterm-cursor-block");break;case"bar":D.push("xterm-cursor-bar");break;case"underline":D.push("xterm-cursor-underline");break}}if(P.isBold()&&D.push("xterm-bold"),P.isItalic()&&D.push("xterm-italic"),P.isDim()&&D.push("xterm-dim"),P.isInvisible()?v=Dr:v=P.getChars()||Dr,P.isUnderline()&&(D.push(`xterm-underline-${P.extended.underlineStyle}`),v===" "&&(v=" "),!P.isUnderlineColorDefault()))if(P.isUnderlineColorRGB())x.style.textDecorationColor=`rgb(${Xl.toColorRGB(P.getUnderlineColor()).join(",")})`;else{let B=P.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&P.isBold()&&B<8&&(B+=8),x.style.textDecorationColor=p.ansi[B].css}P.isOverline()&&(D.push("xterm-overline"),v===" "&&(v=" ")),P.isStrikethrough()&&D.push("xterm-strikethrough"),se&&(x.style.textDecoration="underline");let re=P.getFgColor(),ee=P.getFgColorMode(),Q=P.getBgColor(),V=P.getBgColorMode(),Y=!!P.isInverse();if(Y){let B=re;re=Q,Q=B;let he=ee;ee=V,V=he}let oe,pe,Pe=!1;this._decorationService.forEachDecorationAtCell(E,t,void 0,B=>{B.options.layer!=="top"&&Pe||(B.backgroundColorRGB&&(V=50331648,Q=B.backgroundColorRGB.rgba>>8&16777215,oe=B.backgroundColorRGB),B.foregroundColorRGB&&(ee=50331648,re=B.foregroundColorRGB.rgba>>8&16777215,pe=B.foregroundColorRGB),Pe=B.options.layer==="top")}),!Pe&&z&&(oe=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,Q=oe.rgba>>8&16777215,V=50331648,Pe=!0,p.selectionForeground&&(ee=50331648,re=p.selectionForeground.rgba>>8&16777215,pe=p.selectionForeground)),Pe&&D.push("xterm-decoration-top");let $;switch(V){case 16777216:case 33554432:$=p.ansi[Q],D.push(`xterm-bg-${Q}`);break;case 50331648:$=rt.toColor(Q>>16,Q>>8&255,Q&255),this._addStyle(x,`background-color:#${yg((Q>>>0).toString(16),"0",6)}`);break;case 0:default:Y?($=p.foreground,D.push("xterm-bg-257")):$=p.background}switch(oe||P.isDim()&&(oe=Be.multiplyOpacity($,.5)),ee){case 16777216:case 33554432:P.isBold()&&re<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(re+=8),this._applyMinimumContrast(x,$,p.ansi[re],P,oe,void 0)||D.push(`xterm-fg-${re}`);break;case 50331648:let B=rt.toColor(re>>16&255,re>>8&255,re&255);this._applyMinimumContrast(x,$,B,P,oe,pe)||this._addStyle(x,`color:#${yg(re.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(x,$,p.foreground,P,oe,pe)||Y&&D.push("xterm-fg-257")}D.length&&(x.className=D.join(" "),D.length=0),!j&&!I&&!q&&W?w++:x.textContent=v,A!==this.defaultSpacing&&(x.style.letterSpacing=`${A}px`),d.push(x),E=G}return x&&w&&(x.textContent=v),d}_applyMinimumContrast(e,t,n,r,s,i){if(this._optionsService.rawOptions.minimumContrastRatio===1||wj(r.getCode()))return!1;let l=this._getContrastCache(r),a;if(!s&&!i&&(a=l.getColor(t.rgba,n.rgba)),a===void 0){let c=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);a=Be.ensureContrastRatio(s||t,i||n,c),l.setColor((s||t).rgba,(i||n).rgba,a??null)}return a?(this._addStyle(e,`color:${a.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};_h=Qe([ie(1,wb),ie(2,$t),ie(3,mr),ie(4,Ns),ie(5,Ql),ie(6,Si)],_h);function yg(e,t,n){for(;e.length0&&(this._flat[r]=l),l}let s=e;t&&(s+="B"),n&&(s+="I");let i=this._holey.get(s);if(i===void 0){let l=0;t&&(l|=1),n&&(l|=2),i=this._measure(e,l),i>0&&this._holey.set(s,i)}return i}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Cj=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let s=e.buffers.active.ydisp,i=t[1]-s,l=n[1]-s,a=Math.max(i,0),c=Math.min(l,e.rows-1);if(a>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=i,this.viewportEndRow=l,this.viewportCappedStartRow=a,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function jj(){return new Cj}var fu="xterm-dom-renderer-owner-",dn="xterm-rows",Eo="xterm-fg-",bg="xterm-bg-",zi="xterm-focus",Po="xterm-selection",Nj=1,yh=class extends be{constructor(e,t,n,r,s,i,l,a,c,u,h,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=s,this._helperContainer=i,this._linkifier2=l,this._charSizeService=c,this._optionsService=u,this._bufferService=h,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Nj++,this._rowElements=[],this._selectionRenderModel=jj(),this.onRequestRedraw=this._register(new ne).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(dn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Po),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=Sj(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(m=>this._injectCss(m))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(_h,document),this._element.classList.add(fu+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(m=>this._handleLinkHover(m))),this._register(this._linkifier2.onHideLinkUnderline(m=>this._handleLinkLeave(m))),this._register($e(()=>{this._element.classList.remove(fu+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new kj(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let n of this._rowElements)n.style.width=`${this.dimensions.css.canvas.width}px`,n.style.height=`${this.dimensions.css.cell.height}px`,n.style.lineHeight=`${this.dimensions.css.cell.height}px`,n.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${dn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${dn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${dn} .xterm-dim { color: ${Be.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,s=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${s} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Po} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Po} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Po} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[i,l]of e.ansi.entries())t+=`${this._terminalSelector} .${Eo}${i} { color: ${l.css}; }${this._terminalSelector} .${Eo}${i}.xterm-dim { color: ${Be.multiplyOpacity(l,.5).css}; }${this._terminalSelector} .${bg}${i} { background-color: ${l.css}; }`;t+=`${this._terminalSelector} .${Eo}257 { color: ${Be.opaque(e.background).css}; }${this._terminalSelector} .${Eo}257.xterm-dim { color: ${Be.multiplyOpacity(Be.opaque(e.background),.5).css}; }${this._terminalSelector} .${bg}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let n=this._rowElements.length;n<=t;n++){let r=this._document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(zi),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(zi),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,s=this._selectionRenderModel.viewportEndRow,i=this._selectionRenderModel.viewportCappedStartRow,l=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(n){let c=e[0]>t[0];a.appendChild(this._createSelectionElement(i,c?t[0]:e[0],c?e[0]:t[0],l-i+1))}else{let c=r===i?e[0]:0,u=i===s?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(i,c,u));let h=l-i-1;if(a.appendChild(this._createSelectionElement(i+1,0,this._bufferService.cols,h)),i!==l){let d=s===l?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(l,0,d))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,n,r=1){let s=this._document.createElement("div"),i=t*this.dimensions.css.cell.width,l=this.dimensions.css.cell.width*(n-t);return i+l>this.dimensions.css.canvas.width&&(l=this.dimensions.css.canvas.width-i),s.style.height=`${r*this.dimensions.css.cell.height}px`,s.style.top=`${e*this.dimensions.css.cell.height}px`,s.style.left=`${i}px`,s.style.width=`${l}px`,s}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,s=Math.min(n.x,this._bufferService.cols-1),i=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,l=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let u=c+n.ydisp,h=this._rowElements[c],d=n.lines.get(u);if(!h||!d)break;h.replaceChildren(...this._rowFactory.createRow(d,u,u===r,l,a,s,i,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${fu}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,s,i){n<0&&(e=0),r<0&&(t=0);let l=this._bufferService.rows-1;n=Math.max(Math.min(n,l),0),r=Math.max(Math.min(r,l),0),s=Math.min(s,this._bufferService.cols);let a=this._bufferService.buffer,c=a.ybase+a.y,u=Math.min(a.x,s-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=n;p<=r;++p){let m=p+a.ydisp,x=this._rowElements[p],w=a.lines.get(m);if(!x||!w)break;x.replaceChildren(...this._rowFactory.createRow(w,m,m===c,d,f,u,h,this.dimensions.css.cell.width,this._widthCache,i?p===n?e:0:-1,i?(p===r?t:s)-1:-1))}}};yh=Qe([ie(7,Jf),ie(8,Sc),ie(9,$t),ie(10,Ft),ie(11,Ns),ie(12,mr),ie(13,Si)],yh);var bh=class extends be{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ne),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Pj(this._optionsService))}catch{this._measureStrategy=this._register(new Ej(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};bh=Qe([ie(2,$t)],bh);var $b=class extends be{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},Ej=class extends $b{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Pj=class extends $b{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Aj=class extends be{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Tj(this._window)),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ne),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(r=>this._screenDprMonitor.setWindow(r))),this._register(yt.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(me(this._textarea,"focus",()=>this._isFocused=!0)),this._register(me(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Tj=class extends be{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new xi),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register($e(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=me(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Lj=class extends be{constructor(){super(),this.linkProviders=[],this._register($e(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function lp(e,t,n){let r=n.getBoundingClientRect(),s=e.getComputedStyle(n),i=parseInt(s.getPropertyValue("padding-left")),l=parseInt(s.getPropertyValue("padding-top"));return[t.clientX-r.left-i,t.clientY-r.top-l]}function Dj(e,t,n,r,s,i,l,a,c){if(!i)return;let u=lp(e,t,n);if(u)return u[0]=Math.ceil((u[0]+(c?l/2:0))/l),u[1]=Math.ceil(u[1]/a),u[0]=Math.min(Math.max(u[0],1),r+(c?1:0)),u[1]=Math.min(Math.max(u[1],1),s),u}var wh=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,s){return Dj(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(e,t){let n=lp(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};wh=Qe([ie(0,gr),ie(1,Sc)],wh);var Rj=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Wb={};U1(Wb,{getSafariVersion:()=>Ij,isChromeOS:()=>Vb,isFirefox:()=>Hb,isIpad:()=>Oj,isIphone:()=>Bj,isLegacyEdge:()=>Mj,isLinux:()=>op,isMac:()=>Ka,isNode:()=>kc,isSafari:()=>Ub,isWindows:()=>qb});var kc=typeof process<"u"&&"title"in process,Jl=kc?"node":navigator.userAgent,Zl=kc?"node":navigator.platform,Hb=Jl.includes("Firefox"),Mj=Jl.includes("Edge"),Ub=/^((?!chrome|android).)*safari/i.test(Jl);function Ij(){if(!Ub)return 0;let e=Jl.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Ka=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zl),Oj=Zl==="iPad",Bj=Zl==="iPhone",qb=["Windows","Win16","Win32","WinCE"].includes(Zl),op=Zl.indexOf("Linux")>=0,Vb=/\bCrOS\b/.test(Jl),Kb=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._is){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=s}this.clear()}},zj=class extends Kb{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Fj=class extends Kb{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ga=!kc&&"requestIdleCallback"in window?Fj:zj,$j=class{constructor(){this._queue=new Ga}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Sh=class extends be{constructor(e,t,n,r,s,i,l,a,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=s,this._coreBrowserService=a,this._renderer=this._register(new xi),this._pausedResizeTask=new $j,this._observerDisposable=this._register(new xi),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ne),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ne),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ne),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Rj((u,h)=>this._renderRows(u,h),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Wj(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register($e(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(l.onResize(()=>this._fullRefresh())),this._register(l.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(i.onDecorationRegistered(()=>this._fullRefresh())),this._register(i.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(l.cols,l.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(l.buffer.y,l.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(u=>this._registerIntersectionObserver(u,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let n=new e.IntersectionObserver(r=>this._handleIntersectionChange(r[r.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=$e(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Sh=Qe([ie(2,$t),ie(3,Sc),ie(4,Ns),ie(5,Ql),ie(6,Ft),ie(7,mr),ie(8,Si)],Sh);var Wj=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Hj(e,t,n,r){let s=n.buffer.x,i=n.buffer.y;if(!n.buffer.hasScrollback)return Vj(s,i,e,t,n,r)+Cc(i,t,n,r)+Kj(s,i,e,t,n,r);let l;if(i===t)return l=s>e?"D":"C",Fl(Math.abs(s-e),zl(l,r));l=i>t?"D":"C";let a=Math.abs(i-t),c=qj(i>t?e:s,n)+(a-1)*n.cols+1+Uj(i>t?s:e);return Fl(c,zl(l,r))}function Uj(e,t){return e-1}function qj(e,t){return t.cols-e}function Vj(e,t,n,r,s,i){return Cc(t,r,s,i).length===0?"":Fl(Yb(e,t,e,t-Ss(t,s),!1,s).length,zl("D",i))}function Cc(e,t,n,r){let s=e-Ss(e,n),i=t-Ss(t,n),l=Math.abs(s-i)-Gj(e,t,n);return Fl(l,zl(Gb(e,t),r))}function Kj(e,t,n,r,s,i){let l;Cc(t,r,s,i).length>0?l=r-Ss(r,s):l=t;let a=r,c=Yj(e,t,n,r,s,i);return Fl(Yb(e,l,n,a,c==="C",s).length,zl(c,i))}function Gj(e,t,n){let r=0,s=e-Ss(e,n),i=t-Ss(t,n);for(let l=0;l=0&&e0?l=r-Ss(r,s):l=t,e=n&&lt?"A":"B"}function Yb(e,t,n,r,s,i){let l=e,a=t,c="";for(;(l!==n||a!==r)&&a>=0&&ai.cols-1?(c+=i.buffer.translateBufferLineToString(a,!1,e,l),l=0,e=0,a++):!s&&l<0&&(c+=i.buffer.translateBufferLineToString(a,!1,0,e+1),l=i.cols-1,e=l,a--);return c+i.buffer.translateBufferLineToString(a,!1,e,l)}function zl(e,t){let n=t?"O":"[";return K.ESC+n+e}function Fl(e,t){e=Math.floor(e);let n="";for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function wg(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var pu=50,Qj=15,Jj=50,Zj=500,eN=" ",tN=new RegExp(eN,"g"),kh=class extends be{constructor(e,t,n,r,s,i,l,a,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=s,this._mouseService=i,this._optionsService=l,this._renderService=a,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new yn,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ne),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ne),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=u=>this._handleMouseMove(u),this._mouseUpListener=u=>this._handleMouseUp(u),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(u=>this._handleTrim(u)),this._register(this._bufferService.buffers.onBufferActivate(u=>this._handleBufferActivate(u))),this.enable(),this._model=new Xj(this._bufferService),this._activeSelectionMode=0,this._register($e(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(u=>{u.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let s=e[0]s.replace(tN," ")).join(qb?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),op&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=wg(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=lp(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-pu),pu),t/=pu,t/Math.abs(t)+Math.round(t*(Qj-1)))}shouldForceSelection(e){return Ka?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Jj)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Ka&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let s=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:s>1&&t!==r&&(n+=s-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let s=this._bufferService.buffer,i=s.lines.get(e[1]);if(!i)return;let l=s.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(i,e[0]),c=a,u=e[0]-a,h=0,d=0,f=0,p=0;if(l.charAt(a)===" "){for(;a>0&&l.charAt(a-1)===" ";)a--;for(;c1&&(p+=_-1,c+=_-1);w>0&&a>0&&!this._isCharWordSeparator(i.loadCell(w-1,this._workCell));){i.loadCell(w-1,this._workCell);let y=this._workCell.getChars().length;this._workCell.getWidth()===0?(h++,w--):y>1&&(f+=y-1,a-=y-1),a--,w--}for(;v1&&(p+=y-1,c+=y-1),c++,v++}}c++;let m=a+u-h+f,x=Math.min(this._bufferService.cols,c-a+h+d-f-p);if(!(!t&&l.slice(a,c).trim()==="")){if(n&&m===0&&i.getCodePoint(0)!==32){let w=s.lines.get(e[1]-1);if(w&&i.isWrapped&&w.getCodePoint(this._bufferService.cols-1)!==32){let v=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(v){let _=this._bufferService.cols-v.start;m-=_,x+=_}}}if(r&&m+x===this._bufferService.cols&&i.getCodePoint(this._bufferService.cols-1)!==32){let w=s.lines.get(e[1]+1);if(w?.isWrapped&&w.getCodePoint(0)!==32){let v=this._getWordAt([0,e[1]+1],!1,!1,!0);v&&(x+=v.length)}}return{start:m,length:x}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=wg(n,this._bufferService.cols)}};kh=Qe([ie(3,Ft),ie(4,Ns),ie(5,Zf),ie(6,$t),ie(7,gr),ie(8,mr)],kh);var Sg=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},kg=class{constructor(){this._color=new Sg,this._css=new Sg}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},it=Object.freeze((()=>{let e=[He.toColor("#2e3436"),He.toColor("#cc0000"),He.toColor("#4e9a06"),He.toColor("#c4a000"),He.toColor("#3465a4"),He.toColor("#75507b"),He.toColor("#06989a"),He.toColor("#d3d7cf"),He.toColor("#555753"),He.toColor("#ef2929"),He.toColor("#8ae234"),He.toColor("#fce94f"),He.toColor("#729fcf"),He.toColor("#ad7fa8"),He.toColor("#34e2e2"),He.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],s=t[n/6%6|0],i=t[n%6];e.push({css:rt.toCss(r,s,i),rgba:rt.toRgba(r,s,i)})}for(let n=0;n<24;n++){let r=8+n*10;e.push({css:rt.toCss(r,r,r),rgba:rt.toRgba(r,r,r)})}return e})()),ss=He.toColor("#ffffff"),il=He.toColor("#000000"),Cg=He.toColor("#ffffff"),jg=il,Fi={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},nN=ss,Ch=class extends be{constructor(e){super(),this._optionsService=e,this._contrastCache=new kg,this._halfContrastCache=new kg,this._onChangeColors=this._register(new ne),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ss,background:il,cursor:Cg,cursorAccent:jg,selectionForeground:void 0,selectionBackgroundTransparent:Fi,selectionBackgroundOpaque:Be.blend(il,Fi),selectionInactiveBackgroundTransparent:Fi,selectionInactiveBackgroundOpaque:Be.blend(il,Fi),scrollbarSliderBackground:Be.opacity(ss,.2),scrollbarSliderHoverBackground:Be.opacity(ss,.4),scrollbarSliderActiveBackground:Be.opacity(ss,.5),overviewRulerBorder:ss,ansi:it.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Te(e.foreground,ss),t.background=Te(e.background,il),t.cursor=Be.blend(t.background,Te(e.cursor,Cg)),t.cursorAccent=Be.blend(t.background,Te(e.cursorAccent,jg)),t.selectionBackgroundTransparent=Te(e.selectionBackground,Fi),t.selectionBackgroundOpaque=Be.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Te(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Be.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Te(e.selectionForeground,_g):void 0,t.selectionForeground===_g&&(t.selectionForeground=void 0),Be.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Be.opacity(t.selectionBackgroundTransparent,.3)),Be.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Be.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Te(e.scrollbarSliderBackground,Be.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Te(e.scrollbarSliderHoverBackground,Be.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Te(e.scrollbarSliderActiveBackground,Be.opacity(t.foreground,.5)),t.overviewRulerBorder=Te(e.overviewRulerBorder,nN),t.ansi=it.slice(),t.ansi[0]=Te(e.black,it[0]),t.ansi[1]=Te(e.red,it[1]),t.ansi[2]=Te(e.green,it[2]),t.ansi[3]=Te(e.yellow,it[3]),t.ansi[4]=Te(e.blue,it[4]),t.ansi[5]=Te(e.magenta,it[5]),t.ansi[6]=Te(e.cyan,it[6]),t.ansi[7]=Te(e.white,it[7]),t.ansi[8]=Te(e.brightBlack,it[8]),t.ansi[9]=Te(e.brightRed,it[9]),t.ansi[10]=Te(e.brightGreen,it[10]),t.ansi[11]=Te(e.brightYellow,it[11]),t.ansi[12]=Te(e.brightBlue,it[12]),t.ansi[13]=Te(e.brightMagenta,it[13]),t.ansi[14]=Te(e.brightCyan,it[14]),t.ansi[15]=Te(e.brightWhite,it[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;ri.index-l.index),r=[];for(let i of n){let l=this._services.get(i.id);if(!l)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${i.id._id}.`);r.push(l)}let s=n.length>0?n[0].index:t.length;if(t.length!==s)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${s+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},iN={trace:0,debug:1,info:2,warn:3,error:4,off:5},lN="xterm.js: ",jh=class extends be{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=iN[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;r--)this._array[this._getCyclicIndex(r+n.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;rthis._maxLength){let r=this._length+n.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+n<0)throw new Error("Cannot shift elements in list beyond index 0");if(n>0){for(let s=t-1;s>=0;s--)this.set(e+s+n,this.get(e+s));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r]}set(t,n){this._data[t*ye+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*ye+0]=t|2097152|n[2]<<22):this._data[t*ye+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*ye+0]>>22}hasWidth(t){return this._data[t*ye+0]&12582912}getFg(t){return this._data[t*ye+1]}getBg(t){return this._data[t*ye+2]}hasContent(t){return this._data[t*ye+0]&4194303}getCodePoint(t){let n=this._data[t*ye+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*ye+0]&2097152}getString(t){let n=this._data[t*ye+0];return n&2097152?this._combined[t]:n&2097151?jr(n&2097151):""}isProtected(t){return this._data[t*ye+2]&536870912}loadCell(t,n){return Ao=t*ye,n.content=this._data[Ao+0],n.fg=this._data[Ao+1],n.bg=this._data[Ao+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*ye+0]=n.content,this._data[t*ye+1]=n.fg,this._data[t*ye+2]=n.bg}setCellFromCodepoint(t,n,r,s){s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*ye+0]=n|r<<22,this._data[t*ye+1]=s.fg,this._data[t*ye+2]=s.bg}addCodepointToCell(t,n,r){let s=this._data[t*ye+0];s&2097152?this._combined[t]+=jr(n):s&2097151?(this._combined[t]=jr(s&2097151)+jr(n),s&=-2097152,s|=2097152):s=n|1<<22,r&&(s&=-12582913,s|=r<<22),this._data[t*ye+0]=s}insertCells(t,n,r){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,r),n=0;--i)this.setCell(t+n+i,this.loadCell(t+i,s));for(let i=0;ithis.length){if(this._data.buffer.byteLength>=r*4)this._data=new Uint32Array(this._data.buffer,0,r);else{let s=new Uint32Array(r);s.set(this._data),this._data=s}for(let s=this.length;s=t&&delete this._combined[a]}let i=Object.keys(this._extendedAttrs);for(let l=0;l=t&&delete this._extendedAttrs[a]}}return this.length=t,r*4*mu=0;--t)if(this._data[t*ye+0]&4194303)return t+(this._data[t*ye+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ye+0]&4194303||this._data[t*ye+2]&50331648)return t+(this._data[t*ye+0]>>22);return 0}copyCellsFrom(t,n,r,s,i){let l=t._data;if(i)for(let c=s-1;c>=0;c--){for(let u=0;u=n&&(this._combined[u-n+r]=t._combined[u])}}translateToString(t,n,r,s){n=n??0,r=r??this.length,t&&(r=Math.min(r,this.getTrimmedLength())),s&&(s.length=0);let i="";for(;n>22||1}return s&&s.push(n),i}};function oN(e,t,n,r,s,i){let l=[];for(let a=0;a=a&&r0&&(w>d||h[w].getTrimmedLength()===0);w--)x++;x>0&&(l.push(a+h.length-x),l.push(x)),a+=h.length-1}return l}function aN(e,t){let n=[],r=0,s=t[r],i=0;for(let l=0;l$l(e,u,t)).reduce((c,u)=>c+u),i=0,l=0,a=0;for(;ac&&(i-=c,l++);let u=e[l].getWidth(i-1)===2;u&&i--;let h=u?n-1:n;r.push(h),a+=h}return r}function $l(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,s=e[t+1].getWidth(0)===2;return r&&s?n-1:n}var Qb=class Jb{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Jb._nextId++,this._onDispose=this.register(new ne),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ws(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Qb._nextId=1;var dN=Qb,ut={},is=ut.B;ut[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ut.A={"#":"£"};ut.B=void 0;ut[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ut.C=ut[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ut.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ut.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ut.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ut.E=ut[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ut.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ut.H=ut[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Eg=4294967295,Pg=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=nt.clone(),this.savedCharset=is,this.markers=[],this._nullCell=yn.fromCharData([0,mb,1,0]),this._whitespaceCell=yn.fromCharData([0,Dr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ga,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Ng(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Ua),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Ua),this._whitespaceCell}getBlankLine(e,t){return new ll(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eEg?Eg:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=nt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Ng(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(nt),r=0,s=this._getCorrectBufferLength(t);if(s>this.lines.maxLength&&(this.lines.maxLength=s),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+i+1?(this.ybase--,i++,this.ydisp>0&&this.ydisp--):this.lines.push(new ll(e,n)));else for(let l=this._rows;l>t;l--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(s0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=s}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),i&&(this.y+=i),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let i=0;i.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=oN(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(nt),n);if(r.length>0){let s=aN(this.lines,r);cN(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(nt),s=n;for(;s-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let a=this.lines.get(l);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let c=[a];for(;a.isWrapped&&l>0;)a=this.lines.get(--l),c.unshift(a);if(!n){let y=this.ybase+this.y;if(y>=l&&y0&&(s.push({start:l+c.length+i,newLines:p}),i+=p.length),c.push(...p);let m=h.length-1,x=h[m];x===0&&(m--,x=h[m]);let w=c.length-d-1,v=u;for(;w>=0;){let y=Math.min(v,x);if(c[m]===void 0)break;if(c[m].copyCellsFrom(c[w],v-y,x-y,y,!0),x-=y,x===0&&(m--,x=h[m]),v-=y,v===0){w--;let b=Math.max(w,0);v=$l(c,b,this._cols)}}for(let y=0;y0;)this.ybase===0?this.y0){let l=[],a=[];for(let x=0;x=0;x--)if(d&&d.start>u+f){for(let w=d.newLines.length-1;w>=0;w--)this.lines.set(x--,d.newLines[w]);x++,l.push({index:u+1,amount:d.newLines.length}),f+=d.newLines.length,d=s[++h]}else this.lines.set(x,a[u--]);let p=0;for(let x=l.length-1;x>=0;x--)l[x].index+=p,this.lines.onInsertEmitter.fire(l[x]),p+=l[x].amount;let m=Math.max(0,c+i-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(e,t,n=0,r){let s=this.lines.get(e);return s?s.translateToString(t,n,r):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.linen.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},hN=class extends be{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ne),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Pg(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Pg(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Zb=2,ew=1,Nh=class extends be{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Zb),this.rows=Math.max(e.rawOptions.rows||0,ew),this.buffers=this._register(new hN(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let s=n.ybase+n.scrollTop,i=n.ybase+n.scrollBottom;if(n.scrollTop===0){let l=n.lines.isFull;i===n.lines.length-1?l?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(i+1,0,r.clone()),l?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let l=i-s+1;n.lines.shiftElements(s+1,l-1,-1),n.lines.set(i,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Nh=Qe([ie(0,$t)],Nh);var Ds={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Ka,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},fN=["normal","bold","100","200","300","400","500","600","700","800","900"],pN=class extends be{constructor(e){super(),this._onOptionChange=this._register(new ne),this.onOptionChange=this._onOptionChange.event;let t={...Ds};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(r){console.error(r)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register($e(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=n=>{if(!(n in Ds))throw new Error(`No option with key "${n}"`);return this.rawOptions[n]},t=(n,r)=>{if(!(n in Ds))throw new Error(`No option with key "${n}"`);r=this._sanitizeAndValidateOption(n,r),this.rawOptions[n]!==r&&(this.rawOptions[n]=r,this._onOptionChange.fire(n))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ds[e]),!mN(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ds[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=fN.includes(t)?t:Ds[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function mN(e){return e==="block"||e==="underline"||e==="bar"}function ol(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&ol(e[r],t-1);return n}var Ag=Object.freeze({insertMode:!1}),Tg=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Eh=class extends be{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ne),this.onData=this._onData.event,this._onUserInput=this._register(new ne),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ne),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=ol(Ag),this.decPrivateModes=ol(Tg)}reset(){this.modes=ol(Ag),this.decPrivateModes=ol(Tg)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(r=>r.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};Eh=Qe([ie(0,Ft),ie(1,yb),ie(2,$t)],Eh);var Lg={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function gu(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var xu=String.fromCharCode,Dg={DEFAULT:e=>{let t=[gu(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${xu(t[0])}${xu(t[1])}${xu(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${gu(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${gu(e,!0)};${e.x};${e.y}${t}`}},Ph=class extends be{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ne),this.onProtocolChange=this._onProtocolChange.event;for(let r of Object.keys(Lg))this.addProtocol(r,Lg[r]);for(let r of Object.keys(Dg))this.addEncoding(r,Dg[r]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,s=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(s/=r+0,Math.abs(e.deltaY)<50&&(s*=.3),this._wheelPartialScroll+=s,s=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(s*=this._bufferService.rows),s}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Ph=Qe([ie(0,Ft),ie(1,Ns),ie(2,$t)],Ph);var vu=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],gN=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],lt;function xN(e,t){let n=0,r=t.length-1,s;if(et[r][1])return!1;for(;r>=n;)if(s=n+r>>1,e>t[s][1])n=s+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let s=ds.extractWidth(t);s===0?r=!1:s>n&&(n=s)}return ds.createPropertyValue(0,n,r)}},ds=class fa{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ne,this.onChange=this._onChange.event;let t=new vN;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,r=!1){return(t&16777215)<<3|(n&3)<<1|(r?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,r=0,s=t.length;for(let i=0;i=s)return n+this.wcwidth(l);let u=t.charCodeAt(i);56320<=u&&u<=57343?l=(l-55296)*1024+u-56320+65536:n+=this.wcwidth(u)}let a=this.charProperties(l,r),c=fa.extractWidth(a);fa.extractShouldJoin(a)&&(c-=fa.extractWidth(r)),n+=c,r=a}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},_N=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Rg(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var $i=2147483647,yN=256,tw=class Ah{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>yN)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new Ah;if(!t.length)return n;for(let r=Array.isArray(t[0])?1:0;r>8,s=this._subParamsIdx[n]&255;s-r>0&&t.push(Array.prototype.slice.call(this._subParams,r,s))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>$i?$i:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>$i?$i:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;return r-n>0?this._subParams.subarray(n,r):null}getSubParamsAll(){let t={};for(let n=0;n>8,s=this._subParamsIdx[n]&255;s-r>0&&(t[n]=this._subParams.slice(r,s))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,s=r[n-1];r[n-1]=~s?Math.min(s*10+t,$i):t}},Wi=[],bN=class{constructor(){this._state=0,this._active=Wi,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Wi}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Wi,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Wi,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,"PUT",wc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let n=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Wi,this._id=-1,this._state=0}}},en=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=wc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(n=>(this._data="",this._hitLimit=!1,n));return this._data="",this._hitLimit=!1,t}},Hi=[],wN=class{constructor(){this._handlers=Object.create(null),this._active=Hi,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Hi}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Hi,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Hi,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let n=this._active.length-1;n>=0;n--)this._active[n].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,"PUT",wc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let n=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Hi,this._ident=0}},al=new tw;al.addParam(0);var Mg=class{constructor(e){this._handler=e,this._data="",this._params=al,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():al,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=wc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=al,this._data="",this._hitLimit=!1,n));return this._params=al,this._data="",this._hitLimit=!1,t}},SN=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let s=0;sc),n=(a,c)=>t.slice(a,c),r=n(32,127),s=n(0,24);s.push(25),s.push.apply(s,n(28,32));let i=n(0,14),l;e.setDefault(1,0),e.addMany(r,0,2,0);for(l in i)e.addMany([24,26,153,154],l,3,0),e.addMany(n(128,144),l,3,0),e.addMany(n(144,152),l,3,0),e.add(156,l,0,0),e.add(27,l,11,1),e.add(157,l,4,8),e.addMany([152,158,159],l,0,7),e.add(155,l,11,3),e.add(144,l,11,9);return e.addMany(s,0,3,0),e.addMany(s,1,3,1),e.add(127,1,0,1),e.addMany(s,8,0,8),e.addMany(s,3,3,3),e.add(127,3,0,3),e.addMany(s,4,3,4),e.add(127,4,0,4),e.addMany(s,6,3,6),e.addMany(s,5,3,5),e.add(127,5,0,5),e.addMany(s,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(s,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(s,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(s,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(s,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(s,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(s,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(pn,0,2,0),e.add(pn,8,5,8),e.add(pn,6,0,6),e.add(pn,11,0,11),e.add(pn,13,13,13),e}(),CN=class extends be{constructor(e=kN){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new tw,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,n,r)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,n)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register($e(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new bN),this._dcsParser=this._register(new wN),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let s=0;si||i>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");n<<=8,n|=i}}if(e.final.length!==1)throw new Error("final must be a single byte");let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,s){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=s}parse(e,t,n){let r=0,s=0,i=0,l;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,i=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let a=this._parseStack.handlers,c=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&c>-1){for(;c>=0&&(l=a[c](this._params),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 4:if(n===!1&&c>-1){for(;c>=0&&(l=a[c](),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],l=this._dcsParser.unhook(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],l=this._oscParser.end(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,i=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=i;a>4){case 2:for(let f=a+1;;++f){if(f>=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=0&&(l=c[u](this._params),l!==!0);u--)if(l instanceof Promise)return this._preserveStack(3,c,u,s,a),l;u<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++a47&&r<60);a--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let h=this._escHandlers[this._collect<<8|r],d=h?h.length-1:-1;for(;d>=0&&(l=h[d](),l!==!0);d--)if(l instanceof Promise)return this._preserveStack(4,h,d,s,a),l;d<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let f=a+1;;++f)if(f>=t||(r=e[f])===24||r===26||r===27||r>127&&r=t||(r=e[f])<32||r>127&&r>4:i>>8}return r}}function _u(e,t){let n=e.toString(16),r=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function EN(e,t=16){let[n,r,s]=e;return`rgb:${_u(n,t)}/${_u(r,t)}/${_u(s,t)}`}var PN={"(":0,")":1,"*":2,"+":3,"-":1,".":2},br=131072,Og=10;function Bg(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var zg=5e3,Fg=0,AN=class extends be{constructor(e,t,n,r,s,i,l,a,c=new CN){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=s,this._oscLinkService=i,this._coreMouseService=l,this._unicodeService=a,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Y1,this._utf8Decoder=new X1,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone(),this._onRequestBell=this._register(new ne),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ne),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ne),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ne),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ne),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ne),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ne),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ne),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ne),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Th(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,h)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:h.toArray()})}),this._parser.setEscHandlerFallback(u=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(u)})}),this._parser.setExecuteHandlerFallback(u=>{this._logService.debug("Unknown EXECUTE code: ",{code:u})}),this._parser.setOscHandlerFallback((u,h,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:h,data:d})}),this._parser.setDcsHandlerFallback((u,h,d)=>{h==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:h,payload:d})}),this._parser.setPrintHandler((u,h,d)=>this.print(u,h,d)),this._parser.registerCsiHandler({final:"@"},u=>this.insertChars(u)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},u=>this.scrollLeft(u)),this._parser.registerCsiHandler({final:"A"},u=>this.cursorUp(u)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},u=>this.scrollRight(u)),this._parser.registerCsiHandler({final:"B"},u=>this.cursorDown(u)),this._parser.registerCsiHandler({final:"C"},u=>this.cursorForward(u)),this._parser.registerCsiHandler({final:"D"},u=>this.cursorBackward(u)),this._parser.registerCsiHandler({final:"E"},u=>this.cursorNextLine(u)),this._parser.registerCsiHandler({final:"F"},u=>this.cursorPrecedingLine(u)),this._parser.registerCsiHandler({final:"G"},u=>this.cursorCharAbsolute(u)),this._parser.registerCsiHandler({final:"H"},u=>this.cursorPosition(u)),this._parser.registerCsiHandler({final:"I"},u=>this.cursorForwardTab(u)),this._parser.registerCsiHandler({final:"J"},u=>this.eraseInDisplay(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},u=>this.eraseInDisplay(u,!0)),this._parser.registerCsiHandler({final:"K"},u=>this.eraseInLine(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},u=>this.eraseInLine(u,!0)),this._parser.registerCsiHandler({final:"L"},u=>this.insertLines(u)),this._parser.registerCsiHandler({final:"M"},u=>this.deleteLines(u)),this._parser.registerCsiHandler({final:"P"},u=>this.deleteChars(u)),this._parser.registerCsiHandler({final:"S"},u=>this.scrollUp(u)),this._parser.registerCsiHandler({final:"T"},u=>this.scrollDown(u)),this._parser.registerCsiHandler({final:"X"},u=>this.eraseChars(u)),this._parser.registerCsiHandler({final:"Z"},u=>this.cursorBackwardTab(u)),this._parser.registerCsiHandler({final:"`"},u=>this.charPosAbsolute(u)),this._parser.registerCsiHandler({final:"a"},u=>this.hPositionRelative(u)),this._parser.registerCsiHandler({final:"b"},u=>this.repeatPrecedingCharacter(u)),this._parser.registerCsiHandler({final:"c"},u=>this.sendDeviceAttributesPrimary(u)),this._parser.registerCsiHandler({prefix:">",final:"c"},u=>this.sendDeviceAttributesSecondary(u)),this._parser.registerCsiHandler({final:"d"},u=>this.linePosAbsolute(u)),this._parser.registerCsiHandler({final:"e"},u=>this.vPositionRelative(u)),this._parser.registerCsiHandler({final:"f"},u=>this.hVPosition(u)),this._parser.registerCsiHandler({final:"g"},u=>this.tabClear(u)),this._parser.registerCsiHandler({final:"h"},u=>this.setMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"h"},u=>this.setModePrivate(u)),this._parser.registerCsiHandler({final:"l"},u=>this.resetMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"l"},u=>this.resetModePrivate(u)),this._parser.registerCsiHandler({final:"m"},u=>this.charAttributes(u)),this._parser.registerCsiHandler({final:"n"},u=>this.deviceStatus(u)),this._parser.registerCsiHandler({prefix:"?",final:"n"},u=>this.deviceStatusPrivate(u)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},u=>this.softReset(u)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},u=>this.setCursorStyle(u)),this._parser.registerCsiHandler({final:"r"},u=>this.setScrollRegion(u)),this._parser.registerCsiHandler({final:"s"},u=>this.saveCursor(u)),this._parser.registerCsiHandler({final:"t"},u=>this.windowOptions(u)),this._parser.registerCsiHandler({final:"u"},u=>this.restoreCursor(u)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},u=>this.insertColumns(u)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},u=>this.deleteColumns(u)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},u=>this.selectProtected(u)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},u=>this.requestMode(u,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},u=>this.requestMode(u,!1)),this._parser.setExecuteHandler(K.BEL,()=>this.bell()),this._parser.setExecuteHandler(K.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(K.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(K.BS,()=>this.backspace()),this._parser.setExecuteHandler(K.HT,()=>this.tab()),this._parser.setExecuteHandler(K.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(K.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(da.IND,()=>this.index()),this._parser.setExecuteHandler(da.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(da.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new en(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new en(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new en(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new en(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new en(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new en(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new en(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new en(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new en(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new en(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new en(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new en(u=>this.restoreCursorColor(u))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let u in ut)this._parser.registerEscHandler({intermediates:"(",final:u},()=>this.selectCharset("("+u)),this._parser.registerEscHandler({intermediates:")",final:u},()=>this.selectCharset(")"+u)),this._parser.registerEscHandler({intermediates:"*",final:u},()=>this.selectCharset("*"+u)),this._parser.registerEscHandler({intermediates:"+",final:u},()=>this.selectCharset("+"+u)),this._parser.registerEscHandler({intermediates:"-",final:u},()=>this.selectCharset("-"+u)),this._parser.registerEscHandler({intermediates:".",final:u},()=>this.selectCharset("."+u)),this._parser.registerEscHandler({intermediates:"/",final:u},()=>this.selectCharset("/"+u));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(u=>(this._logService.error("Parsing error: ",u),u)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Mg((u,h)=>this.requestStatusString(u,h)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),zg))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${zg} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,s=this._activeBuffer.y,i=0,l=this._parseStack.paused;if(l){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,s=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>br&&(i=this._parseStack.position+br)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,u=>String.fromCharCode(u)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(u=>u.charCodeAt(0)):e),this._parseBuffer.lengthbr)for(let u=i;u0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let f=this._parser.precedingJoinState;for(let p=t;pa){if(c){let v=d,_=this._activeBuffer.x-w;for(this._activeBuffer.x=w,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),w>0&&d instanceof ll&&d.copyCellsFrom(v,_,0,w,!1);_=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(u&&(d.insertCells(this._activeBuffer.x,s-w,this._activeBuffer.getNullCell(h)),d.getWidth(a-1)===2&&d.setCellFromCodepoint(a-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,r,s,h),s>0)for(;--s;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>Bg(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Mg(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new en(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,s=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),s),r&&(i.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=a;for(let u=1;u0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(K.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(K.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(K.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(K.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(K.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(x[x.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",x[x.SET=1]="SET",x[x.RESET=2]="RESET",x[x.PERMANENTLY_SET=3]="PERMANENTLY_SET",x[x.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:i}=this._coreMouseService,l=this._coreService,{buffers:a,cols:c}=this._bufferService,{active:u,alt:h}=a,d=this._optionsService.rawOptions,f=(x,w)=>(l.triggerDataEvent(`${K.ESC}[${t?"":"?"}${x};${w}$y`),!0),p=x=>x?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(l.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:c===132?1:0:0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(s==="X10")):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!l.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(s==="VT200")):m===1002?f(m,p(s==="DRAG")):m===1003?f(m,p(s==="ANY")):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(i==="SGR")):m===1015?f(m,4):m===1016?f(m,p(i==="SGR_PIXELS")):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(u===h)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,s){return t===2?(e|=50331648,e&=-16777216,e|=Xl.fromColorRGB([n,r,s])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],s=0,i=0;do{if(r[i+s]=e.params[t+i],e.hasSubParams(t+i)){let l=e.getSubParams(t+i),a=0;do r[1]===5&&(s=1),r[i+a+1+s]=l[a];while(++a=2||r[1]===2&&i+s>=5)break;r[1]&&(s=1)}while(++i+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=nt.fg,e.bg=nt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let s=0;s=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777216|n-90|8):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777216|n-100|8):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(s)?e.getSubParams(s)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=nt.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=nt.bg&16777215):n===38||n===48||n===58?s+=this._extractColor(e,s,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=nt.fg&16777215,r.bg&=-67108864,r.bg|=nt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${K.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[?${t};${n}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=nt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Bg(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${K.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Og&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Og&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let r=n.shift(),s=n.shift();if(/^\d+$/.exec(r)){let i=parseInt(r);if($g(i))if(s==="?")t.push({type:0,index:i});else{let l=Ig(s);l&&t.push({type:1,index:i,color:l})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),r,s=n.findIndex(i=>i.startsWith("id="));return s!==-1&&(r=n[s].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let r=0;r=this._specialColors.length);++r,++t)if(n[r]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let s=Ig(n[r]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let r=0;r=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new yn;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${K.ESC}${l}${K.ESC}\\`),!0),r=this._bufferService.buffer,s=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Th=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Fg=e,e=t,t=Fg),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Th=Qe([ie(0,Ft)],Th);function $g(e){return 0<=e&&e<256}var TN=5e7,Wg=12,LN=50,DN=class extends be{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>TN)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let r=this._writeBuffer[this._bufferOffset],s=this._action(r,t);if(s){let l=a=>performance.now()-n>=Wg?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(n,a);s.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(l);return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-n>=Wg)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>LN&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Lh=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),c={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(c,a)),this._dataByLinkId.set(c.id,c),c.id}let n=e,r=this._getEntryIdKey(n),s=this._entriesWithId.get(r);if(s)return this.addLineToLink(s.id,t.ybase+t.y),s.id;let i=t.addMarker(t.ybase+t.y),l={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(l,i)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(r=>r.line!==t)){let r=this._bufferService.buffer.addMarker(t);n.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(n,r))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Lh=Qe([ie(0,Ft)],Lh);var Hg=!1,RN=class extends be{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new xi),this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onData=this._register(new ne),this.onData=this._onData.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ne),this._instantiationService=new sN,this.optionsService=this._register(new pN(e)),this._instantiationService.setService($t,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Nh)),this._instantiationService.setService(Ft,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(jh)),this._instantiationService.setService(yb,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Eh)),this._instantiationService.setService(Ns,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Ph)),this._instantiationService.setService(_b,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ds)),this._instantiationService.setService(eC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(_N),this._instantiationService.setService(Z1,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Lh),this._instantiationService.setService(bb,this._oscLinkService),this._inputHandler=this._register(new AN(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(yt.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(yt.forward(this._bufferService.onResize,this._onResize)),this._register(yt.forward(this.coreService.onData,this._onData)),this._register(yt.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new DN((t,n)=>this._inputHandler.parse(t,n))),this._register(yt.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ne),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Hg&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Hg=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Zb),t=Math.max(t,ew),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Rg.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Rg(this._bufferService),!1))),this._windowsWrappingHeuristics.value=$e(()=>{for(let t of e)t.dispose()})}}},MN={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function IN(e,t,n,r){let s={type:0,cancel:!1,key:void 0},i=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?s.key=K.ESC+"OA":s.key=K.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?s.key=K.ESC+"OD":s.key=K.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?s.key=K.ESC+"OC":s.key=K.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?s.key=K.ESC+"OB":s.key=K.ESC+"[B");break;case 8:s.key=e.ctrlKey?"\b":K.DEL,e.altKey&&(s.key=K.ESC+s.key);break;case 9:if(e.shiftKey){s.key=K.ESC+"[Z";break}s.key=K.HT,s.cancel=!0;break;case 13:s.key=e.altKey?K.ESC+K.CR:K.CR,s.cancel=!0;break;case 27:s.key=K.ESC,e.altKey&&(s.key=K.ESC+K.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"D":t?s.key=K.ESC+"OD":s.key=K.ESC+"[D";break;case 39:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"C":t?s.key=K.ESC+"OC":s.key=K.ESC+"[C";break;case 38:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"A":t?s.key=K.ESC+"OA":s.key=K.ESC+"[A";break;case 40:if(e.metaKey)break;i?s.key=K.ESC+"[1;"+(i+1)+"B":t?s.key=K.ESC+"OB":s.key=K.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(s.key=K.ESC+"[2~");break;case 46:i?s.key=K.ESC+"[3;"+(i+1)+"~":s.key=K.ESC+"[3~";break;case 36:i?s.key=K.ESC+"[1;"+(i+1)+"H":t?s.key=K.ESC+"OH":s.key=K.ESC+"[H";break;case 35:i?s.key=K.ESC+"[1;"+(i+1)+"F":t?s.key=K.ESC+"OF":s.key=K.ESC+"[F";break;case 33:e.shiftKey?s.type=2:e.ctrlKey?s.key=K.ESC+"[5;"+(i+1)+"~":s.key=K.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:e.ctrlKey?s.key=K.ESC+"[6;"+(i+1)+"~":s.key=K.ESC+"[6~";break;case 112:i?s.key=K.ESC+"[1;"+(i+1)+"P":s.key=K.ESC+"OP";break;case 113:i?s.key=K.ESC+"[1;"+(i+1)+"Q":s.key=K.ESC+"OQ";break;case 114:i?s.key=K.ESC+"[1;"+(i+1)+"R":s.key=K.ESC+"OR";break;case 115:i?s.key=K.ESC+"[1;"+(i+1)+"S":s.key=K.ESC+"OS";break;case 116:i?s.key=K.ESC+"[15;"+(i+1)+"~":s.key=K.ESC+"[15~";break;case 117:i?s.key=K.ESC+"[17;"+(i+1)+"~":s.key=K.ESC+"[17~";break;case 118:i?s.key=K.ESC+"[18;"+(i+1)+"~":s.key=K.ESC+"[18~";break;case 119:i?s.key=K.ESC+"[19;"+(i+1)+"~":s.key=K.ESC+"[19~";break;case 120:i?s.key=K.ESC+"[20;"+(i+1)+"~":s.key=K.ESC+"[20~";break;case 121:i?s.key=K.ESC+"[21;"+(i+1)+"~":s.key=K.ESC+"[21~";break;case 122:i?s.key=K.ESC+"[23;"+(i+1)+"~":s.key=K.ESC+"[23~";break;case 123:i?s.key=K.ESC+"[24;"+(i+1)+"~":s.key=K.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?s.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?s.key=K.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?s.key=K.DEL:e.keyCode===219?s.key=K.ESC:e.keyCode===220?s.key=K.FS:e.keyCode===221&&(s.key=K.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let l=MN[e.keyCode]?.[e.shiftKey?1:0];if(l)s.key=K.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){let a=e.ctrlKey?e.keyCode-64:e.keyCode+32,c=String.fromCharCode(a);e.shiftKey&&(c=c.toUpperCase()),s.key=K.ESC+c}else if(e.keyCode===32)s.key=K.ESC+(e.ctrlKey?K.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let a=e.code.slice(3,4);e.shiftKey||(a=a.toLowerCase()),s.key=K.ESC+a,s.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(s.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?s.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(s.key=K.US),e.key==="@"&&(s.key=K.NUL));break}return s}var Je=0,ON=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ga,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ga,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((s,i)=>this._getKey(s)-this._getKey(i)),t=0,n=0,r=new Array(this._array.length+this._insertedValues.length);for(let s=0;s=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[s]=e[t],t++):r[s]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Je=this._search(t),Je===-1)||this._getKey(this._array[Je])!==t)return!1;do if(this._array[Je]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Je),!0;while(++Jes-i),t=0,n=new Array(this._array.length-e.length),r=0;for(let s=0;s0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Je=this._search(e),!(Je<0||Je>=this._array.length)&&this._getKey(this._array[Je])===e))do yield this._array[Je];while(++Je=this._array.length)&&this._getKey(this._array[Je])===e))do t(this._array[Je]);while(++Je=t;){let r=t+n>>1,s=this._getKey(this._array[r]);if(s>e)n=r-1;else if(s0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},yu=0,Ug=0,BN=class extends be{constructor(){super(),this._decorations=new ON(e=>e?.marker.line),this._onDecorationRegistered=this._register(new ne),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ne),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register($e(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new zN(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),r=t.onDispose(()=>{r.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,s=0;for(let i of this._decorations.getKeyIterator(t))r=i.options.x??0,s=r+(i.options.width??1),e>=r&&e{yu=s.options.x??0,Ug=yu+(s.options.width??1),e>=yu&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let s=r-this._lastRefreshMs,i=this._debounceThresholdMS-s;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},i)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},qg=20,Ya=class extends be{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let s=this._coreBrowserService.mainDocument;this._accessibilityContainer=s.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=s.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let i=0;ithis._handleBoundaryFocus(i,0),this._bottomBoundaryFocusListener=i=>this._handleBoundaryFocus(i,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=s.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new $N(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(i=>this._handleResize(i.rows))),this._register(this._terminal.onRender(i=>this._refreshRows(i.start,i.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(i=>this._handleChar(i))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(i=>this._handleTab(i))),this._register(this._terminal.onKey(i=>this._handleKey(i.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(me(s,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register($e(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===qg+1&&(this._liveRegion.textContent+=Jd.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let s=e;s<=t;s++){let i=n.lines.get(n.ydisp+s),l=[],a=i?.translateToString(!0,void 0,void 0,l)||"",c=(n.ydisp+s+1).toString(),u=this._rowElements[s];u&&(a.length===0?(u.textContent=" ",this._rowColumns.set(u,[0,1])):(u.textContent=a,this._rowColumns.set(u,l)),u.setAttribute("aria-posinset",c),u.setAttribute("aria-setsize",r),this._alignRowWidth(u))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],s=n.getAttribute("aria-posinset"),i=t===0?"1":`${this._terminal.buffer.lines.length}`;if(s===i||e.relatedTarget!==r)return;let l,a;if(t===0?(l=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(l=this._rowElements.shift(),a=n,this._rowContainer.removeChild(l)),l.removeEventListener("focus",this._topBoundaryFocusListener),a.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let c=this._createAccessibilityTreeNode();this._rowElements.unshift(c),this._rowContainer.insertAdjacentElement("afterbegin",c)}else{let c=this._createAccessibilityTreeNode();this._rowElements.push(c),this._rowContainer.appendChild(c)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let s=({node:a,offset:c})=>{let u=a instanceof Text?a.parentNode:a,h=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(h))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(u);if(!d)return console.warn("columns is null. Race condition?"),null;let f=c=this._terminal.cols&&(++h,f=0),{row:h,column:f}},i=s(t),l=s(n);if(!(!i||!l)){if(i.row>l.row||i.row===l.row&&i.column>=l.column)throw new Error("invalid range");this._terminal.select(i.column,i.row,(l.row-i.row)*this._terminal.cols-i.column+l.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{ws(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(me(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(me(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(me(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(me(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let r=0;r{r?.forEach(s=>{s.link.dispose&&s.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,s]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):s.provideLinks(e.y,i=>{if(this._isMouseOut)return;let l=i?.map(a=>({link:a}));this._activeProviderReplies?.set(r,l),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:l.link.range.end.x;for(let u=a;u<=c;u++){if(n.has(u)){s.splice(i--,1);break}n.add(u)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),s=!1;for(let i=0;ithis._linkAtPosition(l.link,t));i&&(n=!0,this._handleNewLink(i))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let i=0;ithis._linkAtPosition(a.link,t));if(l){n=!0,this._handleNewLink(l);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&WN(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ws(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let r=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(r,s),this._lastMouseEvent)){let i=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);i&&this._askForLink(i,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,s=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(s)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,s=t.y*this._bufferService.cols+t.x;return n<=s&&s<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,s){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:s}}};Dh=Qe([ie(1,Zf),ie(2,gr),ie(3,Ft),ie(4,Sb)],Dh);function WN(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var HN=class extends RN{constructor(e={}){super(e),this._linkifier=this._register(new xi),this.browser=Wb,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new xi),this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ne),this.onKey=this._onKey.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ne),this.onBell=this._onBell.event,this._onFocus=this._register(new ne),this._onBlur=this._register(new ne),this._onA11yCharEmitter=this._register(new ne),this._onA11yTabEmitter=this._register(new ne),this._onWillOpen=this._register(new ne),this._setup(),this._decorationService=this._instantiationService.createInstance(BN),this._instantiationService.setService(Ql,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Lj),this._instantiationService.setService(Sb,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(eh)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(yt.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(yt.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(yt.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(yt.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register($e(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let n,r="";switch(t.index){case 256:n="foreground",r="10";break;case 257:n="background",r="11";break;case 258:n="cursor",r="12";break;default:n="ansi",r="4;"+t.index}switch(t.type){case 0:let s=Be.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${K.ESC}]${r};${EN(s)}${Fb.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(i=>i.ansi[t.index]=rt.toColor(...t.color));else{let i=n;this._themeService.modifyColors(l=>l[i]=rt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ya,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,s=t.getWidth(n),i=this._renderService.dimensions.css.cell.width*s,l=this.buffer.y*this._renderService.dimensions.css.cell.height,a=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=l+"px",this.textarea.style.width=i+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(me(this.element,"copy",t=>{this.hasSelection()&&K1(t,this._selectionService)}));let e=t=>G1(t,this.textarea,this.coreService,this.optionsService);this._register(me(this.textarea,"paste",e)),this._register(me(this.element,"paste",e)),Hb?this._register(me(this.element,"mousedown",t=>{t.button===2&&tg(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(me(this.element,"contextmenu",t=>{tg(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),op&&this._register(me(this.element,"auxclick",t=>{t.button===1&&pb(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(me(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(me(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(me(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(me(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(me(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(me(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(me(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(me(this.screenElement,"mousemove",s=>this.updateCursorStyle(s))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Qd.get()),Vb||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Aj,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(mr,this._coreBrowserService),this._register(me(this.textarea,"focus",s=>this._handleTextAreaFocus(s))),this._register(me(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(bh,this._document,this._helperContainer),this._instantiationService.setService(Sc,this._charSizeService),this._themeService=this._instantiationService.createInstance(Ch),this._instantiationService.setService(Si,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Va),this._instantiationService.setService(wb,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Sh,this.rows,this.screenElement)),this._instantiationService.setService(gr,this._renderService),this._register(this._renderService.onRenderedViewportChange(s=>this._onRender.fire(s))),this.onResize(s=>this._renderService.resize(s.cols,s.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(vh,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(wh),this._instantiationService.setService(Zf,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Dh,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(gh,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(s=>{super.scrollLines(s,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(kh,this.element,this.screenElement,r)),this._instantiationService.setService(nC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(s=>this.scrollLines(s.amount,s.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(s=>this._renderService.handleSelectionChanged(s.start,s.end,s.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(s=>{this.textarea.value=s,this.textarea.focus(),this.textarea.select()})),this._register(yt.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(xh,this.screenElement)),this._register(me(this.element,"mousedown",s=>this._selectionService.handleMouseDown(s))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Ya,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",s=>this._handleScreenReaderModeOptionChange(s))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(qa,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",s=>{!this._overviewRulerRenderer&&s&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(qa,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(yh,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(i){let l=e._mouseService.getMouseReportCoords(i,e.screenElement);if(!l)return!1;let a,c;switch(i.overrideType||i.type){case"mousemove":c=32,i.buttons===void 0?(a=3,i.button!==void 0&&(a=i.button<3?i.button:3)):a=i.buttons&1?0:i.buttons&4?1:i.buttons&2?2:3;break;case"mouseup":c=0,a=i.button<3?i.button:3;break;case"mousedown":c=1,a=i.button<3?i.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(i)===!1)return!1;let u=i.deltaY;if(u===0||e.coreMouseService.consumeWheelEvent(i,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;c=u<0?0:1,a=4;break;default:return!1}return c===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:l.col,row:l.row,x:l.x,y:l.y,button:a,action:c,ctrl:i.ctrlKey,alt:i.altKey,shift:i.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s={mouseup:i=>(n(i),i.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(i)),wheel:i=>(n(i),this.cancel(i,!0)),mousedrag:i=>{i.buttons&&n(i)},mousemove:i=>{i.buttons||n(i)}};this._register(this.coreMouseService.onProtocolChange(i=>{i?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(i)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),i&8?r.mousemove||(t.addEventListener("mousemove",s.mousemove),r.mousemove=s.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),i&16?r.wheel||(t.addEventListener("wheel",s.wheel,{passive:!1}),r.wheel=s.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),i&2?r.mouseup||(r.mouseup=s.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),i&4?r.mousedrag||(r.mousedrag=s.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(me(t,"mousedown",i=>{if(i.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(i)))return n(i),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(i)})),this._register(me(t,"wheel",i=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(i)===!1)return!1;if(!this.buffer.hasScrollback){if(i.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(i,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(i,!0);let l=K.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(i.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(l,!0),this.cancel(i,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){fb(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=IN(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let r=this.rows-1;return this.scrollLines(n.type===2?-r:r),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===K.ETX||n.key===K.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(UN(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new yn)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Vg=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new VN(t)}getNullCell(){return new yn}},KN=class extends be{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ne),this.onBufferChange=this._onBufferChange.event,this._normal=new Vg(this._core.buffers.normal,"normal"),this._alternate=new Vg(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},GN=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,r)=>t(n,r.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},YN=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},XN=["cols","rows"],On=0,QN=class extends be{constructor(e){super(),this._core=this._register(new HN(e)),this._addonManager=this._register(new qN),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],n=(r,s)=>{this._checkReadonlyOptions(r),this._core.options[r]=s};for(let r in this._core.options){let s={get:t.bind(this,r),set:n.bind(this,r)};Object.defineProperty(this._publicOptions,r,s)}}_checkReadonlyOptions(e){if(XN.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new GN(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new YN(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new KN(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Qd.get()},set promptLabel(e){Qd.set(e)},get tooMuchOutput(){return Jd.get()},set tooMuchOutput(e){Jd.set(e)}}}_verifyIntegers(...e){for(On of e)if(On===1/0||isNaN(On)||On%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(On of e)if(On&&(On===1/0||isNaN(On)||On%1!==0||On<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var JN=2,ZN=1,eE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),s=Math.max(0,parseInt(n.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),l={top:parseInt(i.getPropertyValue("padding-top")),bottom:parseInt(i.getPropertyValue("padding-bottom")),right:parseInt(i.getPropertyValue("padding-right")),left:parseInt(i.getPropertyValue("padding-left"))},a=l.top+l.bottom,c=l.right+l.left,u=r-a,h=s-c-t;return{cols:Math.max(JN,Math.floor(h/e.css.cell.width)),rows:Math.max(ZN,Math.floor(u/e.css.cell.height))}}};function jt(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}function Ui(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Jr,hn,Rs,To;const Kg="__TAURI_TO_IPC_KEY__";function nw(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}class Wl{constructor(t){Jr.set(this,void 0),hn.set(this,0),Rs.set(this,[]),To.set(this,void 0),Ui(this,Jr,t||(()=>{})),this.id=nw(n=>{const r=n.index;if("end"in n){r==jt(this,hn,"f")?this.cleanupCallback():Ui(this,To,r);return}const s=n.message;if(r==jt(this,hn,"f")){for(jt(this,Jr,"f").call(this,s),Ui(this,hn,jt(this,hn,"f")+1);jt(this,hn,"f")in jt(this,Rs,"f");){const i=jt(this,Rs,"f")[jt(this,hn,"f")];jt(this,Jr,"f").call(this,i),delete jt(this,Rs,"f")[jt(this,hn,"f")],Ui(this,hn,jt(this,hn,"f")+1)}jt(this,hn,"f")===jt(this,To,"f")&&this.cleanupCallback()}else jt(this,Rs,"f")[r]=s})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(t){Ui(this,Jr,t)}get onmessage(){return jt(this,Jr,"f")}[(Jr=new WeakMap,hn=new WeakMap,Rs=new WeakMap,To=new WeakMap,Kg)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[Kg]()}}async function F(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}var Gg;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_SUSPENDED="tauri://suspended",e.WINDOW_RESUMED="tauri://resumed",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"})(Gg||(Gg={}));async function tE(e,t){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,t),await F("plugin:event|unlisten",{event:e,eventId:t})}async function Xa(e,t,n){var r;const s=(r=void 0)!==null&&r!==void 0?r:{kind:"Any"};return F("plugin:event|listen",{event:e,target:s,handler:nw(t)}).then(i=>async()=>tE(e,i))}async function Yg(e={}){return typeof e=="object"&&Object.freeze(e),await F("plugin:dialog|open",{options:e})}const nE="domain://event",rE="app-exit-work-guard";class sE{async health(t){return F("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await Xa(nE,r=>{t(r.payload)})}async pickFolder(){const t=await Yg({directory:!0,multiple:!1});return t==null?null:typeof t=="string"?t:null}async pickArchiveFile(){const t=await Yg({directory:!1,multiple:!1,filters:[{name:"Plugin archive",extensions:["ideaplug","zip","vsix"]}]});return typeof t=="string"?t:null}async onAppExitWorkGuard(t){return await Xa(rE,r=>{t(r.payload)})}async confirmAppExit(){await F("confirm_app_exit")}}function Qa(e,t){let n=Promise.resolve();return{sessionId:e,write(r){const s=n.then(async()=>{Xg("start",e,r),await F("write_terminal",{request:{sessionId:e,data:Array.from(r)}}),Xg("ok",e,r)});return n=s.catch(()=>{}),s},async resize(r,s){await F("resize_terminal",{request:{sessionId:e,rows:r,cols:s}})},detach(){t.onmessage=()=>{}},async close(){await F("close_terminal",{sessionId:e})}}}function Xg(e,t,n){n.length===1&&n[0]>=32&&n[0]!==127||console.info("[terminal-write]",e,{sessionId:t,bytes:n.length,control:iE(n)})}function iE(e){return e.length===0?"":e.length>16?"":Array.from(e).map(t=>{switch(t){case 13:return"\\r";case 10:return"\\n";case 127:return"\\x7f";default:return t<32?`\\x${t.toString(16).padStart(2,"0")}`:String.fromCharCode(t)}}).join("")}class lE{async openTerminal(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("open_terminal",{request:{cwd:t.cwd,rows:t.rows,cols:t.cols},onOutput:r});return Qa(s.sessionId,r)}async reattach(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Qa(s.sessionId,r),scrollback:Uint8Array.from(s.scrollback)}}async closeTerminal(t){await F("close_terminal",{sessionId:t})}}class oE{listAgents(t){return F("list_agents",{projectId:t})}listLiveAgents(t){return F("list_live_agents",{projectId:t})}listResumableAgents(t){return F("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return F("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return F("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return F("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,s,i){return F("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:s,cols:i}})}readContext(t,n){return F("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await F("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await F("delete_agent",{projectId:t,agentId:n})}async launchAgent(t,n,r,s){const i=new Wl;i.onmessage=c=>s(Uint8Array.from(c));const l=await F("launch_agent",{request:{projectId:t,agentId:n,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,nodeId:r.nodeId??null},onOutput:i});return{...Qa(l.sessionId,i),...l.assignedConversationId?{assignedConversationId:l.assignedConversationId}:{}}}async reattach(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Qa(s.sessionId,r),scrollback:Uint8Array.from(s.scrollback)}}inspectConversation(t,n,r){return F("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}}class aE{async interrupt(t,n){await F("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){console.info("[input-gateway] delegationDelivered:start",{projectId:t,agentId:n,ticket:r}),await F("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}}),console.info("[input-gateway] delegationDelivered:ok",{projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){console.info("[input-gateway] setFrontAttached:start",{agentId:t,attached:n}),await F("set_front_attached",{request:{agentId:t,attached:n}}),console.info("[input-gateway] setFrontAttached:ok",{agentId:t,attached:n})}async cancelResume(t){return F("cancel_resume",{agentId:t})}async setResumeAt(t,n){await F("set_resume_at",{agentId:t,resetsAtMs:n})}}class cE{listProjects(){return F("list_projects")}createProject(t,n){return F("create_project",{request:{name:t,root:n}})}openProject(t){return F("open_project",{projectId:t})}async closeProject(t){await F("close_project",{projectId:t})}readProjectContext(t){return F("read_project_context",{projectId:t})}async updateProjectContext(t,n){await F("update_project_context",{request:{projectId:t,content:n}})}}class uE{loadLayout(t,n){return F("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return F("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return F("list_layouts",{projectId:t})}createLayout(t,n,r){return F("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return F("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return F("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return F("set_active_layout",{request:{projectId:t,layoutId:n}})}}class dE{firstRunState(){return F("first_run_state")}referenceProfiles(){return F("reference_profiles")}detectProfiles(t){return F("detect_profiles",{request:{candidates:t}})}listProfiles(){return F("list_profiles")}saveProfile(t){return F("save_profile",{request:{profile:t}})}async deleteProfile(t){await F("delete_profile",{profileId:t})}configureProfiles(t){return F("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return F("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return F("list_opencode_providers")}saveOpenCodeProviderProfile(t){return F("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class hE{listModelServers(){return F("list_model_servers")}saveModelServer(t){return F("save_model_server",{request:{config:t}})}async deleteModelServer(t){await F("delete_model_server",{serverId:t})}previewModelServerCommand(t){return F("preview_model_server_command",{config:t})}}const fE=2e3;class pE{constructor(t=fE){this.pollMs=t}getExposureSettings(){return F("get_server_exposure_settings")}async saveExposureSettings(t){await F("save_server_exposure_settings",{settings:t})}previewExposure(t){return F("preview_server_exposure_settings",{settings:t})}status(){return F("embedded_server_status")}start(){return F("embedded_server_start")}stop(){return F("embedded_server_stop")}async onStatusChanged(t){let n=!1;const r=setInterval(()=>{this.status().then(s=>{n||t(s)},()=>{})},this.pollMs);return()=>{n=!0,clearInterval(r)}}}class mE{listTemplates(){return F("list_templates")}createTemplate(t){return F("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return F("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await F("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return F("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return F("detect_agent_drift",{projectId:t})}syncAgent(t,n){return F("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class gE{listSkills(t,n){return F("list_skills",{projectId:t,scope:n})}createSkill(t){return F("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,s){return F("update_skill",{request:{projectId:t,scope:n,skillId:r,content:s}})}async deleteSkill(t,n,r){await F("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,s){await F("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:s}})}async unassignSkill(t,n,r){await F("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class xE{listMemories(t){return F("list_memories",{projectId:t})}getMemory(t,n){return F("get_memory",{projectId:t,slug:n})}createMemory(t){return F("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,s,i){return F("update_memory",{request:{projectId:t,slug:n,description:r,type:s,content:i}})}async deleteMemory(t,n){await F("delete_memory",{projectId:t,slug:n})}readIndex(t){return F("read_memory_index",{projectId:t})}resolveLinks(t,n){return F("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return F("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class vE{listEmbedderProfiles(){return F("list_embedder_profiles")}saveEmbedderProfile(t){return F("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await F("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return F("describe_embedder_engines")}}class _E{async listDevices(){return(await F("list_devices")).devices}createPairingCode(){return F("create_pairing_code")}renameDevice(t,n){return F("rename_device",{request:{deviceId:t,name:n}})}revokeDevice(t){return F("revoke_device",{request:{deviceId:t}})}revokeAllDevices(){return F("revoke_all_devices")}}class yE{status(t){return F("git_status",{projectId:t})}async stage(t,n){await F("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await F("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return F("git_commit",{request:{projectId:t,message:n}})}branches(t){return F("git_branches",{projectId:t})}async checkout(t,n){await F("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return F("git_log",{projectId:t,limit:n})}async init(t){await F("git_init",{projectId:t})}graph(t,n){return F("git_graph",{projectId:t,limit:n})}}class bE{getProjectPermissions(t){return F("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return F("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return F("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return F("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getProjectSystemPermissions(t){return F("get_project_system_permissions",{projectId:t})}updateProjectSystemPermissions(t,n){return F("update_project_system_permissions",{request:{projectId:t,permissions:n}})}updateAgentSystemPermissions(t,n,r){return F("update_agent_system_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentSystemPermissions(t,n){return F("resolve_agent_system_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return F("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return F("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return F("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xe(e,t=""){return typeof e=="string"?e:t}function Yn(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function wE(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ms(e){return Array.isArray(e)?e:[]}function Qg(e){return typeof e=="string"?e:void 0}function ci(e){return typeof e=="string"?e:null}function rw(e){return Tn(e)?e.kind==="agent"?{kind:"agent",agentId:Xe(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function SE(e){return e==="inProgress"?"inProgress":"queued"}function kE(e){return Tn(e)&&e.state==="busy"?{state:"busy",ticket:Xe(e.ticket,"unknown"),sinceMs:Yn(e.sinceMs,0)}:{state:"idle"}}function CE(e,t){const n=Tn(e)?e:{},r=Xe(n.taskPreview);return{ticketId:Xe(n.ticketId,`legacy-ticket-${t}`),conversationId:Xe(n.conversationId),position:Yn(n.position,t),status:SE(n.status),source:rw(n.source),requesterLabel:Xe(n.requesterLabel),taskPreview:r,taskLen:Yn(n.taskLen,r.length)}}function jE(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="completed"||t==="success"||t==="succeeded"?"completed":t==="failed"||t==="failure"?"failed":t==="cancelled"||t==="canceled"||t==="expired"?"cancelled":t==="running"||t==="started"?"running":t==="delivered"?"delivered":"pending"}function NE(e,t,n){const r=Tn(e)?e:{};return{taskId:Xe(r.taskId,`legacy-task-${t}`),ownerAgentId:Xe(r.ownerAgentId,n),projectId:Xe(r.projectId),kind:Xe(r.kind,"background"),status:jE(r.status??r.state),exitCode:wE(r.exitCode),summary:ci(r.summary),stdoutTail:ci(r.stdoutTail),stderrTail:ci(r.stderrTail),updatedAtMs:Yn(r.updatedAtMs)}}function sw(e,t,n){const r=Tn(e)?e:{};return{id:Xe(r.id,`legacy-inbox-${t}`),agentId:Xe(r.agentId??r.agent_id,n),source:Xe(r.source,"unknown"),kind:Xe(r.kind,"message"),body:Xe(r.body),createdAtMs:Yn(r.createdAtMs??r.created_at_ms,0),...Qg(r.correlationId??r.correlation_id)?{correlationId:Qg(r.correlationId??r.correlation_id)}:{},priority:Yn(r.priority,0)}}function EE(e,t){const n=Tn(e)?e:{},r=Tn(n.live)&&n.live.kind==="structured"?"structured":"pty",s=Tn(n.live)?{nodeId:Xe(n.live.nodeId),sessionId:Xe(n.live.sessionId),kind:r}:void 0,i=Xe(n.agentId,`legacy-agent-${t}`),l=ms(n.inbox).map((c,u)=>sw(c,u,i)),a=ms(n.backgroundTasks??n.backgroundCompletions).map((c,u)=>NE(c,u,i));return{agentId:i,name:Xe(n.name,"Unnamed agent"),profileId:Xe(n.profileId,"unknown"),...s?{live:s}:{},busy:kE(n.busy),tickets:ms(n.tickets).map(CE),inboxDepth:Yn(n.inboxDepth,l.length),inbox:l,backgroundTasks:a}}function PE(e){return e==="ready"||e==="partial"||e==="unavailable"||e==="missing"?e:"missing"}function AE(e,t){const n=Tn(e)?e:{},r=Xe(n.textPreview);return{role:n.role==="response"||n.role==="toolActivity"?n.role:"prompt",source:rw(n.source),atMs:Yn(n.atMs,t),textPreview:r,textLen:Yn(n.textLen,r.length)}}function TE(e,t){const n=Tn(e)?e:{};return{conversationId:Xe(n.conversationId,`legacy-conversation-${t}`),status:PE(n.status),objectivePreview:ci(n.objectivePreview),summaryPreview:ci(n.summaryPreview),summaryLen:Yn(n.summaryLen,0),upTo:ci(n.upTo),recentTurns:ms(n.recentTurns).map(AE)}}function ap(e){const t=Tn(e)?e:{},n=ms(t.agents).map(EE),r=ms(t.inboxItems).map((s,i)=>sw(s,i,""));for(const s of r){const i=n.find(l=>l.agentId===s.agentId);i&&(i.inbox??=[],i.inboxDepth??=0,i.inbox.some(l=>l.id===s.id)||(i.inbox.push(s),i.inboxDepth=Math.max(i.inboxDepth,i.inbox.length)))}return{agents:n,conversations:ms(t.conversations).map(TE)}}class LE{async getProjectWorkState(t){const n=await F("get_project_work_state",{projectId:t});return ap(n)}async cancelBackgroundTask(t){await F("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await F("retry_background_task",{taskId:t})}}function cp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Rh(e,t=""){return typeof e=="string"?e:t}function Jg(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function DE(e){return Array.isArray(e)?e:[]}function RE(e){return cp(e)?e.kind==="agent"?{kind:"agent",agentId:Rh(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function ME(e){return e==="response"||e==="toolActivity"?e:"prompt"}function IE(e,t){const n=cp(e)?e:{},r=Rh(n.text);return{id:Rh(n.id,`turn-${t}`),atMs:Jg(n.atMs,t),role:ME(n.role),source:RE(n.source),text:r,textLen:Jg(n.textLen,r.length)}}function iw(e){const t=cp(e)?e:{},n=t.nextAnchor;return{turns:DE(t.turns).map(IE),hasMore:t.hasMore===!0,...typeof n=="string"?{nextAnchor:n}:{}}}class OE{async readPage(t,n,r){const s=await F("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return iw(s)}}class BE{async create(t,n){return F("ticket_create",{request:{projectId:t,...n}})}async read(t,n,r=!1){return F("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}async list(t,n){const{statuses:r,priorities:s,...i}=n??{};return F("ticket_list",{request:{projectId:t,statuses:r??[],priorities:s??[],...i}})}async update(t,n,r){return F("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await F("ticket_delete",{request:{projectId:t,ref:n}})}async readCarnet(t,n){return F("ticket_read_carnet",{request:{projectId:t,ref:n}})}async updateCarnet(t,n,r,s){return F("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:s}})}async link(t,n,r,s,i){return F("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:s,expectedVersion:i}})}async unlink(t,n,r,s,i){return F("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:s,kind:i}})}async assign(t,n,r,s,i){return F("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:s,expectedVersion:i}})}async listSprints(t){return(await F("sprint_list",{request:{projectId:t}})).items}async setTicketSprint(t,n,r,s){return r===null?F("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:s}}):F("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:s}})}async createSprint(t,n){return F("sprint_create",{request:{projectId:t,name:n}})}async renameSprint(t,n,r,s){return F("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:s}})}async reorderSprints(t,n){return(await F("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await F("sprint_delete",{request:{projectId:t,sprintId:n}})}async openTicketChat(t,n,r){return F("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await F("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const s=new Wl;s.onmessage=i=>r(i),await F("agent_send",{sessionId:t,prompt:n,onReply:s})}}const zE="view-window://lifecycle";class FE{async openViewWindow(t){await F("open_view_window",{panel:t})}async closeViewWindow(t){await F("close_view_window",{panel:t})}async listOpenViewWindows(){return F("list_open_view_windows")}async onViewWindowClosed(t){return await Xa(zE,r=>{r.payload.kind==="closed"&&t({panel:r.payload.panel})})}}const $E="focused-project://changed";class WE{async setFocusedProject(t){await F("set_focused_project",{project:t})}async getFocusedProject(){return await F("get_focused_project")??null}async onFocusedProjectChanged(t){return await Xa($E,r=>t(r.payload.project??null))}}function bu(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}class lw{read(t){const n=bu();if(!n)return null;let r;try{r=n.getItem(t)}catch{return null}if(r===null)return null;try{return JSON.parse(r)}catch{try{n.removeItem(t)}catch{}return null}}write(t,n){const r=bu();if(r)try{r.setItem(t,JSON.stringify(n))}catch{}}remove(t){const n=bu();if(n)try{n.removeItem(t)}catch{}}}class HE{listPlugins(){return F("plugin_list_plugins")}reviewPackage(t){return F("plugin_review_package",{request:{sourceKind:t.sourceKind,path:t.path}})}installFromArchive(t){return F("plugin_install_from_archive",{path:t})}installFromDirectory(t){return F("plugin_install_from_directory",{path:t})}setEnabled(t,n){return F("plugin_set_enabled",{pluginId:t,enabled:n})}uninstall(t){return F("plugin_uninstall",{pluginId:t})}listRuntimeContributions(){return F("plugin_list_runtime_contributions")}async openPluginsFolder(t){await F("plugin_open_plugins_folder",{pluginId:t??null})}}function UE(e){throw{code:"NOT_IMPLEMENTED",message:`${e} is not implemented yet (pending its lot).`}}class qE{connect(){return UE("RemoteGateway.connect")}}function VE(){return{system:new sE,agent:new oE,input:new aE,terminal:new lE,project:new cE,layout:new uE,git:new yE,remote:new qE,profile:new dE,modelServer:new hE,desktopServer:new pE,template:new mE,skill:new gE,memory:new xE,embedder:new vE,device:new _E,permission:new bE,workState:new LE,conversation:new OE,ticket:new BE,window:new FE,focusedProject:new WE,uiPreferences:new lw,plugin:new HE}}function Mh(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Lo(e=Mh()){return{root:{type:"leaf",node:{id:e,session:null}}}}function Ih(e){if(e.length===0)return[];const t=1e-6,n=e.map(s=>Number.isFinite(s)&&s>0?s:t),r=n.reduce((s,i)=>s+i,0);if(r<=0){const s=100/n.length;return n.map(()=>s)}return n.map(s=>s/r*100)}function Zg(e,t,n){const r=[...e];if(t<0||t+1>=r.length)return r;const s=r.reduce((u,h)=>u+h,0),i=n*s,l=s*.05,a=r[t]+i,c=r[t+1]-i;return a({node:Ut(r.node,t),weight:r.weight}))}};break;case"grid":n={type:"grid",node:{...e.node,cells:e.node.cells.map(r=>({...r,node:Ut(r.node,t)}))}};break}return t(n)}function ex(e,t){let n;return Ut(e,r=>(r.type==="leaf"&&r.node.id===t&&(n=r.node.session??null),r)),n}function KE(e,t){switch(t.type){case"split":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const i={id:t.newLeaf,session:null};return{type:"split",node:{id:t.container,direction:t.direction,children:[{node:s,weight:1},{node:{type:"leaf",node:i},weight:1}]}}}return s});if(!n)throw er(t.target);return{root:r}}case"merge":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="split"&&s.node.id===t.container){const i=s.node.children[t.keepIndex];if(!i)throw Do(`merge keepIndex ${t.keepIndex} out of range`);return n=!0,i.node}return s});if(!n)throw er(t.container);return{root:r}}case"resize":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="split"&&s.node.id===t.container){if(s.node.children.length!==t.weights.length)throw Do("resize weight count mismatch");n=!0;const i=s.node.children.map((l,a)=>({node:l.node,weight:t.weights[a]}));return{type:"split",node:{...s.node,children:i}}}return s});if(!n)throw er(t.container);return{root:r}}case"move":{const n=ex(e.root,t.from);if(n===void 0)throw er(t.from);if(n===null)throw Do("source cell has no session");const r=ex(e.root,t.to);if(r===void 0)throw er(t.to);if(r!==null)throw Do("target cell is occupied");return{root:Ut(e.root,i=>i.type==="leaf"&&i.node.id===t.from?{type:"leaf",node:{...i.node,session:null}}:i.type==="leaf"&&i.node.id===t.to?{type:"leaf",node:{...i.node,session:n}}:i)}}case"setSession":{let n=!1;const r=Ut(e.root,s=>s.type==="leaf"&&s.node.id===t.target?(n=!0,{type:"leaf",node:{...s.node,session:t.session??null}}):s);if(!n)throw er(t.target);return{root:r}}case"setCellAgent":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{agent:i,...l}=s.node;return{type:"leaf",node:t.agent!==null?{...l,agent:t.agent}:l}}return s});if(!n)throw er(t.target);return{root:r}}case"setCellConversation":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{conversationId:i,...l}=s.node;return{type:"leaf",node:t.conversationId!==null?{...l,conversationId:t.conversationId}:l}}return s});if(!n)throw er(t.target);return{root:r}}case"setAgentRunning":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{agentWasRunning:i,...l}=s.node;return{type:"leaf",node:t.running?{...l,agentWasRunning:!0}:l}}return s});if(!n)throw er(t.target);return{root:r}}}}function Ja(e){const t=[];return Ut(e.root,n=>(n.type==="leaf"&&t.push(n.node),n)),t}function GE(e,t,n){return{root:Ut(e.root,r=>r.type==="customPluginLayout"&&r.node.id===t?{type:"customPluginLayout",node:{...r.node,state:n}}:r)}}function YE(e,t){return{root:Ut(e.root,n=>n.type==="customPluginLayout"&&n.node.id===t?{type:"leaf",node:{id:t}}:n)}}function XE(e,t){return{type:"split",target:e,direction:t,newLeaf:Mh(),container:Mh()}}function er(e){return{code:"NOT_FOUND",message:`layout node ${e} not found`}}function Do(e){return{code:"INVALID",message:e}}const tx={low:0,medium:1,high:2,critical:3},nx={open:0,inProgress:1,QA:2,closed:3};function QE(e,t){return e.sort((n,r)=>{let s=0;return t.field==="number"?s=n.number-r.number:t.field==="priority"?s=tx[n.priority]-tx[r.priority]:t.field==="status"?s=nx[n.status]-nx[r.status]:s=n.title.localeCompare(r.title,void 0,{sensitivity:"base"})||n.title.localeCompare(r.title),(t.direction==="desc"?-s:s)||n.number-r.number})}class JE{constructor(){X(this,"listeners",new Set);X(this,"exitGuardListeners",new Set);X(this,"confirmAppExitCallCount",0)}async health(t){const n={version:"0.1.0-mock",alive:!0,timeMillis:Date.now(),correlationId:`mock-${Math.random().toString(36).slice(2,10)}`,note:t??null};return this.emit({type:"projectCreated",projectId:n.correlationId}),n}async onDomainEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(t){for(const n of this.listeners)n(t)}async pickFolder(){return"/home/user/mock-project"}async pickArchiveFile(){return"/home/user/mock-plugin.ideaplug"}async onAppExitWorkGuard(t){return this.exitGuardListeners.add(t),()=>{this.exitGuardListeners.delete(t)}}emitAppExitWorkGuard(t){for(const n of this.exitGuardListeners)n(t)}async confirmAppExit(){this.confirmAppExitCallCount+=1}}function up(e){let t="",n=!1;for(const r of e.trim())/[a-zA-Z0-9]/.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="-",n=!0);return t.replace(/^-+|-+$/g,"")}class Oh{constructor(t,n){X(this,"scrollback",[]);X(this,"sink",null);X(this,"closed",!1);this.sessionId=t,this.sink=n}emit(t){if(!this.closed){for(const n of t)this.scrollback.push(n);this.sink?.(t)}}detach(){this.sink=null}reattach(t){return this.sink=t,Uint8Array.from(this.scrollback)}}class ZE{constructor(){X(this,"agents",new Map);X(this,"contexts",new Map);X(this,"sessionSeq",0);X(this,"sessions",new Map);X(this,"liveByAgent",new Map);X(this,"liveSessionByAgent",new Map);X(this,"resumable",new Map);X(this,"conversationDetails",new Map)}getAgents(t){return this.agents.has(t)||this.agents.set(t,[]),this.agents.get(t)}contextKey(t,n){return`${t}::${n}`}async listAgents(t){return structuredClone(this.getAgents(t))}async listLiveAgents(t){const n=new Set(this.getAgents(t).map(r=>r.id));return[...this.liveByAgent.entries()].filter(([r])=>n.has(r)).map(([r,s])=>({agentId:r,nodeId:s,sessionId:this.liveSessionByAgent.get(r),kind:"pty"}))}_setResumableAgents(t,n){this.resumable.set(t,n)}async listResumableAgents(t){return structuredClone(this.resumable.get(t)??[])}async attachLiveAgent(t,n,r){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const i=this.liveSessionByAgent.get(n);if(!i||!this.sessions.has(i))throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};return this.liveByAgent.set(n,r),{agentId:n,nodeId:r,sessionId:i,kind:"pty"}}async stopLiveAgent(t,n){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const s=this.liveSessionByAgent.get(n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};const i=this.sessions.get(s);return i&&(i.closed=!0),this.sessions.delete(s),this.liveSessionByAgent.delete(n),this.liveByAgent.delete(n),{agentId:n,sessionId:s,kind:"pty"}}async createAgent(t,n){const r=this.getAgents(t),s=up(n.name)||"agent",i=new Set(r.map(u=>u.contextPath));let l=`agents/${s}.md`,a=2;for(;i.has(l);)l=`agents/${s}-${a}.md`,a+=1;const c={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:n.name,contextPath:l,profileId:n.profileId,origin:{type:"scratch"},synchronized:!1,skills:[]};return r.push(c),this.contexts.set(this.contextKey(t,c.id),n.initialContent??""),structuredClone(c)}async readContext(t,n){if(!this.getAgents(t).some(s=>s.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};return this.contexts.get(this.contextKey(t,n))??""}async updateContext(t,n,r){if(!this.getAgents(t).some(i=>i.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.contexts.set(this.contextKey(t,n),r)}async deleteAgent(t,n){const r=this.getAgents(t),s=r.findIndex(i=>i.id===n);if(s===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};r.splice(s,1),this.contexts.delete(this.contextKey(t,n))}async changeAgentProfile(t,n,r,s,i){const l=this.getAgents(t),a=l.findIndex(m=>m.id===n);if(a===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};l[a]={...l[a],profileId:r};const c=structuredClone(l[a]),u=this.liveByAgent.get(n),h=this.liveSessionByAgent.get(n);if(!u||!h)return{agent:c};const d=this.sessions.get(h);d&&(d.closed=!0),this.sessions.delete(h),this.sessionSeq+=1;const f=`mock-agent-session-${this.sessionSeq}`,p=new Oh(f,()=>{});return p.detach(),this.sessions.set(f,p),this.liveSessionByAgent.set(n,f),this.liveByAgent.set(n,u),{agent:c,relaunchedSession:{sessionId:f,cwd:"/home/user/mock-project",rows:s,cols:i}}}_insertAgent(t,n,r){this.getAgents(t).push(n),this.contexts.set(this.contextKey(t,n.id),r)}_updateAgent(t,n,r,s){const i=this.getAgents(t),l=i.findIndex(a=>a.id===n);l!==-1&&(i[l]={...i[l],...r},s!==void 0&&this.contexts.set(this.contextKey(t,n),s))}_rawAgents(t){return this.getAgents(t)}_setSkills(t,n,r){const s=this.getAgents(t),i=s.findIndex(l=>l.id===n);i!==-1&&(s[i]={...s[i],skills:r})}async launchAgent(t,n,r,s){if(!this.getAgents(t).some(p=>p.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const l=this.liveByAgent.get(n);if(l!==void 0&&r.nodeId&&l!==r.nodeId)throw{code:"AGENT_ALREADY_RUNNING",message:`agent ${n} is already running in cell ${l}`};this.sessionSeq+=1;const a=`mock-agent-session-${this.sessionSeq}`,c=r.cwd;r.nodeId&&(this.liveByAgent.set(n,r.nodeId),this.liveSessionByAgent.set(n,a));const u=()=>{this.liveByAgent.get(n)===r.nodeId&&(this.liveByAgent.delete(n),this.liveSessionByAgent.delete(n))},h=new TextEncoder,d=new Oh(a,s);this.sessions.set(a,d),queueMicrotask(()=>d.emit(h.encode(`agent ${n} @ ${c}\r -`)));const f=Za(d,()=>{this.sessions.delete(a),u()});return r.conversationId?f:{...f,assignedConversationId:`mock-conversation-${a}`}}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`agent session ${t} is not alive`};const s=r.reattach(n);return{handle:Za(r,()=>{this.sessions.delete(t);for(const[i,l]of this.liveSessionByAgent)l===t&&(this.liveSessionByAgent.delete(i),this.liveByAgent.delete(i))}),scrollback:s}}_setConversationDetails(t,n){this.conversationDetails.set(t,n)}async inspectConversation(t,n,r){return structuredClone(this.conversationDetails.get(r)??{})}}function Za(e,t){return{sessionId:e.sessionId,async write(n){if(e.closed)return;const r=[];for(const s of n)s===13?r.push(13,10):r.push(s);e.emit(Uint8Array.from(r))},async resize(){},detach(){e.detach()},async close(){e.closed=!0,t()}}}class e2{constructor(){X(this,"seq",0);X(this,"sessions",new Map)}async openTerminal(t,n){this.seq+=1;const r=`mock-session-${this.seq}`,s=new TextEncoder,i=new Oh(r,n);return this.sessions.set(r,i),queueMicrotask(()=>i.emit(s.encode(`mock terminal @ ${t.cwd}\r -`))),Za(i,()=>this.sessions.delete(r))}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`terminal session ${t} is not alive`};const s=r.reattach(n);return{handle:Za(r,()=>this.sessions.delete(t)),scrollback:s}}async closeTerminal(t){const n=this.sessions.get(t);n&&(n.closed=!0,this.sessions.delete(t))}}class t2{constructor(){X(this,"projects",[]);X(this,"contexts",new Map)}async listProjects(){return[...this.projects]}async createProject(t,n){if(this.projects.some(s=>s.root===n))throw{code:"INVALID",message:`a project already exists at ${n} for this remote`};const r={id:`mock-project-${Math.random().toString(36).slice(2,10)}`,name:t,root:n,remote:{kind:"local"},createdAt:Date.now()};return this.projects.push(r),r}async openProject(t){const n=this.projects.find(r=>r.id===t);if(!n)throw{code:"NOT_FOUND",message:`project ${t} not found`};return n}async closeProject(){}async readProjectContext(t){if(!this.projects.some(n=>n.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};return this.contexts.get(t)??""}async updateProjectContext(t,n){if(!this.projects.some(r=>r.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};this.contexts.set(t,n)}}class n2{constructor(){X(this,"store",new Map)}getProjectLayouts(t){if(!this.store.has(t)){const n=`layout-default-${Math.random().toString(36).slice(2,8)}`;this.store.set(t,{activeId:n,layouts:[{id:n,name:"Default",kind:"terminal",tree:Lo()}]})}return this.store.get(t)}getActiveTree(t){const n=this.getProjectLayouts(t),r=n.layouts.find(s=>s.id===n.activeId);return r?r.tree:Lo()}getTree(t,n){if(!n)return this.getActiveTree(t);const s=this.getProjectLayouts(t).layouts.find(i=>i.id===n);return s?s.tree:Lo()}setTree(t,n,r){const s=this.getProjectLayouts(t),i=r??s.activeId,l=s.layouts.find(a=>a.id===i);l&&(l.tree=n)}async loadLayout(t,n){const r=this.getTree(t,n);return structuredClone(r)}async mutateLayout(t,n,r){const s=this.getTree(t,r),i=KE(s,n);return this.setTree(t,i,r),structuredClone(i)}async listLayouts(t){const n=this.getProjectLayouts(t);return{layouts:n.layouts.map(s=>({id:s.id,name:s.name,kind:s.kind})),activeId:n.activeId}}async createLayout(t,n,r="terminal"){const s=this.getProjectLayouts(t),i=`layout-${Math.random().toString(36).slice(2,10)}`;return s.layouts.push({id:i,name:n,kind:r,tree:Lo()}),{layoutId:i}}async renameLayout(t,n,r){const i=this.getProjectLayouts(t).layouts.find(l=>l.id===n);i&&(i.name=r)}async deleteLayout(t,n){const r=this.getProjectLayouts(t),s=r.layouts.findIndex(i=>i.id===n);return s!==-1&&r.layouts.splice(s,1),r.activeId===n&&r.layouts.length>0&&(r.activeId=r.layouts[0].id),{activeId:r.activeId}}async setActiveLayout(t,n){const r=this.getProjectLayouts(t);return r.layouts.some(s=>s.id===n)&&(r.activeId=n),{activeId:r.activeId}}}const r2=[{hash:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",summary:"Merge feature into main",parents:["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","dddddddddddddddddddddddddddddddddddddddd"],refs:["main","HEAD"],author:"Alice",timestamp:17172e5},{hash:"dddddddddddddddddddddddddddddddddddddddd",summary:"Implement feature (step 2)",parents:["cccccccccccccccccccccccccccccccccccccccc"],refs:["feature"],author:"Bob",timestamp:17171e5},{hash:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",summary:"Hotfix on main",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Alice",timestamp:171709e4},{hash:"cccccccccccccccccccccccccccccccccccccccc",summary:"Implement feature (step 1)",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Bob",timestamp:171708e4},{hash:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",summary:"Initial commit",parents:[],refs:["tag: v1.0"],author:"Alice",timestamp:1717e6}];class s2{constructor(){X(this,"projects",new Map)}getState(t){return this.projects.has(t)||this.projects.set(t,this._seedState()),this.projects.get(t)}_seedState(){const t=new Map;return t.set("src/main.rs",!1),t.set("README.md",!1),{files:t,branches:["main"],current:"main",log:[],commitSeq:0}}async init(t){this.projects.has(t)||this.projects.set(t,this._seedState())}async status(t){const n=this.getState(t);return Array.from(n.files.entries()).map(([r,s])=>({path:r,staged:s}))}async stage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!0)}async unstage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!1)}async commit(t,n){const r=this.getState(t);r.commitSeq+=1;const s={hash:`mock-${r.commitSeq}`,summary:n.split(` -`)[0]};for(const[i,l]of Array.from(r.files.entries()))l&&r.files.delete(i);return r.log.unshift(s),s}async branches(t){const n=this.getState(t);return{branches:[...n.branches],current:n.current}}async checkout(t,n){const r=this.getState(t);r.branches.includes(n)||r.branches.push(n),r.current=n}async log(t,n){return this.getState(t).log.slice(0,n)}async graph(t,n){return r2.slice(0,n)}}class i2{async connect(){}}class l2{constructor(){X(this,"open",new Set);X(this,"listeners",new Set)}async openViewWindow(t){this.open.add(t)}async closeViewWindow(t){this.open.delete(t)&&this.emit({panel:t})}async listOpenViewWindows(){return[...this.open].map(t=>({panel:t,label:t,visible:!0}))}async onViewWindowClosed(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}simulateOsClose(t){this.open.delete(t),this.emit({panel:t})}emit(t){for(const n of this.listeners)n(t)}}class o2{constructor(){X(this,"focused",null);X(this,"listeners",new Set)}async setFocusedProject(t){this.focused=t;for(const n of this.listeners)n(t)}async getFocusedProject(){return this.focused}async onFocusedProjectChanged(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}}const wu=[{id:"mock-claude",name:"Claude Code",command:"claude",args:[],contextInjection:{strategy:"conventionFile",target:"CLAUDE.md"},detect:"claude --version",cwdTemplate:"{projectRoot}"},{id:"mock-codex",name:"OpenAI Codex CLI",command:"codex",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"codex --version",cwdTemplate:"{projectRoot}"},{id:"mock-opencode",name:"OpenCode + llama.cpp",command:"opencode",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"opencode --version",cwdTemplate:"{projectRoot}",structuredAdapter:"openCode",opencode:{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}],a2=[{providerId:"anthropic",displayName:"Anthropic",models:["claude-sonnet-5","claude-opus-4-8","claude-haiku-4-5"]},{providerId:"openrouter",displayName:"OpenRouter",models:["openrouter/auto","qwen/qwen3-coder"]}];class c2{constructor(){X(this,"profiles",[]);X(this,"configured",!1);X(this,"cloneCounter",0)}async firstRunState(){return{isFirstRun:!this.configured,referenceProfiles:structuredClone(wu)}}async referenceProfiles(){return structuredClone(wu)}async detectProfiles(t){return t.map(n=>({profile:n,available:n.command==="claude"}))}async listProfiles(){return structuredClone(this.profiles)}async saveProfile(t){const n=this.profiles.findIndex(r=>r.id===t.id);return n>=0?this.profiles[n]=t:this.profiles.push(t),this.configured=!0,structuredClone(t)}async deleteProfile(t){this.profiles=this.profiles.filter(n=>n.id!==t)}async configureProfiles(t){return this.profiles=structuredClone(t),this.configured=!0,structuredClone(t)}async cloneOpenCodeProfileFromSeed(t={}){const n=wu.find(r=>r.structuredAdapter==="openCode");if(!n)throw new Error("no OpenCode seed profile");return this.cloneCounter+=1,structuredClone({...n,id:`mock-opencode-clone-${this.cloneCounter}`,name:t.name??`${n.name} (copy ${this.cloneCounter})`,opencode:t.opencode??n.opencode})}async listOpenCodeProviders(){return structuredClone(a2)}async saveOpenCodeProviderProfile(t){const n={...structuredClone(t.profile),opencode:void 0,opencodeProvider:{providerId:t.providerId,model:t.model,apiKeyRef:`mock-secret-${t.profile.id}`,custom:t.custom}},r=this.profiles.findIndex(s=>s.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}}class u2{constructor(){X(this,"servers",[]);X(this,"inUse",new Set)}async listModelServers(){return structuredClone(this.servers)}async saveModelServer(t){const n=this.servers.findIndex(r=>r.id===t.id);return n>=0?this.servers[n]=structuredClone(t):this.servers.push(structuredClone(t)),structuredClone(t)}async deleteModelServer(t){if(this.inUse.has(t))throw{code:"model_server_in_use",message:"A profile still references this server."};this.servers=this.servers.filter(n=>n.id!==t)}async previewModelServerCommand(t){if(!t.modelSource)throw{code:"INVALID",message:"model.source missing"};const n=t.binaryPath&&t.binaryPath.trim().length>0?t.binaryPath:"llama-server",r=[];t.modelSource.type==="localPath"?r.push("--model",t.modelSource.path):r.push("-hf",t.modelSource.repo),r.push("--port",String(t.port),"--host",t.host),t.gpuLayers!==void 0&&r.push("-ngl",String(t.gpuLayers)),t.contextSize!==void 0&&r.push("-c",String(t.contextSize)),t.jinja&&r.push("--jinja"),r.push(...t.args);const s=[n,...r].map(i=>/\s/.test(i)?`'${i}'`:i).join(" ");return{command:n,args:r,display:s}}markInUse(t){this.inUse.add(t)}}const d2={mode:"localOnly",autoStart:!1,port:17373,trustedProxies:[]},h2=["192.168.1.42","10.0.0.17"];function Ms(e){throw{code:"INVALID",message:e}}class f2{constructor(){X(this,"settings",structuredClone(d2));X(this,"current",{state:"stopped"});X(this,"handlers",new Set)}async getExposureSettings(){return structuredClone(this.settings)}async saveExposureSettings(t){this.validate(t),this.settings=structuredClone(t)}async previewExposure(t){this.validate(t);const n=[];t.mode==="remoteProxyOtherMachine"&&t.trustedProxies.length===0&&n.push({code:"missingTrustedProxy",message:"Add the IP address or CIDR of the reverse proxy that connects to this server."});const r=t.mode==="remoteProxyOtherMachine"?t.lanBindAddress:"127.0.0.1",s=t.mode!=="localOnly"&&r?`http://${r}:${t.port}`:void 0;return{candidateLanAddresses:[...h2],upstreamUrl:s,warnings:n}}async status(){return structuredClone(this.current)}async start(){this.validate(this.settings);const t=await this.previewExposure(this.settings);return this.emit({state:"running",localUrl:`http://127.0.0.1:${this.settings.port}`,publicUrl:this.settings.mode==="localOnly"?void 0:this.settings.publicOrigin,upstreamUrl:t.upstreamUrl}),structuredClone(this.current)}async stop(){return this.emit({state:"stopped"}),structuredClone(this.current)}async onStatusChanged(t){return this.handlers.add(t),()=>this.handlers.delete(t)}setStatus(t){this.emit(t)}emit(t){this.current=t;for(const n of this.handlers)n(structuredClone(t))}validate(t){if(t.mode!=="localOnly"){const n=t.publicOrigin;n||Ms("remote exposure requires publicOrigin"),n.startsWith("https://")||Ms("remote exposure requires publicOrigin to start with https://"),n.includes("*")&&Ms("publicOrigin must be exact, not a wildcard"),n.endsWith("/")&&Ms("publicOrigin must not end with '/'")}t.mode==="remoteProxyOtherMachine"&&(t.lanBindAddress||Ms("remoteProxyOtherMachine requires lanBindAddress"),t.trustedProxies.length===0&&Ms("remoteProxyOtherMachine requires at least one trustedProxies entry"))}}class p2{constructor(t){X(this,"templates",[]);X(this,"seq",0);this.agentGateway=t}async listTemplates(){return structuredClone(this.templates)}async createTemplate(t){this.seq+=1;const n={id:`mock-template-${this.seq}`,name:t.name,contentMd:t.content,version:1,defaultProfileId:t.defaultProfileId};return this.templates.push(n),structuredClone(n)}async updateTemplate(t,n){const r=this.templates.findIndex(s=>s.id===t);if(r===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};return this.templates[r]={...this.templates[r],contentMd:n,version:this.templates[r].version+1},structuredClone(this.templates[r])}async deleteTemplate(t){const n=this.templates.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};this.templates.splice(n,1)}async createAgentFromTemplate(t,n,r){const s=this.templates.find(f=>f.id===n);if(!s)throw{code:"NOT_FOUND",message:`template ${n} not found`};const i=r?.synchronized??!0,l=r?.name??s.name,a=up(l)||"agent",c=new Set(this.agentGateway._rawAgents(t).map(f=>f.contextPath));let u=`agents/${a}.md`,h=2;for(;c.has(u);)u=`agents/${a}-${h}.md`,h+=1;const d={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:l,contextPath:u,profileId:s.defaultProfileId,origin:{type:"fromTemplate",templateId:n,syncedTemplateVersion:s.version},synchronized:i,skills:[]};return this.agentGateway._insertAgent(t,d,s.contentMd),structuredClone(d)}async detectDrift(t){const n=this.agentGateway._rawAgents(t),r=[];for(const s of n){if(!s.synchronized||s.origin.type!=="fromTemplate")continue;const{templateId:i,syncedTemplateVersion:l}=s.origin,a=this.templates.find(c=>c.id===i);a&&a.version>l&&r.push({agentId:s.id,from:l,to:a.version})}return r}async syncAgent(t,n){const s=this.agentGateway._rawAgents(t).find(a=>a.id===n);if(!s||!s.synchronized||s.origin.type!=="fromTemplate")return{synced:!1,version:null};const{templateId:i}=s.origin,l=this.templates.find(a=>a.id===i);return l?(this.agentGateway._updateAgent(t,n,{origin:{type:"fromTemplate",templateId:i,syncedTemplateVersion:l.version}},l.contentMd),{synced:!0,version:l.version}):{synced:!1,version:null}}}class m2{constructor(t){X(this,"global",[]);X(this,"byProject",new Map);X(this,"seq",0);this.agentGateway=t}bucket(t,n){if(n==="global")return this.global;let r=this.byProject.get(t);return r||(r=[],this.byProject.set(t,r)),r}async listSkills(t,n){return structuredClone(this.bucket(t,n))}async createSkill(t){this.seq+=1;const n={id:`mock-skill-${this.seq}`,name:t.name,contentMd:t.content,scope:t.scope};return this.bucket(t.projectId,t.scope).push(n),structuredClone(n)}async updateSkill(t,n,r,s){const i=this.bucket(t,n),l=i.findIndex(a=>a.id===r);if(l===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};return i[l]={...i[l],contentMd:s},structuredClone(i[l])}async deleteSkill(t,n,r){const s=this.bucket(t,n),i=s.findIndex(l=>l.id===r);if(i===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};s.splice(i,1)}async assignSkill(t,n,r,s){const i=this.agentGateway._rawAgents(t).find(l=>l.id===n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};i.skills.some(l=>l.skillId===r)||this.agentGateway._setSkills(t,n,[...i.skills,{skillId:r,scope:s}])}async unassignSkill(t,n,r){const s=this.agentGateway._rawAgents(t).find(i=>i.id===n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.agentGateway._setSkills(t,n,s.skills.filter(i=>i.skillId!==r))}}class g2{constructor(){X(this,"byProject",new Map)}bucket(t){let n=this.byProject.get(t);return n||(n=new Map,this.byProject.set(t,n)),n}notFound(t,n){return{code:"NOT_FOUND",message:`memory ${t} not found in project ${n}`}}async listMemories(t){return structuredClone([...this.bucket(t).values()])}async getMemory(t,n){const r=this.bucket(t).get(n);if(!r)throw this.notFound(n,t);return structuredClone(r)}async createMemory(t){const n={name:t.name,description:t.description,type:t.type,content:t.content};return this.bucket(t.projectId).set(up(t.name),n),structuredClone(n)}async updateMemory(t,n,r,s,i){const l=this.bucket(t),a=l.get(n);if(!a)throw this.notFound(n,t);const c={...a,description:r,type:s,content:i};return l.set(n,c),structuredClone(c)}async deleteMemory(t,n){if(!this.bucket(t).delete(n))throw this.notFound(n,t)}async readIndex(t){return[...this.bucket(t).entries()].map(([n,r])=>({slug:n,title:r.name,hook:r.description,type:r.type}))}async resolveLinks(t,n){const r=this.bucket(t),s=r.get(n);if(!s)throw this.notFound(n,t);const i=new Set;for(const l of s.content.matchAll(/\[\[([^\]]+)\]\]/g)){const a=l[1].trim();a!==n&&r.has(a)&&i.add(a)}return[...i]}async recall(t,n,r){const s=await this.readIndex(t),i=Math.max(0,Math.floor(r/16));return s.slice(0,i)}}class x2{constructor(t,n=[]){X(this,"profiles",new Map);X(this,"engines");this.engines={recommendedOnnx:[{id:"e5-small",displayName:"E5 Small (multilingual)",dimension:384,approxSizeMb:120,recommended:!0},{id:"bge-small",displayName:"BGE Small",dimension:384,approxSizeMb:130,recommended:!1}],ollamaDetected:!1,onnxCachedModels:[],vectorHttpEnabled:!0,vectorOnnxEnabled:!0,...t};for(const r of n)this.profiles.set(r.id,r)}async listEmbedderProfiles(){return structuredClone([...this.profiles.values()])}async saveEmbedderProfile(t){if(!t.id.trim()||!t.name.trim())throw{code:"INVALID",message:"embedder profile id/name must not be empty"};if(t.dimension<=0)throw{code:"INVALID",message:"embedder profile dimension must be > 0"};return this.profiles.set(t.id,structuredClone(t)),structuredClone(t)}async deleteEmbedderProfile(t){this.profiles.delete(t)}async describeEmbedderEngines(){return structuredClone(this.engines)}}class v2{constructor(){X(this,"interrupts",[]);X(this,"delivered",[]);X(this,"frontAttached",[]);X(this,"cancelledResumes",[]);X(this,"resumeArmings",[]);X(this,"cancelResumeResult",!0)}async interrupt(t,n){this.interrupts.push({projectId:t,agentId:n})}async delegationDelivered(t,n,r){this.delivered.push({projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){this.frontAttached.push({agentId:t,attached:n})}async cancelResume(t){return this.cancelledResumes.push(t),this.cancelResumeResult}async setResumeAt(t,n){this.resumeArmings.push({agentId:t,resetsAtMs:n})}}class _2{constructor(){X(this,"devices",[]);X(this,"issued",0);X(this,"_issuedCodes",[])}_setDevices(t){this.devices=structuredClone(t)}async listDevices(){return structuredClone(this.devices)}async createPairingCode(){const t=(268435456+this.issued++).toString(16).toUpperCase().slice(0,8);this._issuedCodes.push(t);const n=600;return{code:t,expiresAtMs:Date.now()+n*1e3,ttlSeconds:n}}async renameDevice(t,n){const r=this.devices.find(s=>s.deviceId===t);if(!r)throw{code:"NOT_FOUND",message:`unknown device ${t}`};r.name=n}async revokeDevice(t){this.devices=this.devices.filter(n=>n.deviceId!==t)}async revokeAllDevices(){this.devices=[]}}class y2{constructor(){X(this,"docs",new Map);X(this,"systemDocs",new Map);X(this,"systemRuntime",new Map);X(this,"mcpCatalogue",{readOnlyTools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read","idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"],writeActionTools:["idea_ask_agent","idea_run_in_background","idea_launch_agent","idea_stop_agent","idea_update_context","idea_context_propose","idea_memory_write","idea_workstate_set","idea_create_skill","idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]});X(this,"mcpDocs",new Map)}doc(t){return this.docs.has(t)||this.docs.set(t,{version:1,agents:[]}),this.docs.get(t)}async getProjectPermissions(t){return structuredClone(this.doc(t))}async updateProjectPermissions(t,n){const r=this.doc(t);return n?r.projectDefaults=structuredClone(n):delete r.projectDefaults,structuredClone(r)}async updateAgentPermissions(t,n,r){const s=this.doc(t),i=(s.agents??[]).filter(l=>l.agentId!==n);return r&&i.push({agentId:n,permissions:structuredClone(r)}),s.agents=i,structuredClone(s)}async resolveAgentPermissions(t,n){const r=this.doc(t),s=r.projectDefaults,i=r.agents?.find(l=>l.agentId===n)?.permissions;return!s&&!i?null:{rules:[...s?.rules??[],...i?.rules??[]],fallback:C2(s?.fallback,i?.fallback)}}systemDoc(t){return this.systemDocs.has(t)||this.systemDocs.set(t,{version:1,agents:[]}),this.systemDocs.get(t)}async getProjectSystemPermissions(t){return structuredClone(this.systemDoc(t))}async updateProjectSystemPermissions(t,n){const r=this.systemDoc(t);return n&&Object.keys(n).length>0?r.projectDefault=structuredClone(n):delete r.projectDefault,structuredClone(r)}async updateAgentSystemPermissions(t,n,r){const s=this.systemDoc(t),i=(s.agents??[]).filter(l=>l.agentId!==n);return r&&Object.keys(r).length>0&&i.push({agentId:n,permissions:structuredClone(r)}),s.agents=i,structuredClone(s)}async resolveAgentSystemPermissions(t,n){const r=this.systemRuntime.get(n);if(r)return structuredClone(r);const s=this.systemDoc(t),i=s.agents?.find(l=>l.agentId===n)?.permissions.network??s.projectDefault?.network??null;return{wanted:i,effective:i??"ask",runtimeLock:{state:"none"},control:{mode:"editable"}}}setResolvedAgentSystemPermissions(t,n){this.systemRuntime.set(t,structuredClone(n))}mcpDoc(t){return this.mcpDocs.has(t)||this.mcpDocs.set(t,{version:1,catalogue:this.mcpCatalogue,projectDefault:null,agents:[]}),this.mcpDocs.get(t)}async getMcpToolPermissions(t){return structuredClone(this.mcpDoc(t))}async updateProjectMcpToolPermissions(t,n){const r=this.mcpDoc(t);return r.projectDefault=n?structuredClone(n):null,structuredClone(r)}async updateAgentMcpToolPermissions(t,n,r){const s=this.mcpDoc(t);return s.agents=s.agents.filter(i=>i.agentId!==n),r&&s.agents.push({agentId:n,policy:structuredClone(r)}),structuredClone(s)}}class b2{constructor(){X(this,"states",new Map)}_setProjectWorkState(t,n){this.states.set(t,ap(n))}async getProjectWorkState(t){return structuredClone(this.states.get(t)??{agents:[],conversations:[]})}async cancelBackgroundTask(t){}async retryBackgroundTask(t){}}class w2{constructor(){X(this,"threads",new Map)}key(t,n){return`${t}::${n}`}_setTurns(t,n,r){this.threads.set(this.key(t,n),r.map(s=>structuredClone(s)))}async readPage(t,n,r){const s=this.threads.get(this.key(t,n))??[],i=s.length,l=r?.limit,a=Math.min(Math.max(l&&l>0?l:50,1),200),c=r?.direction??"backward",u=r?.anchor;let h,d,f;if(u===void 0)c==="forward"?(h=0,d=Math.min(a,i),f=d0);else{const x=s.findIndex(w=>w.id===u);x===-1?(h=0,d=0,f=!1):c==="forward"?(h=x+1,d=Math.min(h+a,i),f=d0)}const p=s.slice(h,d).map(x=>structuredClone(x)),m=p.at(-1);return{turns:p,hasMore:f,...m?{nextAnchor:m.id}:{}}}}class S2{constructor(t){X(this,"tickets",new Map);X(this,"carnets",new Map);X(this,"counters",new Map);X(this,"sprints",new Map);X(this,"sprintCounters",new Map);X(this,"chatSessions",new Map);X(this,"chatCounter",0);this.system=t}_seedTicket(t,n){const r=structuredClone(n);return r.sprintId===void 0&&(r.sprintId=null),this.projectTickets(t).set(r.ref,r),this.counters.set(t,Math.max(this.counters.get(t)??0,r.number)),structuredClone(r)}_seedSprint(t,n){const r={status:"planned",ticketCount:0,version:1,...n};return this.projectSprints(t).set(r.id,r),structuredClone(r)}projectSprints(t){let n=this.sprints.get(t);return n||(n=new Map,this.sprints.set(t,n)),n}recountSprints(t){const n=this.projectSprints(t),r=new Map;for(const s of this.projectTickets(t).values())s.sprintId&&r.set(s.sprintId,(r.get(s.sprintId)??0)+1);for(const s of n.values())s.ticketCount=r.get(s.id)??0}projectTickets(t){let n=this.tickets.get(t);return n||(n=new Map,this.tickets.set(t,n)),n}projectCarnets(t){let n=this.carnets.get(t);return n||(n=new Map,this.carnets.set(t,n)),n}require(t,n){const r=this.projectTickets(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`ticket ${n} not found`};return r}guard(t,n){if(t.version!==n)throw{code:"INVALID",message:`issue version conflict: expected ${n}, actual ${t.version}`}}async create(t,n){const r=(this.counters.get(t)??0)+1;this.counters.set(t,r);const s=Date.now(),i={id:`mock-ticket-${t}-${r}`,ref:`#${r}`,number:r,title:n.title,description:n.description??"",status:n.status??"open",priority:n.priority??"medium",sprintId:null,links:[],assignedAgentIds:[...n.assignedAgentIds??[]],createdBy:{kind:"user"},updatedBy:{kind:"user"},createdAt:s,updatedAt:s,version:1};return this.projectTickets(t).set(i.ref,i),this.system?.emit({type:"issueCreated",issueId:i.id,issueRef:i.ref}),structuredClone(i)}async read(t,n,r=!1){const s=structuredClone(this.require(t,n));return r&&(s.carnet=this.projectCarnets(t).get(n)??""),s}async list(t,n){const r=n??{},s=r.text?.trim().toLowerCase(),i=r.statuses??[],l=r.priorities??[];let a=[...this.projectTickets(t).values()].filter(d=>i.length===0||i.includes(d.status)).filter(d=>l.length===0||l.includes(d.priority)).filter(d=>!r.assignedAgentId||d.assignedAgentIds.includes(r.assignedAgentId)).filter(d=>!s||d.title.toLowerCase().includes(s)||d.description.toLowerCase().includes(s));a=r.sort?QE(a,r.sort):a.sort((d,f)=>f.number-d.number);const c=Number.parseInt(r.cursor??"0",10)||0,u=Math.min(Math.max(r.limit??100,1),500),h=Math.min(a.length,c+u);return{items:a.slice(c,h).map(d=>({ref:d.ref,path:`.ideai/tickets/${d.number}.md`,title:d.title,status:d.status,priority:d.priority,sprintId:d.sprintId??null,assignedAgentIds:[...d.assignedAgentIds],updatedAt:d.updatedAt})),...hc.targetRef===r&&c.kind===s)||l.links.push({targetRef:r,kind:s}),this.bump(l),this.system?.emit({type:"issueLinked",issueRef:n,target:r,kind:s,version:l.version}),structuredClone(l)}async unlink(t,n,r,s,i){const l=this.require(t,n);return this.guard(l,s),l.links=l.links.filter(a=>a.targetRef!==r||i!==void 0&&a.kind!==i),this.bump(l),this.system?.emit({type:"issueUnlinked",issueRef:n,target:r,kind:i??"relatesTo",version:l.version}),structuredClone(l)}async assign(t,n,r,s,i){const l=this.require(t,n);this.guard(l,i);const a=l.assignedAgentIds.includes(r);return s&&!a&&l.assignedAgentIds.push(r),!s&&a&&(l.assignedAgentIds=l.assignedAgentIds.filter(c=>c!==r)),this.bump(l),this.system?.emit({type:s?"issueAgentAssigned":"issueAgentUnassigned",issueRef:n,agentId:r,version:l.version}),structuredClone(l)}async listSprints(t){return this.recountSprints(t),[...this.projectSprints(t).values()].sort((n,r)=>n.order-r.order).map(n=>structuredClone(n))}async setTicketSprint(t,n,r,s){const i=this.require(t,n);if(this.guard(i,s),r!==null&&!this.projectSprints(t).has(r))throw{code:"NOT_FOUND",message:`sprint ${r} not found`};const l=i.sprintId??null;return i.sprintId=r,this.bump(i),this.recountSprints(t),this.system?.emit({type:"issueSprintChanged",issueRef:n,from:l,to:r,version:i.version}),structuredClone(i)}async createSprint(t,n){const r=this.projectSprints(t),s=(this.sprintCounters.get(t)??0)+1;this.sprintCounters.set(t,s);const i=r.size===0?1:Math.max(...[...r.values()].map(a=>a.order))+1,l={id:`mock-sprint-${t}-${s}`,order:i,name:n,status:"planned",ticketCount:0,version:1};return r.set(l.id,l),this.system?.emit({type:"sprintCreated",sprintId:l.id,order:l.order}),structuredClone(l)}async renameSprint(t,n,r,s){const i=this.requireSprint(t,n);return this.guardSprint(i,s),i.name=r,i.version+=1,this.system?.emit({type:"sprintRenamed",sprintId:n,name:r,version:i.version}),structuredClone(i)}async reorderSprints(t,n){const r=this.projectSprints(t);for(const i of n)this.requireSprint(t,i);const s=[...r.values()].filter(i=>!n.includes(i.id)).sort((i,l)=>i.order-l.order).map(i=>i.id);return[...n,...s].forEach((i,l)=>{const a=r.get(i);a&&(a.order=l+1,this.system?.emit({type:"sprintReordered",sprintId:i,order:a.order,version:a.version}))}),this.listSprints(t)}async deleteSprint(t,n){this.requireSprint(t,n);for(const r of this.projectTickets(t).values())r.sprintId===n&&(r.sprintId=null,this.bump(r),this.system?.emit({type:"issueSprintChanged",issueRef:r.ref,from:n,to:null,version:r.version}));this.projectSprints(t).delete(n),this.system?.emit({type:"sprintDeleted",sprintId:n})}async openTicketChat(t,n,r){this.require(t,n);const s=`mock-ticket-chat-${++this.chatCounter}`;return this.chatSessions.set(n,s),this.system?.emit({type:"ticketAssistantOpened",issueRef:n,profileId:r}),{sessionId:s,requester:"ticket-assistant",issueRef:n}}async closeTicketChat(t,n){this.chatSessions.delete(n)&&this.system?.emit({type:"ticketAssistantClosed",issueRef:n})}async sendTicketChat(t,n,r){if(![...this.chatSessions.values()].includes(t))throw{code:"NOT_FOUND",message:`chat session ${t} not found`};const s=`Assistant: reçu « ${n} ».`,i=[{kind:"textDelta",text:"Assistant: reçu "},{kind:"textDelta",text:`« ${n} ».`},{kind:"final",content:s}];for(const l of i)await Promise.resolve(),r(l)}requireSprint(t,n){const r=this.projectSprints(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`sprint ${n} not found`};return r}guardSprint(t,n){if(t.version!==n)throw{code:"INVALID",message:`sprint version conflict: expected ${n}, actual ${t.version}`}}}class k2{constructor(){X(this,"store",new Map)}read(t){const n=this.store.get(t);if(n===void 0)return null;try{return JSON.parse(n)}catch{return this.store.delete(t),null}}write(t,n){try{this.store.set(t,JSON.stringify(n))}catch{}}remove(t){this.store.delete(t)}}function C2(e,t){const n={allow:0,ask:1,deny:2},r=e??t??"ask";return t&&n[t]>=n[r]?t:r}class j2{constructor(){X(this,"plugins",[]);X(this,"seq",0)}summaryFor(t){return{topLevelMenus:0,menuItems:0,layouts:0,mcpServers:0}}_seedPlugin(t){this.plugins.push(t)}async listPlugins(){return structuredClone(this.plugins)}async reviewPackage(t){this.seq+=1;const n=t.path.split("/").pop()??t.path;return{id:`mock.plugin.${this.seq}`,displayName:n.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",description:`Reviewed from ${t.sourceKind}: ${t.path}`,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`),issues:[],installable:!0}}async install(t,n){this.seq+=1;const r=n.split("/").pop()??n,s={id:`mock.plugin.${this.seq}`,displayName:r.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",sourceKind:t,sourceLabel:n,lifecycleState:"enabled",enabled:!0,pendingUninstall:!1,restartRequired:!0,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`)};return this.plugins.push(s),{plugin:structuredClone(s),restartRequired:!0}}installFromArchive(t){return this.install("archive",t)}installFromDirectory(t){return this.install("directory",t)}async setEnabled(t,n){const r=this.plugins.find(i=>i.id===t);if(!r)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};const s=n?"enabled":"disabled";return r.enabled=n,r.lifecycleState=s,r.restartRequired=!0,structuredClone(r)}async uninstall(t){const n=this.plugins.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};return this.plugins.splice(n,1),{pluginId:t,restartRequired:!0}}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){}}function N2(){const e=new ZE,t=new JE;return{system:t,agent:e,input:new v2,terminal:new e2,project:new t2,layout:new n2,git:new s2,remote:new i2,profile:new c2,modelServer:new u2,desktopServer:new f2,template:new p2(e),skill:new m2(e),memory:new g2,embedder:new x2,device:new _2,permission:new y2,workState:new b2,conversation:new w2,ticket:new S2(t),window:new l2,focusedProject:new o2,uiPreferences:new k2,plugin:new j2}}function ow(){const e=globalThis.fetch;return typeof e=="function"?e.bind(globalThis):e}function E2(e,t){if(e&&typeof e=="object"){const n=e,r=typeof n.code=="string"?n.code:void 0,s=typeof n.message=="string"?n.message:void 0;if(r||s)return{code:r??"ERROR",message:s??t}}return{code:"TRANSPORT_ERROR",message:t}}class P2{constructor(t){X(this,"baseUrl");X(this,"token");X(this,"fetchImpl");X(this,"onUnauthorized");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.onUnauthorized=t.onUnauthorized,this.fetchImpl=t.fetchImpl??ow()}invoke(t,n={}){return this.request("POST","/api/invoke",{command:t,args:n},`command '${t}'`)}async request(t,n,r,s=`${t} ${n}`){const i={"Content-Type":"application/json"};this.token&&(i.Authorization=`Bearer ${this.token}`);let l;try{l=await this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:i,body:r===void 0?void 0:JSON.stringify(r),credentials:"same-origin"})}catch(c){throw{code:"TRANSPORT_ERROR",message:`HTTP request for ${s} failed: ${String(c)}`}}if(!l.ok){l.status===401&&this.onUnauthorized?.();let c;try{c=await l.json()}catch{c=void 0}throw E2(c,`${s} failed (HTTP ${l.status})`)}let a;try{a=await l.json()}catch{a=void 0}return a}}function A2(e){let t="";for(let n=0;naw(i.bytesBase64)),n=t.reduce((i,l)=>i+l.length,0),r=new Uint8Array(n);let s=0;for(const i of t)r.set(i,s),s+=i.length;return r}class cw{constructor(t){X(this,"wsUrl");X(this,"token");X(this,"socketFactory");X(this,"reconnectBaseMs");X(this,"reconnectMaxMs");X(this,"setTimeoutImpl");X(this,"clearTimeoutImpl");X(this,"onReconnectFailed");X(this,"socket",null);X(this,"opening",null);X(this,"disposed",!1);X(this,"everConnected",!1);X(this,"connState","connecting");X(this,"reconnectAttempt",0);X(this,"reconnectHandle",null);X(this,"outputSinks",new Map);X(this,"terminals",new Map);X(this,"pending",new Map);X(this,"domainEventHandler",null);X(this,"connListeners",new Set);this.wsUrl=t.wsUrl.replace(/\/+$/,""),this.token=t.token,this.socketFactory=t.socketFactory??(n=>new WebSocket(n)),this.reconnectBaseMs=t.reconnectBaseMs??500,this.reconnectMaxMs=t.reconnectMaxMs??1e4,this.setTimeoutImpl=t.setTimeoutImpl??((n,r)=>setTimeout(n,r)),this.clearTimeoutImpl=t.clearTimeoutImpl??(n=>clearTimeout(n)),this.onReconnectFailed=t.onReconnectFailed}getConnectionState(){return this.connState}onConnectionStateChange(t){return this.connListeners.add(t),()=>this.connListeners.delete(t)}setConnState(t){if(this.connState!==t){this.connState=t;for(const n of this.connListeners)n(t)}}setDomainEventHandler(t){this.domainEventHandler=t}clearDomainEventHandler(){this.domainEventHandler=null}setOutputSink(t,n){this.outputSinks.set(t,n)}removeOutputSink(t){this.outputSinks.delete(t)}async ensureConnected(){if(!this.socket)return this.opening?this.opening:this.connect()}connect(){return this.setConnState(this.everConnected?"reconnecting":"connecting"),this.opening=new Promise((t,n)=>{const r=this.token?`${this.wsUrl}${rx}?token=${encodeURIComponent(this.token)}`:`${this.wsUrl}${rx}`,s=this.socketFactory(r);s.onopen=()=>{this.socket=s,this.opening=null,this.everConnected=!0,this.reconnectAttempt=0,this.setConnState("connected"),t()},s.onerror=i=>{this.opening=null,n(i)},s.onclose=()=>this.handleSocketClosed(),s.onmessage=i=>this.handleMessage(i.data)}),this.opening}handleSocketClosed(){if(this.socket=null,this.opening=null,this.rejectAllPending({code:"WS_CLOSED",message:"socket closed"}),this.disposed){this.setConnState("closed");return}if(this.setConnState("reconnecting"),this.terminals.size>0)for(const t of this.terminals.values())t.onData(Su("déconnecté — reconnexion…"));this.needsReconnect()&&this.scheduleReconnect()}needsReconnect(){return this.terminals.size>0||this.domainEventHandler!==null}scheduleReconnect(){if(this.disposed||this.reconnectHandle)return;const t=Math.min(this.reconnectMaxMs,this.reconnectBaseMs*2**this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectHandle=this.setTimeoutImpl(()=>{this.reconnectHandle=null,this.reconnectNow()},t)}async reconnectNow(){if(!this.disposed)try{await this.connect(),await this.reattachAll()}catch{this.onReconnectFailed?.(),this.needsReconnect()&&this.scheduleReconnect()}}async reattachAll(){for(const[t,n]of this.terminals)try{const s=(await this.send("terminal.attach",{sessionId:t,lastSeq:n.lastSeq})).payload;n.onData(Su("reconnecté"));const i=lx(s);i.length>0&&n.onData(i),typeof s.nextSeq=="number"&&(n.lastSeq=Math.max(0,s.nextSeq-1))}catch{}}openTerminal(t){return this.attachInternal("terminal.open",{cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}launchAgent(t){return this.attachInternal("agent.launch",{projectId:t.projectId,agentId:t.agentId,nodeId:t.nodeId??null,rows:t.rows,cols:t.cols,conversationId:t.conversationId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}attachTerminal(t){return this.attachInternal("terminal.attach",{sessionId:t.sessionId,rows:t.rows,cols:t.cols,lastSeq:t.lastSeq??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:t.lastSeq??0},t.sessionId)}async attachInternal(t,n,r,s){const l=(await this.send(t,n)).payload,a=s??l.session.sessionId;return typeof l.nextSeq=="number"&&(r.lastSeq=Math.max(0,l.nextSeq-1)),this.terminals.set(a,r),this.setOutputSink(a,r.onData),{sessionId:a,scrollback:lx(l),assignedConversationId:l.assignedConversationId,status:l.status}}async detachTerminal(t){this.removeTerminal(t),await this.sendFireAndForget("terminal.detach",{sessionId:t})}async closeTerminalSession(t){this.removeTerminal(t),await this.send("terminal.close",{sessionId:t})}removeTerminal(t){this.terminals.delete(t),this.outputSinks.delete(t)}async send(t,n){await this.ensureConnected();const r=this.socket;if(!r)throw{code:"WS_CLOSED",message:"socket not connected"};const s=ix(),i={id:s,kind:t,payload:n},l=new Promise((a,c)=>{this.pending.set(s,{resolve:a,reject:c})});return r.send(JSON.stringify(i)),l}async sendFireAndForget(t,n){await this.ensureConnected();const s={id:ix(),kind:t,payload:n};this.socket?.send(JSON.stringify(s))}static encodeInput(t){return A2(t)}disconnect(){this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disconnected"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null;const t=this.socket;t&&(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close()),this.socket=null,this.opening=null,this.everConnected=!1,this.reconnectAttempt=0,this.setConnState("closed")}dispose(){this.disposed=!0,this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disposed"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null,this.socket?.close(),this.socket=null,this.opening=null,this.setConnState("closed")}rejectAllPending(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}switch(n.kind){case"terminal.output":{const r=n.payload,s=this.terminals.get(r.sessionId);s&&typeof r.seq=="number"&&(s.lastSeq=r.seq);const i=this.outputSinks.get(r.sessionId);i&&i(aw(r.bytesBase64));return}case"terminal.status":{const r=n.payload;this.handleStatus(r);return}case"event.domain":{this.domainEventHandler?.(n.payload);return}}if(n.replyTo){const r=this.pending.get(n.replyTo);r&&(this.pending.delete(n.replyTo),n.kind==="error"?r.reject(n.payload):r.resolve(n))}}handleStatus(t){const n=this.terminals.get(t.sessionId);if(n)if(t.status==="exited"||t.status==="closed"){const r=t.exitCode;n.onData(Su(r==null?"session terminée":`session terminée (code ${r})`)),n.onStatus?.(t.status,t.exitCode),this.removeTerminal(t.sessionId)}else n.onStatus?.(t.status,t.exitCode)}}const ku="idea.web.paired";function L2(){const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n),removeItem:t=>void e.delete(t)}}function D2(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return L2()}function R2(){return typeof window<"u"&&window.location?window.location.origin:"http://localhost"}const M2={invalidOrExpired:"Code invalide ou expiré.",invalidName:"Nom d'appareil invalide (1 à 40 caractères). Le code reste valable.",rateLimited:"Trop de tentatives. Réessayez dans quelques minutes avec un nouveau code.",pairingFailed:"Échec de l'appairage."};function I2(e,t){const n=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;let r;return n==="invalid_or_expired"?r="invalidOrExpired":n==="invalid_name"?r="invalidName":n==="rate_limited"||t===429?r="rateLimited":t===401||t===403?r="invalidOrExpired":r="pairingFailed",{code:r,message:M2[r]}}class O2{constructor(t={}){X(this,"baseUrl");X(this,"fetchImpl");X(this,"store");X(this,"unauthorizedHandlers",new Set);this.baseUrl=(t.baseUrl??R2()).replace(/\/+$/,""),this.fetchImpl=t.fetchImpl??ow(),this.store=t.store??D2()}isPaired(){return this.store.getItem(ku)==="1"}markPaired(){this.store.setItem(ku,"1")}forget(){this.store.removeItem(ku)}async logout(){try{await this.fetchImpl(`${this.baseUrl}/api/logout`,{method:"POST",credentials:"same-origin"})}catch{}finally{this.forget()}}async pair(t,n){let r;try{r=await this.fetchImpl(`${this.baseUrl}/api/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,name:n})})}catch(s){throw{code:"TRANSPORT_ERROR",message:`Impossible de joindre le serveur : ${String(s)}`}}if(!r.ok){let s;try{s=await r.json()}catch{s=void 0}throw I2(s,r.status)}this.markPaired()}notifyUnauthorized(){this.forget();for(const t of this.unauthorizedHandlers)t()}onUnauthorized(t){return this.unauthorizedHandlers.add(t),()=>this.unauthorizedHandlers.delete(t)}}let Cu=null;function uw(){return Cu||(Cu=new O2),Cu}let dp=null;function B2(e){dp=e}function Bh(){return dp}function ox(){dp?.disconnect()}class z2{constructor(t){this.http=t}async listDevices(){return(await this.http.request("GET","/api/devices")).devices}createPairingCode(){return this.http.request("POST","/api/pairing-code")}renameDevice(t,n){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/rename`,{name:n})}revokeDevice(t){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/revoke`)}revokeAllDevices(){return this.http.request("POST","/api/devices/revoke-all")}}class F2{constructor(t){this.http=t}listProjects(){return this.http.invoke("list_projects")}createProject(t,n){return this.http.invoke("create_project",{request:{name:t,root:n}})}openProject(t){return this.http.invoke("open_project",{projectId:t})}async closeProject(t){await this.http.invoke("close_project",{projectId:t})}readProjectContext(t){return this.http.invoke("read_project_context",{projectId:t})}async updateProjectContext(t,n){await this.http.invoke("update_project_context",{request:{projectId:t,content:n}})}}class $2{constructor(t){this.http=t}loadLayout(t,n){return this.http.invoke("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return this.http.invoke("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return this.http.invoke("list_layouts",{projectId:t})}createLayout(t,n,r){return this.http.invoke("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return this.http.invoke("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return this.http.invoke("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return this.http.invoke("set_active_layout",{request:{projectId:t,layoutId:n}})}}class W2{constructor(t){this.http=t}status(t){return this.http.invoke("git_status",{projectId:t})}async stage(t,n){await this.http.invoke("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await this.http.invoke("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return this.http.invoke("git_commit",{request:{projectId:t,message:n}})}branches(t){return this.http.invoke("git_branches",{projectId:t})}async checkout(t,n){await this.http.invoke("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return this.http.invoke("git_log",{projectId:t,limit:n})}async init(t){await this.http.invoke("git_init",{projectId:t})}graph(t,n){return this.http.invoke("git_graph",{projectId:t,limit:n})}}class H2{constructor(t){this.http=t}firstRunState(){return this.http.invoke("first_run_state")}referenceProfiles(){return this.http.invoke("reference_profiles")}detectProfiles(t){return this.http.invoke("detect_profiles",{request:{candidates:t}})}listProfiles(){return this.http.invoke("list_profiles")}saveProfile(t){return this.http.invoke("save_profile",{request:{profile:t}})}async deleteProfile(t){await this.http.invoke("delete_profile",{profileId:t})}configureProfiles(t){return this.http.invoke("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return this.http.invoke("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return this.http.invoke("list_opencode_providers")}saveOpenCodeProviderProfile(t){return this.http.invoke("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class U2{constructor(t){this.http=t}listModelServers(){return this.http.invoke("list_model_servers")}saveModelServer(t){return this.http.invoke("save_model_server",{request:{config:t}})}async deleteModelServer(t){await this.http.invoke("delete_model_server",{serverId:t})}previewModelServerCommand(t){return this.http.invoke("preview_model_server_command",{config:t})}}class q2{constructor(t){this.http=t}listTemplates(){return this.http.invoke("list_templates")}createTemplate(t){return this.http.invoke("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return this.http.invoke("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await this.http.invoke("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return this.http.invoke("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return this.http.invoke("detect_agent_drift",{projectId:t})}syncAgent(t,n){return this.http.invoke("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class V2{constructor(t){this.http=t}listSkills(t,n){return this.http.invoke("list_skills",{projectId:t,scope:n})}createSkill(t){return this.http.invoke("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,s){return this.http.invoke("update_skill",{request:{projectId:t,scope:n,skillId:r,content:s}})}async deleteSkill(t,n,r){await this.http.invoke("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,s){await this.http.invoke("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:s}})}async unassignSkill(t,n,r){await this.http.invoke("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class K2{constructor(t){this.http=t}listMemories(t){return this.http.invoke("list_memories",{projectId:t})}getMemory(t,n){return this.http.invoke("get_memory",{projectId:t,slug:n})}createMemory(t){return this.http.invoke("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,s,i){return this.http.invoke("update_memory",{request:{projectId:t,slug:n,description:r,type:s,content:i}})}async deleteMemory(t,n){await this.http.invoke("delete_memory",{projectId:t,slug:n})}readIndex(t){return this.http.invoke("read_memory_index",{projectId:t})}resolveLinks(t,n){return this.http.invoke("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return this.http.invoke("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class G2{constructor(t){this.http=t}listEmbedderProfiles(){return this.http.invoke("list_embedder_profiles")}saveEmbedderProfile(t){return this.http.invoke("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await this.http.invoke("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return this.http.invoke("describe_embedder_engines")}}class Y2{constructor(t){this.http=t}getProjectPermissions(t){return this.http.invoke("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return this.http.invoke("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return this.http.invoke("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return this.http.invoke("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getProjectSystemPermissions(t){return this.http.invoke("get_project_system_permissions",{projectId:t})}updateProjectSystemPermissions(t,n){return this.http.invoke("update_project_system_permissions",{request:{projectId:t,permissions:n}})}updateAgentSystemPermissions(t,n,r){return this.http.invoke("update_agent_system_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentSystemPermissions(t,n){return this.http.invoke("resolve_agent_system_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return this.http.invoke("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return this.http.invoke("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return this.http.invoke("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}class X2{constructor(t){this.http=t}async getProjectWorkState(t){const n=await this.http.invoke("get_project_work_state",{projectId:t});return ap(n)}async cancelBackgroundTask(t){await this.http.invoke("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await this.http.invoke("retry_background_task",{taskId:t})}}class Q2{constructor(t){this.http=t}async readPage(t,n,r){const s=await this.http.invoke("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return iw(s)}}class J2{constructor(t){this.http=t}async interrupt(t,n){await this.http.invoke("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){await this.http.invoke("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}})}async setFrontAttached(t,n){await this.http.invoke("set_front_attached",{request:{agentId:t,attached:n}})}async cancelResume(t){return this.http.invoke("cancel_resume",{agentId:t})}async setResumeAt(t,n){await this.http.invoke("set_resume_at",{agentId:t,resetsAtMs:n})}}function at(e){throw{code:"UNSUPPORTED_ON_WEB",message:`${e} is not available in the web client (desktop-only).`}}class Z2{openViewWindow(){return at("Detaching a panel into an OS window")}closeViewWindow(){return at("Closing a detached OS window")}listOpenViewWindows(){return Promise.resolve([])}onViewWindowClosed(t){return Promise.resolve(()=>{})}}class eP{setFocusedProject(t){return Promise.resolve()}getFocusedProject(){return Promise.resolve(null)}onFocusedProjectChanged(t){return Promise.resolve(()=>{})}}class tP{connect(){return at("Remote (SSH/WSL) connection")}}class nP{async getExposureSettings(){return at("Embedded server settings")}async saveExposureSettings(t){return at("Embedded server settings")}async previewExposure(t){return at("Embedded server settings")}async status(){return at("Embedded server status")}async start(){return at("Starting the embedded server")}async stop(){return at("Stopping the embedded server")}onStatusChanged(t){return Promise.resolve(()=>{})}}class rP{async listPlugins(){return at("Plugin management")}async reviewPackage(t){return at("Plugin management")}async installFromArchive(t){return at("Plugin management")}async installFromDirectory(t){return at("Plugin management")}async setEnabled(t,n){return at("Plugin management")}async uninstall(t){return at("Plugin management")}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){return at("Plugin management")}}function ec(e,t,n){return{sessionId:e,...n?{assignedConversationId:n}:{},async write(r){await t.sendFireAndForget("terminal.input",{sessionId:e,bytesBase64:cw.encodeInput(r)})},async resize(r,s){await t.sendFireAndForget("terminal.resize",{sessionId:e,rows:r,cols:s})},detach(){t.detachTerminal(e)},async close(){await t.closeTerminalSession(e)}}}class sP{constructor(t,n){this.http=t,this.ws=n}health(t){return this.http.invoke("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await this.ws.ensureConnected(),this.ws.setDomainEventHandler(t),()=>this.ws.clearDomainEventHandler()}pickFolder(){return at("Native folder picker")}pickArchiveFile(){return at("Native file picker")}onAppExitWorkGuard(t){return Promise.resolve(()=>{})}confirmAppExit(){return at("Confirming an app exit")}}class iP{constructor(t){this.ws=t}async openTerminal(t,n){const r=await this.ws.openTerminal({cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null,onData:n});return ec(r.sessionId,this.ws)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:ec(r.sessionId,this.ws),scrollback:r.scrollback}}async closeTerminal(t){await this.ws.closeTerminalSession(t)}}class lP{constructor(t,n){this.http=t,this.ws=n}listAgents(t){return this.http.invoke("list_agents",{projectId:t})}listLiveAgents(t){return this.http.invoke("list_live_agents",{projectId:t})}listResumableAgents(t){return this.http.invoke("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return this.http.invoke("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return this.http.invoke("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return this.http.invoke("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,s,i){return this.http.invoke("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:s,cols:i}})}readContext(t,n){return this.http.invoke("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await this.http.invoke("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await this.http.invoke("delete_agent",{projectId:t,agentId:n})}inspectConversation(t,n,r){return this.http.invoke("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}async launchAgent(t,n,r,s){const i=await this.ws.launchAgent({projectId:t,agentId:n,nodeId:r.nodeId??null,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,onData:s});return ec(i.sessionId,this.ws,i.assignedConversationId)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:ec(r.sessionId,this.ws),scrollback:r.scrollback}}}class oP{constructor(t,n){this.http=t,this.ws=n}create(t,n){return this.http.invoke("ticket_create",{request:{projectId:t,...n}})}read(t,n,r=!1){return this.http.invoke("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}list(t,n){const{statuses:r,priorities:s,...i}=n??{};return this.http.invoke("ticket_list",{request:{projectId:t,statuses:r??[],priorities:s??[],...i}})}update(t,n,r){return this.http.invoke("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await this.http.invoke("ticket_delete",{request:{projectId:t,ref:n}})}readCarnet(t,n){return this.http.invoke("ticket_read_carnet",{request:{projectId:t,ref:n}})}updateCarnet(t,n,r,s){return this.http.invoke("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:s}})}link(t,n,r,s,i){return this.http.invoke("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:s,expectedVersion:i}})}unlink(t,n,r,s,i){return this.http.invoke("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:s,kind:i}})}assign(t,n,r,s,i){return this.http.invoke("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:s,expectedVersion:i}})}async listSprints(t){return(await this.http.invoke("sprint_list",{request:{projectId:t}})).items}setTicketSprint(t,n,r,s){return r===null?this.http.invoke("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:s}}):this.http.invoke("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:s}})}createSprint(t,n){return this.http.invoke("sprint_create",{request:{projectId:t,name:n}})}renameSprint(t,n,r,s){return this.http.invoke("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:s}})}async reorderSprints(t,n){return(await this.http.invoke("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await this.http.invoke("sprint_delete",{request:{projectId:t,sprintId:n}})}openTicketChat(t,n,r){return this.http.invoke("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await this.http.invoke("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const i=(await this.ws.send("chat.send",{sessionId:t,prompt:n})).payload;i&&i.chunk&&r(i.chunk)}}function aP(e){const t=typeof window<"u"&&window.location?window.location.origin:"http://localhost",n=e.baseUrl??t,r=e.wsUrl??n.replace(/^http(s?):\/\//,(s,i)=>`ws${i}://`);return{baseUrl:n,wsUrl:r}}function cP(e={}){const{baseUrl:t,wsUrl:n}=aP(e),r=uw();let s;const i=new P2({baseUrl:t,token:e.token,onUnauthorized:()=>{r.notifyUnauthorized(),s?.disconnect()}});return s=new cw({wsUrl:n,token:e.token,onReconnectFailed:()=>{i.invoke("health",{request:null}).catch(()=>{})}}),B2(s),{system:new sP(i,s),agent:new lP(i,s),input:new J2(i),terminal:new iP(s),project:new F2(i),layout:new $2(i),git:new W2(i),remote:new tP,profile:new H2(i),modelServer:new U2(i),desktopServer:new nP,template:new q2(i),skill:new V2(i),memory:new K2(i),embedder:new G2(i),device:new z2(i),permission:new Y2(i),workState:new X2(i),conversation:new Q2(i),ticket:new oP(i,s),window:new Z2,focusedProject:new eP,uiPreferences:new lw,plugin:new rP}}function uP(e){return"http"}const dw=g.createContext(null);function hw(){return uP()}function dP(){switch(hw()){case"mock":return N2();case"http":return cP();case"tauri":return VE()}}function hP({children:e,gateways:t}){const n=g.useMemo(()=>t??dP(),[t]);return o.jsx(dw.Provider,{value:n,children:e})}function fe(){const e=g.useContext(dw);if(!e)throw new Error("useGateways must be used within a ");return e}function hp({cwd:e,open:t,reattach:n,sessionId:r,onSessionId:s,agentMode:i=!1,portal:l,onReady:a,refitSignal:c,systemPermissions:u}){const{terminal:h}=fe(),d=g.useRef(null),[f,p]=g.useState(null),m=g.useRef(t);m.current=t;const x=g.useRef(n);x.current=n;const w=g.useRef(r);w.current=r;const v=g.useRef(s);v.current=s;const _=g.useRef(h);_.current=h;const y=g.useRef(i);y.current=i;const b=g.useRef(l);b.current=l;const C=g.useRef(a);C.current=a;const S=g.useRef(null);g.useEffect(()=>{const A=d.current,k=_.current,D=m.current??k?.openTerminal.bind(k),R=x.current??k?.reattach.bind(k);if(!A||!D)return;p(null);const E=new QN({convertEol:!1,cursorBlink:!0,fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'}),O=new eE;E.loadAddon(O);try{E.open(A)}catch{E.dispose();return}try{O.fit()}catch{}let I=!1,W=null;const G=new TextEncoder;let P="";const z=E.onData($=>{const B=b.current;y.current&&B&&(B.onHumanData($),B.isSuspended())||(W?W.write(G.encode($)):P+=$)});C.current?.({send:$=>{I||E.input($)},focus:()=>{I||E.focus()}});const j=$=>{I||E.write($)},se=$=>{if(I){$.detach();return}W=$,y.current&&b.current?.bindHandle($),P&&($.write(G.encode(P)),P="")},q=$=>{if(!I){if(fP($)==="AGENT_ALREADY_RUNNING"){E.write(`\r -\x1B[2mCellule disponible — l'agent est en cours dans une autre cellule.\x1B[0m\r -`);return}p(`Échec du lancement de l'agent : ${ax($)}`),E.write(`\r -\x1B[31mfailed to open terminal: ${ax($)}\x1B[0m\r -`)}},T=w.current;T&&R?R(T,j).then(({handle:$,scrollback:B})=>{if(I){$.detach();return}B.length>0&&E.write(B),se($)}).catch(()=>{I||D({cwd:e,rows:E.rows,cols:E.cols},j).then($=>{v.current?.($.sessionId),se($)}).catch(q)}):D({cwd:e,rows:E.rows,cols:E.cols},j).then($=>{v.current?.($.sessionId),se($)}).catch(q);let re=0,ee=E.rows,Q=E.cols;const V=8;let Y=0;const oe=()=>{if(re=0,!I){if(A.clientWidth===0||A.clientHeight===0){Y{re&&cancelAnimationFrame(re),re=requestAnimationFrame(oe)},Pe=new ResizeObserver(pe);return Pe.observe(A),S.current=pe,()=>{I=!0,S.current=null,re&&cancelAnimationFrame(re),Pe.disconnect(),z.dispose(),b.current?.unbindHandle(),W&&W.detach(),E.dispose()}},[e]),g.useEffect(()=>{c!==void 0&&S.current?.()},[c]);const N=u!=null&&(u.runtimeLock.state==="locked"||u.effective==="deny"),L=u?.runtimeLock.reason??u?.control.reason??"Le réseau est interdit pour cette cellule.";return o.jsxs("div",{"data-testid":"terminal-view",style:{position:"relative",width:"100%",height:"100%",minHeight:"16rem"},children:[o.jsx("div",{ref:d,style:{width:"100%",height:"100%"}}),N&&o.jsxs("div",{role:"status","data-testid":"terminal-network-banner",style:{position:"absolute",top:8,left:8,right:8,padding:"0.5rem 0.75rem",border:"1px solid rgba(245, 158, 11, 0.45)",borderRadius:6,background:"rgba(24, 24, 27, 0.94)",color:"var(--color-warning, #f59e0b)",fontSize:12,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:2},children:[u.runtimeLock.state==="locked"?"Réseau verrouillé par le runtime.":"Réseau interdit pour cet agent."," ",L]}),f&&o.jsx("div",{role:"alert","data-testid":"terminal-error",style:{position:"absolute",top:0,left:0,right:0,padding:"0.5rem 0.75rem",background:"rgba(120, 20, 20, 0.92)",color:"#fff",fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:3},children:f})]})}function ax(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function fP(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function pP({agentWasRunning:e,details:t,onResume:n,onNewConversation:r}){const s=e?"en cours":"clot";return o.jsx("div",{"data-testid":"resume-conversation-popup",role:"dialog","aria-label":"Reprise de conversation",style:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)"},children:o.jsxs("div",{style:{minWidth:260,maxWidth:360,padding:"16px 18px",background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:6,boxShadow:"0 8px 24px rgba(0, 0, 0, 0.5)",fontSize:13},children:[o.jsx("p",{style:{margin:"0 0 8px",fontWeight:600},children:"Reprise de conversation"}),o.jsxs("p",{style:{margin:"0 0 6px"},children:["Statut :"," ",o.jsx("span",{"data-testid":"resume-status",children:s})]}),t?.lastTopic&&o.jsxs("p",{style:{margin:"0 0 6px"},"data-testid":"resume-last-topic",children:["Dernier sujet : ",t.lastTopic]}),t?.tokenCount!==void 0&&o.jsxs("p",{style:{margin:"0 0 10px"},"data-testid":"resume-token-count",children:["Tokens : ",t.tokenCount]}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[o.jsx("button",{type:"button",onClick:n,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Reprendre la dernière conversation"}),o.jsx("button",{type:"button",onClick:r,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Nouvelle conversation"})]})]})})}const ju="\r",cx=350,mP=2e3,gP=512,xP=8,vP="[write-portal]",Pr=new TextEncoder;function _P(e){if(e.length===0)return!1;for(const t of e){const n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function yP(e,t){const{system:n,input:r}=fe(),[s,i]=g.useState(!1),l=g.useRef(0),a=g.useRef([]),c=g.useRef(null),u=g.useRef(!1),h=g.useRef(!1),d=g.useRef(null),f=g.useRef(null),p=g.useRef(r);p.current=r;const m=g.useRef(t);m.current=t;const x=g.useRef(e);x.current=e;const w=g.useRef(()=>{});w.current=()=>{const y=c.current&&d.current?d.current:null,b=f.current;b!==y&&(b&&(Ze("front-attached:set",{agent:b,attached:!1}),p.current?.setFrontAttached(b,!1).catch(C=>{Ze("front-attached:set-failed",{agent:b,attached:!1,error:Nu(C)})})),y&&(Ze("front-attached:set",{agent:y,attached:!0}),p.current?.setFrontAttached(y,!0).catch(C=>{Ze("front-attached:set-failed",{agent:y,attached:!0,error:Nu(C)})})),f.current=y)};const v=g.useRef(()=>{});return v.current=()=>{if(h.current)return;const y=a.current[0];if(!y||l.current>0)return;const b=c.current;if(!b)return;const C=m.current,S=x.current;if(!C)return;h.current=!0;const N=Date.now();u.current=!0,i(!0),(async()=>{let L=!1;try{Ze("inject:start",{agent:C,ticket:y.ticket,textBytes:Pr.encode(y.text).byteLength,queue:a.current.length,submitSequence:pa(y.submitSequence),submitDelayMs:y.submitDelayMs??cx}),await Promise.resolve();const A=l.current;A>0&&(Ze("inject:erase-human-window",{agent:C,ticket:y.ticket,count:A}),await b.write(Pr.encode("".repeat(A))),l.current=0),await bP(b,y.text,y.ticket);const k=y.submitDelayMs??cx;Ze("inject:before-submit-delay",{agent:C,ticket:y.ticket,delay:k}),await zh(k);const D=wP(y.submitSequence,y.ticket);Ze("inject:submit-write:start",{agent:C,ticket:y.ticket,submitSequence:pa(D),submitBytes:Pr.encode(D).byteLength}),await b.write(Pr.encode(D)),Ze("inject:submit-write:ok",{agent:C,ticket:y.ticket}),a.current.shift(),L=!0;try{Ze("inject:ack:start",{agent:C,ticket:y.ticket}),await p.current.delegationDelivered(S,C,y.ticket),Ze("inject:ack:ok",{agent:C,ticket:y.ticket})}catch{Ze("inject:ack:failed",{agent:C,ticket:y.ticket})}}catch(A){Ze("inject:failed",{agent:C,ticket:y.ticket,error:Nu(A)})}finally{const A=Date.now()-N,k=mP-A;k>0&&await zh(k),u.current=!1,i(!1),h.current=!1,a.current.length>0&&L&&v.current()}})()},g.useEffect(()=>{if(!n||!t){d.current=null,w.current();return}let y,b=!1;const C=t;return n.onDomainEvent(S=>{S.type==="delegationReady"&&S.agentId===C&&(a.current.push({ticket:S.ticket,text:S.text,submitSequence:S.submitSequence,submitDelayMs:S.submitDelayMs}),Ze("event:delegation-ready",{agent:C,ticket:S.ticket,textBytes:Pr.encode(S.text).byteLength,queue:a.current.length,submitSequence:pa(S.submitSequence),submitDelayMs:S.submitDelayMs}),v.current())}).then(S=>{b?S():(y=S,d.current=C,Ze("event:subscribed",{agent:C}),w.current())}),()=>{b=!0,y?.(),d.current===C&&(d.current=null,Ze("event:unsubscribed",{agent:C})),f.current===C?(p.current?.setFrontAttached(C,!1).catch(()=>{}),f.current=null):w.current()}},[n,t]),{portal:g.useMemo(()=>({onHumanData(y){if(y==="\r"||y===` -`||y===""){l.current=0,v.current();return}_P(y)&&(l.current+=1)},isSuspended(){return u.current},bindHandle(y){c.current=y,Ze("handle:bound",{agent:m.current,sessionId:y.sessionId}),w.current(),v.current()},unbindHandle(){Ze("handle:unbound",{agent:m.current,sessionId:c.current?.sessionId}),c.current=null,w.current()}}),[]),overlay:s}}function zh(e){return new Promise(t=>setTimeout(t,e))}async function bP(e,t,n){const r=SP(t,gP);for(let s=0;s0?e:(Ze("inject:empty-submit-sequence-defaulted",{ticket:t,defaultSubmitSequence:pa(ju)}),ju)}function SP(e,t){if(e.length===0)return[""];const n=[];let r="",s=0;for(const i of e){const l=Pr.encode(i).byteLength;r.length>0&&s+l>t&&(n.push(r),r="",s=0),r+=i,s+=l}return r.length>0&&n.push(r),n}function pa(e){return e==null?"":e.length===0?"":[...e].map(t=>{switch(t){case"\r":return"\\r";case` -`:return"\\n";case"":return"\\x7f";default:{const n=t.codePointAt(0);return n<32?`\\x${n.toString(16).padStart(2,"0")}`:t}}}).join("")}function Nu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Ze(e,t){console.info(vP,e,t)}function kP(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function eo(e){const{workState:t,system:n}=fe(),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{s(await t.getProjectWorkState(e))}catch(h){l(kP(h))}finally{c(!1)}},[e,t]);return g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let h,d=!1;return n.onDomainEvent(f=>{(f.type==="agentLaunched"||f.type==="agentExited"||f.type==="agentBusyChanged"||f.type==="delegationReady"||f.type==="orchestratorRequestProcessed"||f.type==="backgroundTaskChanged"||f.type==="agentInboxChanged"||f.type==="agentWakeChanged")&&u()}).then(f=>{d?f():h=f}),()=>{d=!0,h?.()}},[u,n]),{state:r,error:i,busy:a,refresh:u}}const CP=50;function fw(){return{byTarget:{},nextSeq:1}}function jP(e,t,n=CP){const{target:r,ticketId:s}=t,i={...t,seq:e.nextSeq},l=e.byTarget[r]??{},c=[...l[s]??[],i],u=c.length>n?c.slice(c.length-n):c;return{byTarget:{...e.byTarget,[r]:{...l,[s]:u}},nextSeq:e.nextSeq+1}}function NP(e,t){if(!(t in e.byTarget))return e;const{[t]:n,...r}=e.byTarget;return{byTarget:r,nextSeq:e.nextSeq}}function pw(e,t){return e.atMs-t.atMs||e.seq-t.seq}function EP(e,t){const n=e.byTarget[t];return n?Object.values(n).flat().sort(pw):[]}function PP(e,t,n){const r=[];for(const s of Object.values(e.byTarget))for(const[i,l]of Object.entries(s))if(!(n!==void 0&&i!==n))for(const a of l)a.requester===t&&r.push(a);return r.sort(pw)}const AP=()=>{},TP=fw(),LP={},DP={index:TP,busy:LP,seedBusy:AP},fp=g.createContext(null);function RP({children:e}){const{system:t}=fe(),[n,r]=g.useState(fw),[s,i]=g.useState({}),l=g.useCallback((c,u)=>{i(h=>c in h?h:{...h,[c]:u})},[]);g.useEffect(()=>{if(!t)return;let c,u=!1;return t.onDomainEvent(h=>{if(h.type==="agentAnnouncement")r(d=>jP(d,{requester:h.requester,target:h.target,ticketId:h.ticketId,text:h.text,atMs:h.atMs}));else if(h.type==="agentBusyChanged"){const{agentId:d,busy:f}=h;i(p=>({...p,[d]:f})),f||r(p=>NP(p,d))}}).then(h=>{u?h():c=h}).catch(()=>{}),()=>{u=!0,c?.()}},[t]);const a=g.useMemo(()=>({index:n,busy:s,seedBusy:l}),[n,s,l]);return o.jsx(fp.Provider,{value:a,children:e})}function pp(){return g.useContext(fp)??DP}function MP(){return g.useContext(fp)!==null}function mw(e){const{index:t,busy:n}=pp();return g.useMemo(()=>({announcements:EP(t,e),active:n[e]===!0}),[t,n,e])}function IP(e,t){const{workState:n}=fe(),{seedBusy:r}=pp(),s=MP();g.useEffect(()=>{if(!s||!n)return;let i=!1;return n.getProjectWorkState(e).then(l=>{if(i)return;const a=l.agents.find(c=>c.agentId===t);a&&r(t,a.busy.state==="busy")}).catch(()=>{}),()=>{i=!0}},[s,n,e,t,r])}function OP(e,t){const{index:n}=pp();return g.useMemo(()=>PP(n,e,t),[n,e,t])}function U(...e){return e.filter(Boolean).join(" ")}function Me({size:e=16,className:t,label:n="Loading"}){return o.jsx("span",{role:"status","aria-label":n,className:U("inline-block animate-spin rounded-full border-2 border-current border-t-transparent",t),style:{width:e,height:e}})}const BP="inline-flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors select-none disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none",zP={sm:"h-7 px-2.5 text-xs",md:"h-9 px-3.5 text-sm"},FP={primary:"bg-primary text-on-primary hover:bg-primary-hover",secondary:"bg-raised text-content border border-border hover:border-border-strong",ghost:"text-muted hover:text-content hover:bg-raised",danger:"bg-danger text-white hover:brightness-110"},M=g.forwardRef(function({variant:t="secondary",size:n="md",loading:r=!1,disabled:s,className:i,children:l,...a},c){return o.jsxs("button",{ref:c,type:a.type??"button",disabled:s||r,className:U(BP,zP[n],FP[t],i),...a,children:[r&&o.jsx(Me,{size:n==="sm"?12:14}),l]})}),$P={sm:"h-6 w-6 text-xs",md:"h-8 w-8 text-sm"},sr=g.forwardRef(function({size:t="md",className:n,children:r,...s},i){return o.jsx("button",{ref:i,type:s.type??"button",className:U("inline-flex items-center justify-center rounded-md text-muted transition-colors","hover:bg-raised hover:text-content focus-visible:outline-none","disabled:opacity-50 disabled:cursor-not-allowed",$P[t],n),...s,children:r})}),ce=g.forwardRef(function({invalid:t=!1,className:n,...r},s){return o.jsx("input",{ref:s,"aria-invalid":t||void 0,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border placeholder:text-faint outline-none transition-colors",t?"border-danger":"border-border focus:border-primary","disabled:opacity-50 disabled:cursor-not-allowed",n),...r})});function qt({label:e,hint:t,error:n,hideLabel:r,className:s,children:i}){const l=g.useId(),a=`${l}-msg`,c=n??t;return o.jsxs("div",{className:U("flex flex-col gap-1",s),children:[o.jsx("label",{htmlFor:l,className:U("text-xs font-medium text-muted",r&&"sr-only"),children:e}),i({id:l,describedBy:c?a:void 0}),c&&o.jsx("p",{id:a,role:n?"alert":void 0,className:U("text-xs",n?"text-danger":"text-faint"),children:c})]})}function ke({title:e,actions:t,flush:n,className:r,children:s,...i}){const l=e!=null||t!=null;return o.jsxs("section",{className:U("rounded-lg border border-border bg-surface",r),...i,children:[l&&o.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-2.5",children:[typeof e=="string"?o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}):e,t]}),o.jsx("div",{className:U(!n&&"p-4"),children:s})]})}function WP({items:e,value:t,onSelect:n,onClose:r,className:s}){return o.jsx("div",{role:"tablist",className:U("flex flex-wrap items-stretch gap-1",s),children:e.map(i=>{const l=i.id===t;return o.jsxs("div",{className:U("group flex items-center gap-1 rounded-md border px-1 transition-colors",l?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[o.jsx("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>n(i.id),className:U("px-2 py-1 text-sm focus-visible:outline-none",l?"font-semibold text-content":"text-muted hover:text-content"),children:i.label}),r&&o.jsx(sr,{size:"sm","aria-label":`close ${i.label}`,onClick:()=>r(i.id),className:"opacity-60 group-hover:opacity-100",children:"×"})]},i.id)})})}const HP={start:"justify-start",between:"justify-between",end:"justify-end"};function gw({justify:e="start",className:t,children:n,...r}){return o.jsx("div",{role:"toolbar",className:U("flex items-center gap-2",HP[e],t),...r,children:n})}const Sn={menuDropdown:40,floatingWindow:50,floatingWindowNested:60,toast:70},UP={sm:"max-w-sm",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"},ux='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',qi=[];function Fh({open:e,title:t,onClose:n,size:r="md",children:s}){return e?o.jsx(qP,{title:t,onClose:n,size:r,children:s}):null}function qP({title:e,onClose:t,size:n,children:r}){const s=g.useRef(null),i=g.useRef(t);return i.current=t,g.useEffect(()=>{const l=document.activeElement,a=s.current,c={};qi.push(c);const u=()=>qi[qi.length-1]===c;(a?.querySelector(ux)??a)?.focus();function d(f){if(!u())return;if(f.key==="Escape"){f.preventDefault(),i.current();return}if(f.key!=="Tab"||!a)return;const p=Array.from(a.querySelectorAll(ux));if(p.length===0){f.preventDefault(),a.focus();return}const m=p[0],x=p[p.length-1],w=document.activeElement;f.shiftKey&&w===m?(f.preventDefault(),x.focus()):!f.shiftKey&&w===x&&(f.preventDefault(),m.focus())}return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d);const f=qi.indexOf(c);f>=0&&qi.splice(f,1),l?.focus?.()}},[]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindow},onMouseDown:l=>{l.target===l.currentTarget&&t()},children:o.jsxs("div",{ref:s,role:"dialog","aria-modal":"true","aria-label":e,tabIndex:-1,className:U("flex max-h-[80vh] w-full flex-col overflow-hidden rounded-lg","border border-border bg-surface shadow-xl outline-none",UP[n??"md"]),children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:e}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`close ${e}`,onClick:t,children:"Close"})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})})}function VP({menus:e,className:t}){const[n,r]=g.useState(null),[s,i]=g.useState(null),l=g.useRef(null);function a(){r(null),i(null)}return g.useEffect(()=>{if(n===null)return;function c(h){l.current?.contains(h.target)||a()}function u(h){h.key==="Escape"&&a()}return document.addEventListener("mousedown",c),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("keydown",u)}},[n]),o.jsx("div",{ref:l,className:U("flex shrink-0 items-center gap-0.5 border-b border-border bg-surface px-2 py-1",t),children:e.map(c=>{const u=n===c.id;return o.jsxs("div",{className:"relative",children:[o.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":u,onClick:()=>{i(null),r(h=>h===c.id?null:c.id)},className:U("rounded px-2.5 py-1 text-sm transition-colors",u?"bg-raised text-content":"text-muted hover:bg-raised hover:text-content"),children:c.label}),u&&o.jsx("div",{role:"menu","aria-label":c.label,style:{zIndex:Sn.menuDropdown},className:U("absolute left-0 top-full mt-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:c.items.map(h=>{const d=(h.submenu?.length??0)>0,f=d&&s===h.id;return o.jsxs("div",{className:"relative",onMouseEnter:()=>i(d?h.id:null),children:[o.jsxs("button",{type:"button",disabled:h.disabled,"aria-haspopup":d?"menu":void 0,"aria-expanded":d?f:void 0,onClick:()=>{if(d){i(p=>p===h.id?null:h.id);return}h.onSelect(),a()},className:U("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[o.jsx("span",{children:h.label}),d?o.jsx("span",{"aria-hidden":!0,className:"text-muted",children:h.active?"● ▸":"▸"}):h.active&&o.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]}),f&&o.jsx("div",{role:"menu","aria-label":h.label,style:{zIndex:Sn.floatingWindowNested},className:U("absolute left-full top-0 ml-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:h.submenu.map(p=>o.jsxs("button",{type:"button",disabled:p.disabled,onClick:()=>{p.onSelect(),a()},className:U("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[o.jsx("span",{children:p.label}),p.active&&o.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]},p.id))})]},h.id)})})]},c.id)})})}const KP=240,GP=720;function dx({side:e,width:t,onResize:n,minWidth:r=KP,maxWidth:s=GP,"aria-label":i,children:l}){const a=g.useRef(null);function c(p){return Math.min(s,Math.max(r,p))}function u(p){p.preventDefault(),p.currentTarget.setPointerCapture?.(p.pointerId),a.current={startX:p.clientX,startWidth:t}}function h(p){const m=a.current;if(!m)return;const x=p.clientX-m.startX,w=e==="left"?x:-x;n(c(m.startWidth+w))}function d(p){if(!a.current)return;const m=p.clientX-a.current.startX,x=e==="left"?m:-m;a.current=null,n(c(t+x))}const f=o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":`resize ${e} dock`,onPointerDown:u,onPointerMove:h,onPointerUp:d,className:"shrink-0 cursor-col-resize bg-border hover:bg-border-strong",style:{flex:"0 0 4px",touchAction:"none"}});return o.jsxs("aside",{"aria-label":i??`${e} dock`,className:U("flex h-full shrink-0 bg-surface",e==="left"?"flex-row border-r border-border":"flex-row-reverse border-l border-border"),style:{width:t},children:[o.jsx("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:l}),f]})}function YP(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleTimeString()}catch{return""}}function XP({projectId:e,agentId:t}){IP(e,t);const{announcements:n,active:r}=mw(t),s=g.useRef(null);return g.useEffect(()=>{const i=s.current;i&&(i.scrollTop=i.scrollHeight)},[n]),r?o.jsxs("div",{"data-testid":"target-announcements-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-[4] flex flex-col bg-canvas/85 backdrop-blur-sm",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-surface/80 px-4 py-2",children:[o.jsx(Me,{size:14}),o.jsx("span",{className:"text-sm font-medium text-content",children:"Un agent est en train de lui parler…"})]}),o.jsx("div",{ref:s,className:"flex flex-1 flex-col justify-end gap-1.5 overflow-hidden px-6 py-4",children:n.map(i=>{const l=YP(i.atMs);return o.jsxs("div",{className:"flex items-baseline gap-2 text-sm text-muted",children:[l&&o.jsx("span",{className:"shrink-0 text-xs text-faint",children:l}),o.jsx("span",{className:"whitespace-pre-wrap break-words text-content/90",children:i.text})]},i.seq)})})]}):null}function QP({requester:e,ticketId:t,limit:n=3}){const r=OP(e,t);if(r.length===0)return null;const s=r.slice(Math.max(0,r.length-n));return o.jsxs("div",{"data-testid":"announcements-preview",className:"flex flex-col gap-1 rounded-md border border-primary/25 bg-primary/5 px-2.5 py-1.5",children:[o.jsxs("span",{className:"flex items-center gap-1.5 text-[0.65rem] font-medium uppercase tracking-wide text-primary",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-primary"}),"En attente d'un agent"]}),o.jsx("ul",{className:"flex flex-col gap-0.5",children:s.map(i=>o.jsx("li",{className:"truncate text-xs text-muted",title:i.text,children:i.text},i.seq))})]})}class JP{constructor(t,n){X(this,"handlers",new Map);this.pluginId=t,this.declaredCommandIds=n}register(t,n){if(!this.declaredCommandIds.has(t))throw new Error(`plugin "${this.pluginId}" tried to register command "${t}" which is not declared by any menu item in its manifest`);return this.handlers.set(t,n),{dispose:()=>{this.handlers.get(t)===n&&this.handlers.delete(t)}}}async run(t,...n){const r=this.handlers.get(t);r&&await r(...n)}has(t){return this.handlers.has(t)}}class ZP{constructor(t,n){X(this,"components",new Map);this.pluginId=t,this.declaredLayoutTypes=n}register(t){if(!this.declaredLayoutTypes.has(t.type))throw new Error(`plugin "${this.pluginId}" tried to register layout type "${t.type}" which is not declared in its manifest`);return this.components.set(t.type,t.component),{dispose:()=>{this.components.get(t.type)===t.component&&this.components.delete(t.type)}}}get(t){return this.components.get(t)}}class eA{constructor(t){this.pluginId=t}get ownerPluginId(){return this.pluginId}}class mp{constructor(){X(this,"loaded",new Map)}add(t){this.loaded.set(t.pluginId,t)}async remove(t){const n=this.loaded.get(t);if(n)try{await n.dispose()}finally{this.loaded.delete(t)}}get(t){return this.loaded.get(t)}list(){return[...this.loaded.values()]}topLevelMenus(){return this.list().flatMap(t=>t.contributes.menus.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,menu:n})))}menuItems(){return this.list().flatMap(t=>t.contributes.menuItems.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,item:n})))}layoutComponent(t,n){return this.loaded.get(t)?.layouts.get(n)}layoutContributions(){return this.list().flatMap(t=>t.contributes.layouts.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,layout:n})))}async runCommand(t,n,...r){await this.loaded.get(t)?.commands.run(n,...r)}}function tA(e){return typeof e=="object"&&e!==null&&"activate"in e&&typeof e.activate=="function"}async function nA(e,t){try{const n=await import(e.bundleUrl);if(!tA(n))return{failure:{pluginId:e.id,reason:'bundle does not export an "activate(ctx)" function'}};const r=new Set(e.contributes.menuItems.map(d=>d.command)),s=new Set(e.contributes.layouts.map(d=>d.type)),i=new JP(e.id,r),l=new ZP(e.id,s),a=new eA(e.id),c={pluginId:e.id,pluginDisplayName:e.displayName,version:e.version,commands:i,layouts:l,menu:a,...t},u=await n.activate(c);return{plugin:{pluginId:e.id,displayName:e.displayName,contributes:e.contributes,commands:i,layouts:l,menu:a,dispose:async()=>{try{await u.dispose?.()}catch{}}}}}catch(n){return{failure:{pluginId:e.id,reason:n instanceof Error?n.message:String(n)}}}}async function rA(e,t){const n=new mp,r=[],s=await Promise.all(e.map(i=>nA(i,t)));for(const i of s)"failure"in i?r.push(i.failure):n.add(i.plugin);return{registry:n,failures:r}}const sA=new Set(["projectOpen","gitRepository","agentSelected","terminalFocused","layoutCellFocused"]);function iA(e){const t=[];let n=0;for(;n=this.tokens.length}}function oA(e,t){if(e===void 0||e.trim()==="")return{ok:!0,value:!0};const n=iA(e);if(!n)return{ok:!1,reason:`invalid "when" expression: ${e}`};try{const r=new lA(n),s=r.parseOr(t);if(!r.finished())throw new Error("unexpected trailing tokens");return{ok:!0,value:s}}catch(r){const s=r instanceof Error?r.message:String(r);return{ok:!1,reason:`invalid "when" expression "${e}": ${s}`}}}const aA={registry:new mp,failures:[],loading:!1},xw=g.createContext(aA);function cA({children:e,value:t}){const n=fe(),[r,s]=g.useState(t??{registry:new mp,failures:[],loading:!0});return g.useEffect(()=>{if(t)return;let i=!1;return n.plugin.listRuntimeContributions().then(l=>rA(l.plugins,{project:n.project,git:n.git,terminal:n.terminal,agents:n.agent,system:n.system})).then(l=>{i||s({registry:l.registry,failures:l.failures,loading:!1})}).catch(()=>{i||s(l=>({...l,loading:!1}))}),()=>{i=!0}},[]),o.jsx(xw.Provider,{value:r,children:e})}function gp(){return g.useContext(xw)}function hx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:s=!1,onConfirm:i,onCancel:l}){const a=g.useRef(null);return g.useEffect(()=>{a.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.floatingWindow},onClick:l,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-md flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"whitespace-pre-line text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),o.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:s,onClick:()=>void i(),children:n})]})]})})}function Zr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function uA(){const{plugin:e,system:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(null),[l,a]=g.useState(!1),c=g.useCallback(async()=>{a(!0),i(null);try{r(await e.listPlugins())}catch(y){i(Zr(y))}finally{a(!1)}},[e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async y=>{a(!0),i(null);try{return await e.reviewPackage(y)}catch(b){return i(Zr(b)),null}finally{a(!1)}},[e]),h=g.useCallback(y=>u({sourceKind:"archive",path:y}),[u]),d=g.useCallback(y=>u({sourceKind:"directory",path:y}),[u]),f=g.useCallback(async y=>{a(!0),i(null);try{const b=await e.installFromArchive(y);return r(C=>[...C.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return i(Zr(b)),!1}finally{a(!1)}},[e]),p=g.useCallback(async y=>{a(!0),i(null);try{const b=await e.installFromDirectory(y);return r(C=>[...C.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return i(Zr(b)),!1}finally{a(!1)}},[e]),m=g.useCallback(async(y,b)=>{a(!0),i(null);try{const C=await e.setEnabled(y,b);r(S=>S.map(N=>N.id===y?C:N))}catch(C){i(Zr(C))}finally{a(!1)}},[e]),x=g.useCallback(async y=>{a(!0),i(null);try{await e.uninstall(y),r(b=>b.filter(C=>C.id!==y))}catch(b){i(Zr(b))}finally{a(!1)}},[e]),w=g.useCallback(async y=>{try{await e.openPluginsFolder(y)}catch(b){i(Zr(b))}},[e]),v=g.useCallback(()=>t.pickArchiveFile(),[t]),_=g.useCallback(()=>t.pickFolder(),[t]);return{plugins:n,error:s,busy:l,refresh:c,reviewArchive:h,reviewDirectory:d,installFromArchive:f,installFromDirectory:p,setEnabled:m,uninstall:x,openPluginsFolder:w,pickArchiveFile:v,pickDirectory:_}}const dA={enabled:"Activé",disabled:"Désactivé","pending-enable":"Activation en attente","pending-disable":"Désactivation en attente","pending-uninstall":"Désinstallation en attente",invalid:"Invalide"};function hA(){const e=uA(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(null);async function a(){l(null);const d=await e.pickArchiveFile();if(!d)return;const f=await e.reviewArchive(d);if(!f){l("La revue du paquet a échoué.");return}s({sourceKind:"archive",path:d,review:f})}async function c(){l(null);const d=await e.pickDirectory();if(!d)return;const f=await e.reviewDirectory(d);if(!f){l("La revue du paquet a échoué.");return}s({sourceKind:"directory",path:d,review:f})}async function u(){if(!r)return;(r.sourceKind==="archive"?await e.installFromArchive(r.path):await e.installFromDirectory(r.path))&&s(null)}async function h(){t&&(t.kind==="disable"?await e.setEnabled(t.plugin.id,!1):await e.uninstall(t.plugin.id),n(null))}return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:"Plugins"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{size:"sm",onClick:()=>void a(),disabled:e.busy,children:"Installer depuis une archive…"}),o.jsx(M,{size:"sm",variant:"secondary",onClick:()=>void c(),disabled:e.busy,children:"Installer depuis un dossier…"})]})]}),(e.error||i)&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error??i}),e.plugins.length===0?o.jsx(ke,{children:o.jsx("p",{className:"text-sm text-muted",children:"Aucun plugin installé."})}):o.jsx("ul",{className:"flex flex-col gap-2",children:e.plugins.map(d=>o.jsx("li",{children:o.jsxs(ke,{className:"flex items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:d.displayName}),o.jsxs("span",{className:"text-xs text-faint",children:["v",d.version]}),d.publisher&&o.jsxs("span",{className:"text-xs text-faint",children:["· ",d.publisher]}),o.jsx("span",{className:"rounded bg-raised px-1.5 py-0.5 text-[0.65rem] uppercase text-muted",children:"full-trust"})]}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted",children:[o.jsx("span",{"aria-label":"plugin state",className:d.lifecycleState==="invalid"?"text-danger":void 0,children:dA[d.lifecycleState]}),d.restartRequired&&o.jsx("span",{className:"text-warning",children:"Redémarrage requis"}),d.sourceLabel&&o.jsxs("span",{children:["· ",d.sourceLabel]})]}),d.error&&o.jsx("p",{className:"text-xs text-danger",role:"alert",children:d.error})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[d.enabled?o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>n({kind:"disable",plugin:d}),disabled:e.busy,children:"Désactiver"}):o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.setEnabled(d.id,!0),disabled:e.busy,children:"Activer"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.openPluginsFolder(d.id),disabled:e.busy,children:"Ouvrir le dossier"}),o.jsx(M,{size:"sm",variant:"danger",onClick:()=>n({kind:"uninstall",plugin:d}),disabled:e.busy,children:"Désinstaller"})]})]})},d.id))}),r&&o.jsx(hx,{title:`Installer "${r.review.displayName}" ?`,body:fA(r.review),confirmLabel:r.review.installable?"Installer":"Corriger avant d'installer",busy:e.busy,danger:!r.review.installable,onConfirm:()=>{r.review.installable?u():s(null)},onCancel:()=>s(null)}),t&&o.jsx(hx,{title:t.kind==="disable"?`Désactiver "${t.plugin.displayName}" ?`:`Désinstaller "${t.plugin.displayName}" ?`,body:t.kind==="disable"?"Ses contributions seront masquées immédiatement ; un redémarrage sera peut-être nécessaire pour purger complètement le plugin.":"Le plugin, ses fichiers et ses contributions seront supprimés après redémarrage.",confirmLabel:t.kind==="disable"?"Désactiver":"Désinstaller",danger:t.kind==="uninstall",busy:e.busy,onConfirm:()=>void h(),onCancel:()=>n(null)})]})}function fA(e){const{contributionSummary:t}=e;return[`Éditeur : ${e.publisher??"inconnu"}`,`Version : ${e.version}`,e.description??null,"Confiance : full-trust — ce plugin peut exécuter du code arbitraire dans IdeA.",`Contributions : ${t.topLevelMenus} menu(s), ${t.menuItems} item(s), ${t.layouts} layout(s), ${t.mcpServers} serveur(s) MCP.`,...e.issues.map(r=>`${r.severity==="error"?"Erreur":"Avertissement"} : ${r.message}`)].filter(r=>!!r).join(` -`)}function pA(e){return e.topLevelMenus().map(({pluginId:t,pluginDisplayName:n,menu:r})=>({id:`plugin:${r.id}`,pluginId:t,pluginDisplayName:n,label:r.label,icon:r.icon,order:r.order??0})).sort((t,n)=>t.order-n.order||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.label.localeCompare(n.label))}function mA(e,t,n){return e.menuItems().filter(({item:r})=>r.targetMenuId===t).map(({pluginId:r,pluginDisplayName:s,item:i})=>{const l=oA(i.when,n);return{id:i.id,pluginId:r,pluginDisplayName:s,targetMenuId:i.targetMenuId,label:i.label,command:i.command,enabled:l.ok?l.value:!1,disabledReason:l.ok?void 0:l.reason,groupLabel:s,order:i.order??0,iconUrl:i.icon}}).sort((r,s)=>r.order-s.order||r.pluginDisplayName.localeCompare(s.pluginDisplayName)||r.label.localeCompare(s.label))}function gA(e,t){const n=g.useMemo(()=>(i,l)=>e.runCommand(i,l),[e]),r=g.useMemo(()=>i=>mA(e,i,t).map(l=>({id:l.id,label:`${l.label} · ${l.pluginDisplayName}`,disabled:!l.enabled,onSelect:()=>{n(l.pluginId,l.command)}})),[e,t,n]);return{topLevelMenus:g.useMemo(()=>pA(e).map(i=>({id:i.id,label:i.label,items:r(i.id)})),[e,r]),itemsFor:r,runCommand:n}}function xA(e,t,n){const r=e.get(t.pluginId);if(!r){const l=n?.find(a=>a.id===t.pluginId);return l&&!l.enabled?"plugin-disabled":"plugin-missing"}return!r.contributes.layouts.some(l=>l.type===t.layoutType)||!r.layouts.get(t.layoutType)?"incompatible":"available"}const vA={"plugin-disabled":"Le plugin fournisseur est désactivé.","plugin-missing":"Le plugin fournisseur n'est pas installé.",incompatible:"Le plugin fournisseur ne déclare plus ce type de layout."};function _A({cell:e,availability:t,providerDisplayName:n,onOpenPlugins:r,onChooseAnotherLayout:s}){return o.jsxs(ke,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[o.jsx("p",{className:"text-sm font-semibold text-content",children:"Layout indisponible"}),o.jsx("p",{className:"text-xs text-muted",children:vA[t]}),o.jsxs("p",{className:"text-xs text-faint",children:["Fourni par « ",n??e.pluginId," »"]}),o.jsxs("div",{className:"mt-2 flex gap-2",children:[o.jsx(M,{size:"sm",variant:"secondary",onClick:r,children:"Ouvrir Plugins"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:s,children:"Choisir un autre layout"})]})]})}function yA({projectId:e,cell:t,installedPlugins:n,onStateChange:r,onOpenPlugins:s,onChooseAnotherLayout:i}){const{registry:l}=gp(),a=fe(),c=xA(l,t,n);if(c!=="available"){const h=l.get(t.pluginId)?.displayName??n?.find(d=>d.id===t.pluginId)?.displayName;return o.jsx(_A,{cell:t,availability:c,providerDisplayName:h,onOpenPlugins:s,onChooseAnotherLayout:i})}const u=l.layoutComponent(t.pluginId,t.layoutType);return o.jsx(u,{projectId:e,nodeId:t.id,layoutType:t.layoutType,state:t.state,setState:r,availability:"available",gateways:{project:a.project,git:a.git,terminal:a.terminal,agents:a.agent,system:a.system}})}function bA(e){return e.layoutContributions().map(({pluginId:t,pluginDisplayName:n,layout:r})=>({pluginId:t,pluginDisplayName:n,layout:r})).sort((t,n)=>(t.layout.order??0)-(n.layout.order??0)||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.layout.label.localeCompare(n.layout.label))}function wA({registry:e,onSelect:t}){const n=bA(e);return n.length===0?null:o.jsxs("div",{role:"group","aria-label":"Layouts plugins",children:[o.jsx("p",{className:"px-3 pt-2 text-[0.65rem] font-semibold uppercase tracking-wide text-faint",children:"Layouts plugins"}),n.map(r=>o.jsxs("button",{type:"button",role:"menuitem","aria-label":`create ${r.layout.label} layout`,onClick:()=>t(r),className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm text-content hover:bg-raised",children:[o.jsx("span",{children:r.layout.label}),o.jsx("span",{className:"text-xs text-faint",children:r.pluginDisplayName})]},`${r.pluginId}:${r.layout.type}`))]})}function fx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function SA(e){const{template:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(!1),[l,a]=g.useState(null),c=g.useCallback(async()=>{i(!0),a(null);try{const d=await t.detectDrift(e);r(d)}catch(d){a(fx(d))}finally{i(!1)}},[t,e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async(d,f)=>{i(!0),a(null);try{await t.syncAgent(e,d),f&&await f();const p=await t.detectDrift(e);r(p)}catch(p){a(fx(p))}finally{i(!1)}},[t,e]);return{driftByAgentId:new Map(n.map(d=>[d.agentId,d])),driftBusy:s,driftError:l,refreshDrift:c,syncAgent:u}}function Bn(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function kA(e){const{agent:t,profile:n,system:r,terminal:s,input:i}=fe(),[l,a]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState([]),[w,v]=g.useState(null),[_,y]=g.useState(!1),[b,C]=g.useState(null),[S,N]=g.useState({}),[L,A]=g.useState({}),[k,D]=g.useState({}),[R,E]=g.useState({}),O=g.useCallback(async()=>{y(!0),v(null);try{const[ee,Q]=await Promise.all([t.listAgents(e),n.listProfiles()]);a(ee),p(Q)}catch(ee){v(Bn(ee))}finally{y(!1)}},[t,n,e]),I=g.useCallback(async()=>{try{x(await t.listLiveAgents(e))}catch{x([])}},[t,e]);g.useEffect(()=>{O()},[O]),g.useEffect(()=>{I()},[I]),g.useEffect(()=>{if(!r)return;let ee,Q=!1;return r.onDomainEvent(V=>{if((V.type==="agentLaunched"||V.type==="agentExited"||V.type==="agentProfileChanged")&&(O(),I()),V.type==="agentLaunched"&&E(Y=>{if(!(V.agentId in Y))return Y;const{[V.agentId]:oe,...pe}=Y;return pe}),V.type==="orchestratorRequestProcessed"&&V.source!==void 0){const{requesterId:Y,source:oe}=V;N(pe=>pe[Y]===oe?pe:{...pe,[Y]:oe})}switch(V.type){case"agentRateLimited":A(Y=>({...Y,[V.agentId]:{limitedUntil:V.resetsAtMs,resumeFireAt:Y[V.agentId]?.resumeFireAt,suspected:!1}}));break;case"agentResumeScheduled":A(Y=>({...Y,[V.agentId]:{...Y[V.agentId],resumeFireAt:V.fireAtMs}}));break;case"agentResumeCancelled":A(Y=>{const oe=Y[V.agentId];if(!oe)return Y;const{resumeFireAt:pe,...Pe}=oe;return{...Y,[V.agentId]:Pe}});break;case"agentResumed":A(Y=>{if(!(V.agentId in Y))return Y;const{[V.agentId]:oe,...pe}=Y;return pe});break;case"agentRateLimitSuspected":A(Y=>({...Y,[V.agentId]:{...Y[V.agentId],limitedUntil:V.resetsAtMs,suspected:!0}}));break;case"modelServerStatusChanged":D(Y=>({...Y,[V.serverId]:V.status}));break;case"agentLaunchFailed":E(Y=>({...Y,[V.agentId]:{cause:V.cause,code:V.code,message:V.message}}));break}}).then(V=>{Q?V():ee=V}),()=>{Q=!0,ee?.()}},[r,O,I]);const W=g.useCallback(async(ee,Q,V)=>{y(!0),v(null);try{const Y=await t.createAgent(e,{name:ee,profileId:Q,initialContent:V});a(oe=>[...oe,Y])}catch(Y){v(Bn(Y))}finally{y(!1)}},[t,e]),G=g.useCallback(async ee=>{y(!0),v(null);try{const Q=await t.readContext(e,ee);u(ee),d(Q)}catch(Q){v(Bn(Q))}finally{y(!1)}},[t,e]),P=g.useCallback(async ee=>{if(c){y(!0),v(null);try{await t.updateContext(e,c,ee),d(ee)}catch(Q){v(Bn(Q))}finally{y(!1)}}},[t,e,c]),z=g.useCallback(async(ee,Q,V,Y)=>{y(!0),v(null);try{const{agent:oe,relaunchedSession:pe}=await t.changeAgentProfile(e,ee,Q,V,Y);return a(Pe=>Pe.map($=>$.id===oe.id?oe:$)),I(),pe}catch(oe){v(Bn(oe));return}finally{y(!1)}},[t,e,I]),j=g.useCallback(async ee=>{y(!0),v(null);try{await t.deleteAgent(e,ee),a(Q=>Q.filter(V=>V.id!==ee)),u(Q=>Q===ee?null:Q),c===ee&&d(""),C(Q=>Q===ee?null:Q)}catch(Q){v(Bn(Q))}finally{y(!1)}},[t,e,c]),se=g.useCallback(async(ee,Q,V)=>{v(null);try{const Y=await t.launchAgent(e,ee,Q,V);return C(ee),I(),Y}catch(Y){throw v(Bn(Y)),Y}},[t,e,I]),q=g.useCallback(async ee=>{const Q=ee??b,V=Q?m.find(Y=>Y.agentId===Q):null;if(C(Y=>Y===Q||!Q?null:Y),V?.sessionId)try{await s?.closeTerminal(V.sessionId),x(Y=>Y.filter(oe=>oe.agentId!==Q))}catch(Y){v(Bn(Y)),await I()}},[m,I,b,s]),T=g.useCallback(async ee=>{A(Q=>{const V=Q[ee];if(!V?.resumeFireAt)return Q;const{resumeFireAt:Y,...oe}=V;return{...Q,[ee]:oe}});try{return await i?.cancelResume(ee)??!1}catch(Q){return v(Bn(Q)),!1}},[i]),re=g.useCallback(async(ee,Q)=>{try{await i?.setResumeAt(ee,Q)}catch(V){v(Bn(V))}},[i]);return{agents:l,selectedAgentId:c,context:h,profiles:f,liveAgents:m,delegationSourceByRequester:S,limitByAgent:L,modelServerStatusByServer:k,launchFailureByAgent:R,error:w,busy:_,runningAgentId:b,refresh:O,refreshLiveAgents:I,createAgent:W,selectAgent:G,saveContext:P,changeAgentProfile:z,deleteAgent:j,launchAgent:se,stopAgent:q,cancelResume:T,setResumeAt:re}}function vw(e,t,n){if(!e)return;const r=t.find(s=>s.id===e.profileId)?.opencode?.localModelServerId;return r?n[r]:void 0}function CA(e){if(!e)return null;switch(e.state){case"downloading":return"Téléchargement du modèle…";case"starting":case"probing":return"Chargement du serveur…";default:return null}}function Eu(e){if(!Number.isFinite(e)||e<=0)return"0 o";const t=["o","Ko","Mo","Go","To"];let n=e,r=0;for(;n>=1e3&&r{t&&t.listProfiles().then(s).catch(()=>{})},[t]);return g.useEffect(()=>{a()},[a]),g.useEffect(()=>{if(!n)return;let u,h=!1;return n.onDomainEvent(d=>{d.type==="modelServerStatusChanged"?l(f=>({...f,[d.serverId]:d.status})):d.type==="agentProfileChanged"&&a()}).then(d=>{h?d():u=d}),()=>{h=!0,u?.()}},[n,a]),{statusForAgent:g.useCallback(u=>vw(u,r,i),[r,i])}}function EA(e,t){const n=/^(\d{1,2}):(\d{2})$/.exec(e.trim());if(!n)return null;const r=Number(n[1]),s=Number(n[2]);if(r>23||s>59)return null;const i=new Date(t);return i.setHours(r,s,0,0),i.getTime()}function PA(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function AA(e){const t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function TA({state:e,onCancelResume:t,onSetResumeAt:n,busy:r=!1}){const{limitedUntil:s,resumeFireAt:i,suspected:l}=e,[a,c]=g.useState(()=>Date.now());g.useEffect(()=>{if(i===void 0)return;const m=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(m)},[i]);const[u,h]=g.useState(""),d=l===!0&&s===void 0&&i===void 0;function f(m){m.preventDefault();const x=EA(u,Date.now());x!==null&&(n(x),h(""))}const p=s!==void 0?`limité jusqu'à ${PA(s)}`:"limité";return o.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[o.jsx("span",{"aria-label":"session limit",title:l?"Limite de session détectée sans heure fiable":"Limite de session atteinte",className:U("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:p}),d&&o.jsxs("form",{onSubmit:f,className:"flex items-center gap-2","aria-label":"resume time form",children:[o.jsx("span",{className:"text-xs text-muted",role:"note",children:"heure inconnue"}),o.jsx(ce,{type:"time","aria-label":"resume time",value:u,disabled:r,onChange:m=>h(m.target.value),className:"h-8 w-28 text-xs"}),o.jsx(M,{type:"submit",size:"sm",variant:"primary","aria-label":"schedule resume",disabled:r||u.trim()==="",children:"Programmer la reprise"})]}),i!==void 0&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsxs("span",{"aria-label":"resume countdown",className:"text-xs text-muted",children:["reprise dans ",AA(i-a)]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel resume",disabled:r,onClick:t,children:"Annuler la reprise"})]})]})}function LA(e){switch(e.state){case"notConfigured":return null;case"probing":return{label:"vérification du serveur…",tone:"bg-muted/20 text-muted",role:"status"};case"starting":return{label:"démarrage du serveur…",tone:"bg-warning/20 text-warning",role:"status"};case"downloading":return{label:"téléchargement du modèle…",tone:"bg-warning/20 text-warning",role:"status"};case"ready":return e.reused?{label:"serveur prêt (réutilisé)",tone:"bg-success/20 text-success"}:{label:"serveur prêt",tone:"bg-success/20 text-success"};case"failed":return null}}function DA({status:e,failure:t}){const[n,r]=g.useState(!1),s=t||(e?.state==="failed"?{code:e.code,message:e.message}:null);if(s)return o.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[o.jsxs("span",{role:"alert","aria-label":"model server launch failed",className:U("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:["Échec du lancement : ",s.message]}),o.jsx("button",{type:"button","aria-label":"toggle launch failure detail",onClick:()=>r(l=>!l),className:"text-xs text-muted underline hover:text-content",children:"Détails"}),n&&o.jsxs("span",{"aria-label":"launch failure detail",className:"text-xs text-faint",children:["code ",s.code,s.cause?` · cause ${s.cause}`:""]})]});if(!e)return null;const i=LA(e);return i?o.jsx("span",{role:i.role,"aria-label":"model server status",className:U("rounded-full px-2 py-0.5 text-xs font-medium",i.tone),children:i.label}):null}function _w({projectId:e,projectRoot:t=""}){const n=kA(e),r=SA(e),s=fe(),i=s.template??null,l=s.permission??null,[a,c]=g.useState(""),[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState([]),[x,w]=g.useState(!1);!x&&i&&(w(!0),i.listTemplates().then(m).catch(()=>{}));const v=s.skill??null,[_,y]=g.useState([]),[b,C]=g.useState(!1),[S,N]=g.useState("");async function L(){if(v)try{const[$,B]=await Promise.all([v.listSkills(e,"global"),v.listSkills(e,"project")]);y([...B,...$])}catch{}}!b&&v&&(C(!0),L());async function A(){if(!v||!n.selectedAgentId||!S)return;const $=_.find(B=>B.id===S);$&&(await v.assignSkill(e,n.selectedAgentId,$.id,$.scope),N(""),await n.refresh())}async function k($){!v||!n.selectedAgentId||(await v.unassignSkill(e,n.selectedAgentId,$),await n.refresh())}const[D,R]=g.useState(n.context),[E,O]=g.useState(n.context);n.context!==E&&(O(n.context),R(n.context));const[I,W]=g.useState(null),[G,P]=g.useState({}),[z,j]=g.useState({}),[se,q]=g.useState({});g.useEffect(()=>{if(!l||n.agents.length===0){q({});return}let $=!1;return Promise.all(n.agents.map(async B=>{try{return[B.id,await l.resolveAgentSystemPermissions(e,B.id)]}catch{return[B.id,null]}})).then(B=>{$||q(Object.fromEntries(B.filter(he=>he[1]!==null)))}),()=>{$=!0}},[l,e,n.agents]);const[T,re]=g.useState(null);async function ee(){if(!T)return;const{agentId:$,profileId:B}=T;re(null);const he=await n.changeAgentProfile($,B,24,80);he&&$===I&&j(ue=>({...ue,[$]:he.sessionId}))}const Q=a.trim().length>0&&!n.busy;async function V($){if($.preventDefault(),!!Q){if(d&&i)await i.createAgentFromTemplate(e,d,{name:a.trim(),synchronized:!0}),await n.refresh();else{const B=u.trim()||"";await n.createAgent(a.trim(),B)}c(""),h(""),f("")}}function Y($){P(B=>({...B,[$]:B[$]??crypto.randomUUID()})),W($)}function oe($){n.stopAgent($),W(null)}const pe=n.agents.find($=>$.id===n.selectedAgentId)??null,Pe=d!=="";return o.jsxs(ke,{title:"Agents",className:"flex flex-col gap-0",children:[n.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),o.jsxs("form",{onSubmit:$=>void V($),className:"flex flex-col gap-3 border-b border-border p-4",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"agent-name-input",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"agent-name-input","aria-label":"agent name",placeholder:"My agent",value:a,onChange:$=>c($.target.value),className:"w-full"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"agent-template-select",className:"text-xs font-medium text-muted",children:"Template"}),o.jsxs("select",{id:"agent-template-select","aria-label":"agent template",value:d,onChange:$=>f($.target.value),className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:n.busy,children:[o.jsx("option",{value:"",children:"(none / from scratch)"}),p.map($=>o.jsx("option",{value:$.id,children:$.name},$.id))]})]}),!Pe&&o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("label",{htmlFor:"agent-profile-select",className:"text-xs font-medium text-muted",children:["Profile",n.profiles.length===0&&o.jsx("span",{className:"ml-1 text-faint",children:"(no profiles configured — you can still enter an id)"})]}),n.profiles.length>0?o.jsxs("select",{id:"agent-profile-select","aria-label":"agent profile",value:u,onChange:$=>h($.target.value),className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— select profile —"}),n.profiles.map($=>o.jsx("option",{value:$.id,children:$.name},$.id))]}):o.jsx(ce,{id:"agent-profile-select","aria-label":"agent profile",placeholder:"profile-id (optional)",value:u,onChange:$=>h($.target.value),className:"min-w-32"})]}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"create agent",disabled:!Q,loading:n.busy,className:"self-end",children:"Create"})]}),o.jsx("div",{className:"p-4",children:n.agents.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.agents.map($=>{const B=$.id===n.selectedAgentId,he=$.id===I,ue=n.liveAgents.find(_e=>_e.agentId===$.id),Ee=n.profiles.find(_e=>_e.id===$.profileId)?.name??$.profileId,dt=r.driftByAgentId.get($.id),Rn=n.delegationSourceByRequester[$.id],Yr=n.limitByAgent[$.id],Ps=vw($,n.profiles,n.modelServerStatusByServer),le=n.launchFailureByAgent[$.id],ge=se[$.id]??null;return o.jsxs("li",{className:U("flex flex-col gap-2 py-3 first:pt-0 last:pb-0",B&&"rounded-md bg-raised px-2"),children:[o.jsxs("button",{type:"button",onClick:()=>void n.selectAgent($.id),className:"flex min-w-0 flex-col items-start gap-0.5 text-left","aria-pressed":B,children:[o.jsxs("span",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:[o.jsx("span",{className:"font-medium text-content",children:$.name}),dt&&o.jsx("span",{"aria-label":"update available",className:"rounded-full bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary",children:"update available"}),Rn&&o.jsx("span",{"aria-label":`delegation source ${Rn}`,title:Rn==="mcp"?"Last delegation arrived via the MCP server":"Last delegation arrived via .ideai/requests",className:"rounded-full bg-raised px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-muted",children:Rn}),ge&&o.jsx(RA,{state:ge})]}),o.jsx("span",{className:"text-xs text-muted",children:Ee}),ue&&o.jsxs("span",{className:"block w-full min-w-0 truncate text-xs text-primary",children:["running in IdeA · ",ue.sessionId??ue.nodeId]})]}),Yr&&o.jsx(TA,{state:Yr,busy:n.busy,onCancelResume:()=>void n.cancelResume($.id),onSetResumeAt:_e=>void n.setResumeAt($.id,_e)}),o.jsx(DA,{status:Ps,failure:le}),o.jsx(QP,{requester:$.id}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.profiles.length>0&&o.jsxs("select",{"aria-label":`profile for ${$.name}`,value:$.profileId,disabled:n.busy,onChange:_e=>{const St=_e.target.value;St&&St!==$.profileId&&re({agentId:$.id,profileId:St})},className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[n.profiles.every(_e=>_e.id!==$.profileId)&&o.jsx("option",{value:$.profileId,children:$.profileId}),n.profiles.map(_e=>o.jsx("option",{value:_e.id,children:_e.name},_e.id))]}),dt&&o.jsx(M,{size:"sm",variant:"primary","aria-label":`sync ${$.name}`,disabled:n.busy||r.driftBusy,onClick:()=>void r.syncAgent($.id,n.refresh),children:"Sync"}),he||ue?o.jsx(M,{size:"sm",variant:"ghost","aria-label":`stop ${$.name}`,onClick:()=>oe($.id),className:"text-danger hover:text-danger",children:"Stop"}):o.jsx(M,{size:"sm",variant:"primary","aria-label":`launch ${$.name}`,disabled:n.busy||I!==null,onClick:()=>Y($.id),children:"Launch"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete ${$.name}`,disabled:n.busy,onClick:()=>void n.deleteAgent($.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},$.id)})})}),I!==null&&o.jsx("div",{className:"border-t border-border p-4",children:o.jsx("div",{className:"h-96 overflow-hidden rounded-lg border border-border bg-surface",children:o.jsx(hp,{cwd:t,open:($,B)=>n.launchAgent(I,{...$,nodeId:G[I]},B),reattach:($,B)=>s.agent.reattach($,B),sessionId:z[I]??null,onSessionId:$=>j(B=>({...B,[I]:$})),systemPermissions:se[I]??null},I)})}),pe&&v&&o.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Skills — ",pe.name]}),pe.skills.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No skills assigned."}):o.jsx("ul",{className:"flex flex-wrap gap-1.5",children:pe.skills.map($=>{const B=_.find(he=>he.id===$.skillId)?.name??$.skillId;return o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[o.jsx("span",{children:B}),o.jsx("button",{type:"button","aria-label":`unassign ${B}`,disabled:n.busy,onClick:()=>void k($.skillId),className:"text-faint hover:text-danger",children:"✕"})]},$.skillId)})}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsxs("select",{"aria-label":"skill to assign",value:S,onChange:$=>N($.target.value),disabled:n.busy,className:U("h-9 min-w-0 flex-1 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— assign a skill —"}),_.filter($=>!pe.skills.some(B=>B.skillId===$.id)).map($=>o.jsxs("option",{value:$.id,children:[$.name," (",$.scope,")"]},$.id))]}),o.jsx(M,{variant:"primary","aria-label":"assign skill",disabled:n.busy||!S,onClick:()=>void A(),children:"Assign"})]})]}),pe&&o.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Context — ",pe.name]}),o.jsx("code",{className:"text-xs text-muted",children:pe.contextPath})]}),o.jsx("textarea",{"aria-label":"agent context",value:D,onChange:$=>R($.target.value),rows:10,className:U("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:n.busy}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.busy&&o.jsx(Me,{size:14}),o.jsx(M,{variant:"primary",disabled:n.busy,onClick:()=>void n.saveContext(D),children:"Save"})]})]}),T&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm profile change",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Changer le moteur IA"}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Changer le moteur abandonne l'historique de conversation (le contexte et la mémoire sont conservés). Continuer ?"}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.jsx(M,{variant:"ghost","aria-label":"cancel profile change",disabled:n.busy,onClick:()=>re(null),children:"Annuler"}),o.jsx(M,{variant:"primary","aria-label":"confirm profile change",loading:n.busy,disabled:n.busy,onClick:()=>void ee(),children:"Continuer"})]})]})})]})}function RA({state:e}){const t=e.runtimeLock.state==="locked",n=t?"Verrouillé":e.effective==="allow"?"Autorisé":e.effective==="deny"?"Interdit":"Demande";return o.jsxs("span",{"aria-label":`network ${n}`,title:t?e.runtimeLock.reason??"Réseau verrouillé par le runtime":`État effectif : ${n}`,className:U("rounded-full px-2 py-0.5 text-xs font-medium",t?"bg-warning/15 text-warning":e.effective==="allow"?"bg-success/15 text-success":e.effective==="deny"?"bg-danger/15 text-danger":"bg-primary/15 text-primary"),children:["Réseau: ",n]})}function Pu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function yw(e,t){const{layout:n,terminal:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState(0),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=g.useCallback(A=>{i(A),a(k=>k+1)},[]);g.useEffect(()=>{if(!e||!n){i(null);return}let A=!1;return d(!0),n.loadLayout(e,t).then(k=>{A||f(k)}).catch(k=>{A||u(Pu(k))}).finally(()=>{A||d(!1)}),()=>{A=!0}},[n,e,t,f]);const p=g.useCallback(async A=>{if(!(!e||!n)){d(!0),u(null);try{f(await n.mutateLayout(e,A,t))}catch(k){u(Pu(k))}finally{d(!1)}}},[n,e,t,f]),m=g.useCallback(async A=>{if(!(!e||!n||A.length===0)){d(!0),u(null);try{let k=null;for(const D of A)k=await n.mutateLayout(e,D,t);k&&f(k)}catch(k){u(Pu(k))}finally{d(!1)}}},[n,e,t,f]),x=g.useCallback((A,k)=>p(XE(A,k)),[p]),w=g.useCallback(async(A,k)=>{await p({type:"merge",container:A,keepIndex:k})},[p]),v=g.useCallback((A,k)=>p({type:"resize",container:A,weights:k}),[p]),_=g.useCallback((A,k)=>p({type:"move",from:A,to:k}),[p]),y=g.useCallback((A,k)=>p({type:"setSession",target:A,session:k}),[p]),b=g.useCallback(async(A,k)=>{const D=s?Ja(s).find(O=>O.id===A):void 0,R=D?.agent??null,E=D?.session??null;if(k!==R&&(await m([{type:"setCellAgent",target:A,agent:k},{type:"setSession",target:A,session:null},{type:"setCellConversation",target:A,conversationId:null}]),E&&!R&&r))try{await r.closeTerminal(E)}catch{}},[s,m,r]),C=g.useCallback(async(A,k,D)=>{const R=s?Ja(s).find(W=>W.id===A):void 0,E=R?.agent??null,O=R?.session??null,I=[];if(k!==E&&I.push({type:"setCellAgent",target:A,agent:k},{type:"setCellConversation",target:A,conversationId:null}),D!==O&&I.push({type:"setSession",target:A,session:D}),await m(I),O&&O!==D&&!E&&r)try{await r.closeTerminal(O)}catch{}},[s,m,r]),S=g.useCallback((A,k)=>p({type:"setCellConversation",target:A,conversationId:k}),[p]),N=g.useCallback((A,k)=>{i(D=>D&&GE(D,A,k)),a(D=>D+1)},[]),L=g.useCallback(A=>{i(k=>k&&YE(k,A)),a(k=>k+1)},[]);return{layout:s,layoutVersion:l,error:c,busy:h,split:x,merge:w,resize:v,move:_,setSession:y,setCellAgent:b,attachLiveAgentToCell:C,setCellConversation:S,setPluginLayoutState:N,replacePluginLayoutWithTerminal:L}}function MA(e,t,n){return e&&t&&!n}function IA({projectId:e,cwd:t,layoutId:n,onOpenConversation:r,onOpenPluginsSettings:s}){const i=yw(e,n),l=eo(e);return i.layout?o.jsxs("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%",position:"relative"},children:[i.error&&o.jsx("p",{role:"alert",style:{color:"crimson",margin:0},children:i.error}),o.jsx(xp,{node:i.layout.root,cwd:t,vm:i,parentSplit:null,projectId:e,workState:l.state,refreshWorkState:l.refresh,onOpenConversation:r,onOpenPluginsSettings:s})]}):o.jsx("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%"},children:i.error?o.jsx("p",{role:"alert",style:{color:"crimson"},children:i.error}):o.jsx("p",{children:"Loading layout…"})})}function xp({node:e,cwd:t,vm:n,parentSplit:r,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c}){switch(e.type){case"customPluginLayout":return o.jsx(yA,{projectId:s,cell:e.node,onStateChange:u=>n.setPluginLayoutState(e.node.id,u),onOpenPlugins:()=>c?.(),onChooseAnotherLayout:()=>n.replacePluginLayoutWithTerminal(e.node.id)});case"leaf":return o.jsx(BA,{id:e.node.id,session:e.node.session??null,agent:e.node.agent??null,conversationId:e.node.conversationId??null,agentWasRunning:e.node.agentWasRunning??!1,cwd:t,vm:n,parentSplit:r,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a});case"split":return o.jsx(zA,{split:e.node,cwd:t,vm:n,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c});case"grid":return o.jsx($A,{grid:e.node,cwd:t,vm:n,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c})}}function OA(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}const Vi={banner:3,veil:4,controls:5};function BA({id:e,session:t,agent:n,conversationId:r,agentWasRunning:s,cwd:i,vm:l,parentSplit:a,projectId:c,workState:u,refreshWorkState:h,onOpenConversation:d}){const f=a!==null&&a.siblings===2,p=a&&a.index===0?1:0,{agent:m,input:x,system:w}=fe(),{portal:v,overlay:_}=yP(c,n??null),[y,b]=g.useState([]);g.useEffect(()=>{if(!m)return;let le=!1;return m.listAgents(c).then(ge=>{le||b(ge)}).catch(()=>{}),()=>{le=!0}},[m,c]);const[C,S]=g.useState([]),N=()=>{m?.listLiveAgents&&m.listLiveAgents(c).then(S).catch(()=>{})};g.useEffect(()=>{if(!m?.listLiveAgents)return;let le=!1;return m.listLiveAgents(c).then(ge=>{le||S(ge)}).catch(()=>{}),()=>{le=!0}},[m,c]),g.useEffect(()=>{if(!w)return;let le,ge=!1;return w.onDomainEvent(_e=>{(_e.type==="agentLaunched"||_e.type==="agentExited")&&N()}).then(_e=>{ge?_e():le=_e}),()=>{ge=!0,le?.()}},[w,m,c]);const L=n??null,{active:A}=mw(L??""),{statusForAgent:k}=NA(),D=L?y.find(le=>le.id===L):void 0,R=k(D),E=CA(R),O=jA(R),I=L?u?.agents.find(le=>le.agentId===L):void 0,W=I?.tickets.find(le=>le.status==="inProgress"),G=I?.tickets.filter(le=>le.status==="queued")??[],P=Math.max(I?.inboxDepth??0,I?.inbox?.length??0,G.length),z=I?.backgroundTasks?.filter(le=>le.status==="completed"||le.status==="failed"||le.status==="cancelled")??[],j=I?.busy.state==="busy"||!!W,se=W?.source.kind==="agent"?W:void 0,q=W?.conversationId??r??null;async function T(){if(!(!L||!x))try{await x.interrupt(c,L),await h()}catch(le){oe({message:px(le)})}}const re=le=>C.find(ge=>ge.agentId===le),ee=async(le,ge)=>{const _e=px(le);if(!mx(le))return{message:_e};const Dt=(m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C).find(H=>H.agentId===ge);return{message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:Dt&&Dt.nodeId!==e?Dt.nodeId:void 0}},Q=le=>{if(!l.layout)return;const ge=Ja(l.layout).find(_e=>_e.id!==e&&(_e.agent??null)===le);return ge?{nodeId:ge.id}:void 0},V=le=>{const ge=re(le);if(!(!ge||ge.kind!=="pty"||ge.nodeId===e))return Q(le)?void 0:ge},[Y,oe]=g.useState(null),[pe,Pe]=g.useState(null),[$,B]=g.useState(null),[he,ue]=g.useState(0);g.useEffect(()=>{if(!L||!m?.attachLiveAgent||pe)return;const le=V(L);if(!le?.sessionId||le.sessionId===t)return;let ge=!1;return(async()=>{const _e=await m.attachLiveAgent(c,L,e);ge||(await l.attachLiveAgentToCell(e,L,_e.sessionId??le.sessionId),ge||ue(St=>St+1))})().catch(()=>{}),()=>{ge=!0}},[C,L,t]);const Ee=async(le,ge,_e)=>{const St=V(L);if(St?.sessionId&&m.attachLiveAgent){const te=(await m.attachLiveAgent(c,L,e)).sessionId??St.sessionId;l.setSession(e,te);const xe=await m.reattach(te,ge);return N(),xe.handle}const Dt=await m.launchAgent(c,L,{...le,conversationId:_e,nodeId:e},ge).catch(async H=>{throw mx(H)&&oe(await ee(H,L)),H});return Dt.assignedConversationId&&l.setCellConversation(e,Dt.assignedConversationId),Dt},dt=m&&L?(le,ge)=>r?(Promise.resolve(m.inspectConversation?.(c,L,r)).then(_e=>B(_e??{})).catch(()=>B({})),new Promise((_e,St)=>{Pe({opts:le,onData:ge,resolve:_e,reject:St})})):Ee(le,ge,void 0):void 0,Rn=()=>{const le=pe;le&&(Pe(null),B(null),Ee(le.opts,le.onData,r??void 0).then(le.resolve,le.reject))},Yr=()=>{const le=pe;le&&(Pe(null),B(null),l.setCellConversation(e,null),Ee(le.opts,le.onData,void 0).then(le.resolve,le.reject))},Ps=m&&L?(le,ge)=>m.reattach(le,ge):void 0;return o.jsxs("div",{"data-testid":"layout-leaf","data-node-id":e,style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0,border:"1px solid #2a2a2a",boxSizing:"border-box",overflow:"hidden"},children:[o.jsxs("div",{style:{position:"absolute",top:2,right:16,zIndex:Vi.controls,display:"flex",gap:2,alignItems:"center"},children:[o.jsxs("select",{"aria-label":`agent selector ${e}`,value:L??"",onChange:le=>{const ge=le.target.value;if(ge===""){oe(null),l.setCellAgent(e,null);return}(async()=>{const _e=m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C;S(_e);const St=Q(ge);if(St){oe({message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:St.nodeId});return}const Dt=_e.find(te=>te.agentId===ge);if(Dt&&Dt.kind==="pty"&&Dt.nodeId!==e){if(!m?.attachLiveAgent||!Dt.sessionId){oe({message:"Session active introuvable pour cet agent."});return}oe(null);const te=await m.attachLiveAgent(c,ge,e);await l.attachLiveAgentToCell(e,ge,te.sessionId??Dt.sessionId),N();return}oe(null),await l.setCellAgent(e,ge)})().catch(async _e=>oe(await ee(_e,ge)))},style:{fontSize:11,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,padding:"1px 2px",maxWidth:100},children:[o.jsx("option",{value:"",children:"Plain"}),y.map(le=>{const ge=Q(le.id),_e=V(le.id);return o.jsxs("option",{value:le.id,disabled:!!ge,children:[le.name,ge?" (visible ailleurs)":_e?" (arrière-plan)":""]},le.id)})]}),o.jsx("button",{type:"button",title:"Split into columns","aria-label":`split ${e} columns`,onClick:()=>void l.split(e,"row"),children:"⬌"}),o.jsx("button",{type:"button",title:"Split into rows","aria-label":`split ${e} rows`,onClick:()=>void l.split(e,"column"),children:"⬍"}),f&&o.jsx("button",{type:"button",title:"Close this terminal","aria-label":`close ${e}`,onClick:()=>void l.merge(a.container,p),children:"✕"})]}),L&&(j||P>0||z.length>0||q)&&o.jsxs("div",{role:"status","aria-live":"polite",style:{position:"absolute",top:30,left:4,zIndex:Vi.banner,display:"flex",maxWidth:"calc(100% - 8px)",alignItems:"center",gap:4,overflow:"hidden"},children:[j&&o.jsx("span",{title:se?.requesterLabel??W?.taskPreview,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-warning, #d49b3a)",borderRadius:3,background:"rgba(212, 155, 58, 0.16)",color:"var(--color-warning, #d49b3a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:se?`Busy · ${se.requesterLabel}`:"Busy"}),!j&&P>0&&o.jsxs("span",{title:`${P} pending message${P===1?"":"s"}`,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued · ",P]}),j&&P>0&&o.jsxs("span",{title:`${P} queued message${P===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued ",P]}),z.length>0&&o.jsxs("span",{title:`${z.length} background task result${z.length===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-success, #57b36a)",borderRadius:3,background:"rgba(87, 179, 106, 0.14)",color:"var(--color-success, #57b36a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Task done ",z.length]}),j&&o.jsx("button",{type:"button","aria-label":`cancel current turn ${e}`,title:"Cancel current turn",onClick:()=>void T(),disabled:!x,style:{flexShrink:0,border:"1px solid var(--color-danger, #d45a5a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-danger, #d45a5a)",cursor:x?"pointer":"default",fontSize:11,padding:"1px 6px"},children:"Cancel"}),q&&d&&o.jsx("button",{type:"button","aria-label":`open cell conversation ${e}`,title:"Open conversation history",onClick:()=>d(q),style:{flexShrink:0,border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",cursor:"pointer",fontSize:11,padding:"1px 6px"},children:"History"})]}),o.jsxs("div",{style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0},children:[o.jsx(hp,{cwd:i,open:dt,reattach:Ps,sessionId:t,onSessionId:le=>void l.setSession(e,le),agentMode:L!=null,portal:L!=null?v:void 0,refitSignal:l.layoutVersion},`${e}-${L??"plain"}-${he}`),!E&&MA(L!=null,!!_,A)&&o.jsx("div",{"data-testid":"write-portal-overlay",role:"status","aria-live":"polite",style:{position:"absolute",inset:0,zIndex:Vi.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.45)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:o.jsx("span",{style:{background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"6px 12px"},children:"Un agent est en train de parler…"})}),!E&&L!=null&&o.jsx(XP,{projectId:c,agentId:L}),E&&o.jsx("div",{"data-testid":"model-server-overlay",role:"status","aria-live":"polite","aria-label":"model server launch",style:{position:"absolute",inset:0,zIndex:Vi.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0,maxWidth:"80%",background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"8px 14px"},children:[o.jsx("span",{children:E}),O&&o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"model-server-progress",role:"progressbar","aria-label":"progression du téléchargement","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":O.percent!=null?Math.round(O.percent):void 0,style:{position:"relative",width:220,maxWidth:"100%",height:6,borderRadius:3,overflow:"hidden",background:"var(--color-raised, #2a2a2a)"},children:o.jsx("div",{style:O.percent!=null?{height:"100%",width:`${O.percent}%`,background:"var(--color-primary, #5b9bd5)",transition:"width 120ms linear"}:{position:"absolute",top:0,bottom:0,width:"40%",background:"var(--color-primary, #5b9bd5)",animation:"model-server-indeterminate 1.1s ease-in-out infinite"}})}),(O.percent!=null||O.bytesLabel)&&o.jsxs("span",{"data-testid":"model-server-progress-label",style:{fontSize:12,color:"var(--color-content-muted, #9a9a9a)"},children:[O.percent!=null?`${Math.round(O.percent)} %`:"",O.percent!=null&&O.bytesLabel?" · ":"",O.bytesLabel??""]}),O.source&&o.jsx("span",{"data-testid":"model-server-source",style:{fontSize:11,color:"var(--color-content-muted, #9a9a9a)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:O.source,children:O.source})]})]})})]}),Y&&o.jsxs("div",{role:"status",style:{position:"absolute",bottom:4,left:4,right:4,margin:0,fontSize:11,color:"var(--color-content-muted, #9a9a9a)",background:"var(--color-surface, #1e1e1e)",padding:"2px 6px",borderRadius:3,zIndex:Vi.banner,display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[o.jsx("span",{style:{minWidth:0},children:Y.message}),Y.goToNodeId&&o.jsx("button",{type:"button","aria-label":"aller à la cellule",onClick:()=>{OA(Y.goToNodeId),oe(null)},style:{flexShrink:0,fontSize:11,cursor:"pointer",background:"transparent",color:"var(--color-primary, #5b9bd5)",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,padding:"1px 6px"},children:"Aller à la cellule"})]}),pe&&o.jsx(pP,{agentWasRunning:s,details:$,onResume:Rn,onNewConversation:Yr})]})}function zA({split:e,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a}){const c=e.direction==="row",u=e.children.map(m=>m.weight),h=g.useRef(null),[d,f]=g.useState(null),p=Ih(d??u);return o.jsx("div",{ref:h,"data-testid":"layout-split","data-direction":e.direction,style:{display:"flex",flexDirection:c?"row":"column",width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.children.map((m,x)=>o.jsxs("div",{style:{display:"contents"},children:[o.jsx("div",{style:{flexBasis:`${p[x]}%`,flexGrow:0,flexShrink:0,minHeight:0,minWidth:0,overflow:"hidden"},children:o.jsx(xp,{node:m.node,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a,parentSplit:{container:e.id,index:x,siblings:e.children.length}})}),xf(Zg(u,x,w)),onDragEnd:w=>{const v=Zg(u,x,w);f(null),n.resize(e.id,v)}})]},bw(m.node,x)))})}function FA({isRow:e,container:t,onDragMove:n,onDragEnd:r}){const s=g.useRef(null);function i(u){if(s.current===null)return null;const h=t.current?.getBoundingClientRect(),d=h?e?h.width:h.height:0;return d<=0?null:(u-s.current)/d}function l(u){u.preventDefault(),u.currentTarget.setPointerCapture(u.pointerId),s.current=e?u.clientX:u.clientY}function a(u){if(s.current===null)return;const h=i(e?u.clientX:u.clientY);h!==null&&n(h)}function c(u){const h=i(e?u.clientX:u.clientY);s.current=null,h!==null&&r(h)}return o.jsx("div",{role:"separator","aria-orientation":e?"vertical":"horizontal",onPointerDown:l,onPointerMove:a,onPointerUp:c,style:{flex:"0 0 6px",cursor:e?"col-resize":"row-resize",background:"#3a3a3a",touchAction:"none"}})}function $A({grid:e,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a}){const c=Ih(e.colWeights).map(h=>`${h}fr`).join(" "),u=Ih(e.rowWeights).map(h=>`${h}fr`).join(" ");return o.jsx("div",{"data-testid":"layout-grid-container",style:{display:"grid",gridTemplateColumns:c,gridTemplateRows:u,width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.cells.map((h,d)=>o.jsx("div",{style:{gridColumn:`${h.col+1} / span ${h.colSpan}`,gridRow:`${h.row+1} / span ${h.rowSpan}`,minHeight:0,minWidth:0,overflow:"hidden"},children:o.jsx(xp,{node:h.node,cwd:t,vm:n,parentSplit:null,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a})},bw(h.node,d)))})}function bw(e,t){return e.node.id??String(t)}function px(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function mx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="AGENT_ALREADY_RUNNING"}function Is(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function gx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="NOT_FOUND"}function WA(e){const{layout:t,system:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{if(!(!e||!t))try{const{layouts:w,activeId:v}=await t.listLayouts(e);s(w),l(_=>_&&w.some(y=>y.id===_)?_:v)}catch(w){h(Is(w))}},[t,e]);g.useEffect(()=>{if(!e||!t){s([]),l(null);return}let w=!1;return c(!0),t.listLayouts(e).then(({layouts:v,activeId:_})=>{w||(s(v),l(_))}).catch(v=>{w||h(Is(v))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[t,e]),g.useEffect(()=>{if(!e||!n)return;let w=!1,v;return n.onDomainEvent(_=>{_.type==="layoutChanged"&&_.projectId===e&&d()}).then(_=>{w?_():v=_}),()=>{w=!0,v?.()}},[n,e,d]);const f=g.useCallback(async w=>{if(!(!e||!t)){c(!0),h(null);try{const v=await t.setActiveLayout(e,w);l(v?.activeId??w)}catch(v){h(Is(v))}finally{c(!1)}}},[t,e]),p=g.useCallback(async(w,v)=>{if(!e||!t)return null;c(!0),h(null);try{const{layoutId:_}=await t.createLayout(e,w,v),y=await t.listLayouts(e);return s(y.layouts),_}catch(_){return h(Is(_)),null}finally{c(!1)}},[t,e]),m=g.useCallback(async(w,v)=>{if(!(!e||!t)){c(!0),h(null);try{await t.renameLayout(e,w,v),s(_=>_.map(y=>y.id===w?{...y,name:v}:y))}catch(_){gx(_)?await d():h(Is(_))}finally{c(!1)}}},[t,e,d]),x=g.useCallback(async w=>{if(!(!e||!t)){if(r.length<=1){h("Cannot delete the last layout.");return}c(!0),h(null);try{const{activeId:v}=await t.deleteLayout(e,w);s(_=>_.filter(y=>y.id!==w)),l(v)}catch(v){gx(v)?await d():h(Is(v))}finally{c(!1)}}},[t,e,r.length,d]);return{layouts:r,activeId:i,busy:a,error:u,setActive:f,create:p,rename:m,deleteLayout:x}}function HA({projectId:e,onActiveLayoutChange:t}){const n=WA(e);g.useEffect(()=>{const _=n.layouts.find(y=>y.id===n.activeId);_&&t(_)},[n.activeId,n.layouts,t]);const[r,s]=g.useState(null),[i,l]=g.useState(""),a=g.useRef(null),[c,u]=g.useState(!1),{registry:h}=gp(),[d,f]=g.useState(null);async function p(_){await n.setActive(_)}async function m(_){n.layouts.length<=1||await n.deleteLayout(_)}function x(_,y){s(_),l(y),setTimeout(()=>a.current?.focus(),0)}async function w(){if(!r)return;const _=i.trim();_&&await n.rename(r,_),s(null),l("")}async function v(_){u(!1);const y=_==="gitGraph"?"Git Graph":"Layout",b=window.prompt("New layout name:",y);if(!b?.trim())return;const C=await n.create(b.trim(),_);C&&await n.setActive(C)}return n.layouts.length===0?null:o.jsxs("div",{"data-testid":"layout-tabs",className:"flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",children:[n.layouts.map(_=>{const y=_.id===n.activeId,b=_.id===r;return o.jsxs("div",{className:U("group flex items-center gap-1 rounded-md border px-1 transition-colors",y?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[b?o.jsx("input",{ref:a,value:i,onChange:C=>l(C.target.value),onBlur:()=>void w(),onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&(s(null),l(""))},"aria-label":`rename layout ${_.name}`,className:"w-24 rounded border border-border bg-base px-1 py-0.5 text-sm text-content focus:outline-none focus:ring-1 focus:ring-primary"}):o.jsxs("button",{type:"button",role:"tab","aria-selected":y,onClick:()=>void p(_.id),onDoubleClick:()=>x(_.id,_.name),className:U("flex items-center gap-1 px-2 py-1 text-sm focus-visible:outline-none",y?"font-semibold text-content":"text-muted hover:text-content"),children:[_.kind==="gitGraph"&&o.jsx("span",{"aria-label":"git graph layout",className:"text-xs text-primary",title:"Git Graph",children:"⎇"}),_.name]}),o.jsx("button",{type:"button","aria-label":`delete layout ${_.name}`,disabled:n.layouts.length<=1,onClick:()=>void m(_.id),className:U("flex h-4 w-4 items-center justify-center rounded text-xs transition-opacity",n.layouts.length<=1?"cursor-not-allowed opacity-20":"opacity-60 hover:opacity-100 group-hover:opacity-100"),children:"×"})]},_.id)}),o.jsxs("div",{className:"relative",children:[o.jsx("button",{type:"button","aria-label":"create layout",onClick:()=>u(_=>!_),className:"flex h-6 w-6 items-center justify-center rounded border border-transparent text-sm text-muted transition-colors hover:border-border hover:text-content",children:"+"}),c&&o.jsxs("div",{role:"menu",className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col rounded-md border border-border bg-surface shadow-lg",children:[o.jsx("button",{type:"button",role:"menuitem","aria-label":"create terminal layout",onClick:()=>void v("terminal"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"Terminal"}),o.jsx("button",{type:"button",role:"menuitem","aria-label":"create git graph layout",onClick:()=>void v("gitGraph"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"⎇ Git graph"}),o.jsx(wA,{registry:h,onSelect:_=>{u(!1),f(`« ${_.layout.label} » (${_.pluginDisplayName}) : la création de layouts plugins nécessite une extension backend pas encore livrée.`)}})]})]}),(n.error||d)&&o.jsx("span",{className:"ml-2 text-xs text-danger",role:"alert",children:n.error??d})]})}class UA extends g.Component{constructor(){super(...arguments);X(this,"state",{error:null,retryKey:0});X(this,"retry",()=>{this.setState(({retryKey:n})=>({error:null,retryKey:n+1}))})}static getDerivedStateFromError(n){return{error:n}}render(){return this.state.error?o.jsx(ke,{title:"Work",children:o.jsxs("div",{role:"alert",className:"rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[o.jsx("p",{className:"font-medium",children:"Work panel failed to render."}),o.jsx("p",{className:"mt-1 text-xs text-danger/80",children:this.state.error.message}),o.jsx(M,{size:"sm",variant:"ghost",className:"mt-2",onClick:this.retry,children:"Retry"})]})}):o.jsx("div",{children:this.props.children},this.state.retryKey)}}function cr(e){return e.length<=8?e:e.slice(0,8)}function qA(e){return e==="inProgress"?"In progress":"Queued"}function VA(e){switch(e){case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed";case"cancelled":return"Cancelled";case"delivered":return"Delivered";case"pending":return"Pending"}}function KA(e){return e==="completed"||e==="failed"||e==="cancelled"}function GA(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function YA(e){if(e.source.kind==="human")return"Human";const t=cr(e.source.agentId);return e.requesterLabel.trim()?`${e.requesterLabel} (${t})`:`Agent ${t}`}function XA(e){switch(e){case"ready":return"Summary";case"missing":return"No summary";case"partial":return"Partial";case"unavailable":return"Unavailable"}}function QA(e){if(e.objectivePreview)return`Goal: ${e.objectivePreview}`;if(e.summaryPreview)return e.summaryPreview;const t=(e.recentTurns??[]).at(-1);return t?`Last: ${t.textPreview}`:null}function xx(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}async function JA(e){if(typeof navigator<"u"&&navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}throw new Error("Clipboard unavailable")}function ZA({summary:e,onOpenConversation:t}){const n=QA(e),[r,s]=g.useState(!1),[i,l]=g.useState(!1);return n?o.jsxs("div",{className:"mt-1 min-w-0 pl-1 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="ready"?"bg-success/10 text-success":"bg-raised text-muted"),children:XA(e.status)}),t?o.jsx("button",{type:"button","aria-label":`open conversation ${e.conversationId}`,className:"min-w-0 flex-1 break-words text-left hover:text-content hover:underline",onClick:()=>t(e.conversationId),children:n}):o.jsx("span",{className:"min-w-0 flex-1 break-words",children:n}),o.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content",onClick:()=>s(a=>!a),children:r?"Hide":"View"}),o.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content disabled:opacity-50",disabled:!n,onClick:()=>{JA(n).then(()=>{l(!0),window.setTimeout(()=>l(!1),1e3)})},children:i?"Copied":"Copy"})]}),r&&o.jsxs("div",{"aria-label":`conversation ${e.conversationId} details`,className:"mt-1 space-y-1 border-l border-border pl-2",children:[e.objectivePreview&&o.jsxs("p",{children:[o.jsx("span",{className:"font-medium text-content",children:"Goal:"})," ",e.objectivePreview]}),e.summaryPreview&&o.jsxs("p",{children:[o.jsx("span",{className:"font-medium text-content",children:"Summary:"})," ",e.summaryPreview]}),(e.recentTurns??[]).length>0&&o.jsx("ul",{className:"space-y-0.5",children:(e.recentTurns??[]).map(a=>o.jsxs("li",{children:[o.jsxs("span",{className:"font-medium text-content",children:[a.role,":"]})," ",a.textPreview]},`${a.atMs}-${a.role}-${a.textPreview}`))})]})]}):null}function eT({ticket:e,summary:t,onOpenConversation:n}){const r=e.taskLen>e.taskPreview.length;return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsxs("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="inProgress"?"bg-warning/15 text-warning":"bg-raised text-muted"),children:["#",e.position+1," ",qA(e.status)]}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"font-medium text-content",children:YA(e)}),o.jsx("span",{className:"text-muted",children:" · "}),o.jsx("span",{className:"break-words",children:e.taskPreview}),r&&o.jsxs("span",{"aria-label":`${e.taskLen-e.taskPreview.length} more characters`,className:"text-muted",children:[" ","+",e.taskLen-e.taskPreview.length]})]}),o.jsx("code",{"aria-label":`ticket ${cr(e.ticketId)}`,title:e.ticketId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.ticketId)})]}),t&&o.jsx(ZA,{summary:t,onOpenConversation:n})]})}function tT({item:e}){return o.jsx("li",{className:"min-w-0 text-xs text-muted",children:o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium text-muted",children:e.kind}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:e.body}),o.jsx("code",{title:e.id,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.id)})]})})}function nT({task:e,onRefresh:t}){const{workState:n}=fe(),[r,s]=g.useState(!1),[i,l]=g.useState(!1),[a,c]=g.useState(null),u=!!(e.stdoutTail||e.stderrTail),h=e.status==="running"||e.status==="pending",d=e.status==="failed"||e.status==="cancelled";async function f(p){l(!0),c(null);try{await p(e.taskId),await t()}catch(m){c(m instanceof Error?m.message:String(m))}finally{l(!1)}}return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",GA(e.status)),children:VA(e.status)}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"font-medium text-content",children:e.kind}),e.exitCode!==null&&o.jsxs("span",{className:"text-muted",children:[" · exit ",e.exitCode]})]}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!h||i,loading:i,onClick:()=>void f(p=>n.cancelBackgroundTask(p)),children:"Cancel"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!u,onClick:()=>s(p=>!p),children:"Output"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!d||i,loading:i,onClick:()=>void f(p=>n.retryBackgroundTask(p)),children:"Retry"}),o.jsx("code",{title:e.taskId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.taskId)})]}),e.summary&&KA(e.status)&&o.jsx("p",{"aria-label":`task ${cr(e.taskId)} summary`,title:e.summary,className:"mt-1 truncate pl-1 text-[11px] text-muted",children:e.summary}),a&&o.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:a}),r&&u&&o.jsxs("pre",{"aria-label":`task ${cr(e.taskId)} output`,className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-canvas p-2 text-[11px] text-muted",children:[e.stdoutTail?`stdout -${e.stdoutTail}`:"",e.stdoutTail&&e.stderrTail?` - -`:"",e.stderrTail?`stderr -${e.stderrTail}`:""]})]})}function rT({agent:e,conversations:t,visibleLeaves:n,layout:r,projectId:s,onRefresh:i,onOpenConversation:l}){const{agent:a}=fe(),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=e.live!==void 0,p=e.busy??{state:"idle"},m=p.state==="busy",x=[...e.tickets??[]].sort((k,D)=>k.position-D.position),w=[...e.inbox??[]].sort((k,D)=>k.createdAtMs-D.createdAtMs),v=[...e.backgroundTasks??[]].sort((k,D)=>D.updatedAtMs-k.updatedAtMs||k.taskId.localeCompare(D.taskId)),_=Math.max(e.inboxDepth??0,w.length,x.length),y=new Set(n.map(k=>k.id)),b=f&&y.has(e.live.nodeId),C=n.find(k=>!k.session&&!k.agent),S=m||x.some(k=>k.status==="inProgress");async function N(){await i()}async function L(){if(!(!e.live||!C||!a?.attachLiveAgent)){d(!0),u(null);try{const k=await a.attachLiveAgent(s,e.agentId,C.id);await r.attachLiveAgentToCell(C.id,e.agentId,k.sessionId),await N(),xx(C.id)}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!1)}}}async function A(){if(!e.live||!a?.stopLiveAgent)return;const k=S?" The current turn will be interrupted.":"";if(window.confirm(`Stop ${e.name}?${k}`)){d(!0),u(null);try{const D=await a.stopLiveAgent(s,e.agentId);if(y.has(e.live.nodeId)){const R=n.find(E=>E.id===e.live?.nodeId);(!R?.session||R.session===D.sessionId)&&await r.setSession(e.live.nodeId,null)}await N()}catch(D){u(D instanceof Error?D.message:String(D))}finally{d(!1)}}}return o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),o.jsx("code",{className:"truncate text-xs text-muted",children:e.profileId})]}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx("span",{className:U("rounded-full px-2 py-0.5 text-xs font-medium",f?"bg-success/15 text-success":"bg-raised text-muted"),children:f?"Live":"Offline"}),o.jsx("span",{className:U("rounded-full px-2 py-0.5 text-xs font-medium",m?"bg-warning/15 text-warning":"bg-raised text-muted"),children:m?"Busy":"Idle"}),_>0&&o.jsxs("span",{"aria-label":`${e.name} queue depth ${_}`,className:"rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary",children:["Queue ",_]}),p.state==="busy"&&o.jsx("code",{"aria-label":`busy ticket ${cr(p.ticket)}`,title:p.ticket,className:"rounded bg-raised px-1.5 py-0.5 text-xs text-muted",children:cr(p.ticket)}),e.live&&b&&o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>xx(e.live.nodeId),children:"Open"}),e.live&&!b&&o.jsx(M,{size:"sm",variant:"ghost",disabled:!C||!a?.attachLiveAgent,loading:h,title:C?void 0:"No empty visible cell available",onClick:()=>void L(),children:"Attach"}),e.live&&o.jsx(M,{size:"sm",variant:"danger",loading:h,disabled:!a?.stopLiveAgent,onClick:()=>void A(),children:"Stop"})]})]}),e.live&&!b&&!C&&o.jsx("p",{className:"mt-1 text-xs text-muted",children:"No empty visible cell."}),c&&o.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:c}),x.length>0&&o.jsx("ul",{"aria-label":`${e.name} tickets`,className:"mt-2 flex flex-col gap-1",children:x.map(k=>o.jsx(eT,{ticket:k,summary:t.get(k.conversationId),onOpenConversation:l},k.ticketId))}),w.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),o.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:w.map(k=>o.jsx(tT,{item:k},k.id))})]}),v.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Background tasks"}),o.jsx("ul",{"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:v.map(k=>o.jsx(nT,{task:k,onRefresh:N},k.taskId))})]})]})}function sT({projectId:e,onOpenConversation:t}){const n=eo(e),r=yw(e),s=n.state?.agents??[],i=r.layout?Ja(r.layout):[],l=new Map((n.state?.conversations??[]).map(a=>[a.conversationId,a]));return o.jsxs(ke,{title:"Work",actions:o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),n.busy&&n.state===null?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading work state…"})]}):s.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agent work state."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:s.map(a=>o.jsx(rT,{agent:a,conversations:l,visibleLeaves:i,layout:r,projectId:e,onRefresh:n.refresh,onOpenConversation:t},a.agentId))})]})}function iT(e){return o.jsx(UA,{children:o.jsx(sT,{...e})})}function Au(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Tu(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function lT(e,t){const{conversation:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(!1),[a,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useRef([]),f=g.useRef(!1),p=g.useCallback(v=>{d.current=v,s(v)},[]),m=g.useCallback(async()=>{if(!f.current){f.current=!0,l(!0),c(null);try{const v=await n.readPage(e,t,{direction:"backward"});p(Tu(v.turns)),h(v.hasMore)}catch(v){c(Au(v))}finally{l(!1),f.current=!1}}},[n,e,t,p]),x=g.useCallback(async()=>{if(f.current)return;const v=d.current[0];if(!v){await m();return}f.current=!0,l(!0),c(null);try{const _=await n.readPage(e,t,{direction:"backward",anchor:v.id});_.turns.length>0&&p(Tu([..._.turns,...d.current])),h(_.hasMore)}catch(_){c(Au(_))}finally{l(!1),f.current=!1}},[n,e,t,m,p]),w=g.useCallback(async()=>{if(!f.current){if(d.current.length===0){await m();return}f.current=!0,l(!0),c(null);try{for(;;){const v=d.current.at(-1);if(!v)break;const _=await n.readPage(e,t,{direction:"forward",anchor:v.id});if(_.turns.length===0||(p(Tu([...d.current,..._.turns])),!_.hasMore))break}}catch(v){c(Au(v))}finally{l(!1),f.current=!1}}},[n,e,t,m,p]);return g.useEffect(()=>{p([]),h(!1),m()},[m,p]),{turns:r,busy:i,error:a,hasMore:u,loadOlder:x,refreshTail:w}}function vx(e){return e.length<=8?e:e.slice(0,8)}function Lu(e){return e.kind==="human"?"human":`agent:${e.agentId}`}function oT(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleString()}catch{return""}}function aT(e){switch(e){case"prompt":return"Prompt";case"response":return"Response";case"toolActivity":return"Tool"}}function cT({turn:e,sideClass:t}){const[n,r]=g.useState(!1);return o.jsx("div",{className:U("flex flex-col",t),children:o.jsxs("div",{className:"max-w-[80%] rounded-md border border-border bg-surface/60 px-3 py-1.5 text-xs text-muted",children:[o.jsxs("button",{type:"button",className:"flex items-center gap-1.5 font-medium hover:text-content",onClick:()=>r(s=>!s),"aria-expanded":n,children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),"Tool activity",o.jsxs("span",{className:"text-faint",children:["· ",e.textLen," chars"]})]}),n&&o.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted",children:e.text})]})})}function uT({projectId:e,conversationId:t,onClose:n}){const r=lT(e,t),s=eo(e),i=g.useMemo(()=>{const u=new Map;for(const h of s.state?.agents??[])h.name.trim()&&u.set(h.agentId,h.name.trim());return u},[s.state]),l=g.useMemo(()=>{const u=[],h=new Map;for(const d of r.turns){const f=Lu(d.source);if(h.has(f))continue;const p=u.length===0?"left":"right",m=d.source.kind==="human"?"User":i.get(d.source.agentId)??`Agent ${vx(d.source.agentId)}`;h.set(f,{label:m,side:p}),u.push(f)}return{order:u,meta:h}},[r.turns,i]),a=g.useMemo(()=>{const u=l.order.map(h=>l.meta.get(h)?.label??"?");return u.length>=2?`${u[0]} ↔ ${u[1]}`:u.length===1?u[0]:"Conversation"},[l]);function c(u){return l.meta.get(Lu(u))?.side??"left"}return o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border bg-surface px-4 py-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:a}),o.jsx("code",{className:"truncate text-xs text-muted",title:t,children:vx(t)})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.refreshTail(),loading:r.busy,children:"Refresh"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"← Retour aux terminaux"})]})]}),r.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),o.jsxs("div",{className:"flex flex-1 flex-col gap-2 overflow-auto px-4 py-3",children:[r.hasMore&&o.jsx("div",{className:"flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.loadOlder(),loading:r.busy,children:"Charger les tours précédents"})}),r.busy&&r.turns.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Chargement du fil…"})]}):r.turns.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun tour pour le moment."}):r.turns.map(u=>{const h=c(u.source),d=h==="right"?"items-end":"items-start";if(u.role==="toolActivity")return o.jsx(cT,{turn:u,sideClass:d},u.id);const f=l.meta.get(Lu(u.source)),p=oT(u.atMs);return o.jsx("div",{className:U("flex flex-col",d),children:o.jsxs("div",{className:U("max-w-[80%] rounded-lg border px-3 py-2 text-sm",h==="right"?"border-primary/20 bg-primary/10 text-content":"border-border bg-raised text-content"),children:[o.jsxs("div",{className:"mb-1 flex items-baseline gap-2 text-xs text-muted",children:[o.jsx("span",{className:"font-medium text-content",children:f?.label??"?"}),o.jsxs("span",{children:["· ",aT(u.role)]}),p&&o.jsxs("span",{className:"text-faint",children:["· ",p]})]}),o.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.text})]})},u.id)})]})]})}function Du(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function dT(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function hT(){const{modelServer:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{l(!0),s(null);try{n(await e.listModelServers())}catch(f){s(Du(f))}finally{l(!1)}},[e]);g.useEffect(()=>{a()},[a]);const c=g.useCallback(async f=>{l(!0),s(null);try{const p=await e.saveModelServer(f);return n(m=>{const x=m.findIndex(w=>w.id===p.id);if(x>=0){const w=m.slice();return w[x]=p,w}return[...m,p]}),p}catch(p){return s(Du(p)),null}finally{l(!1)}},[e]),u=g.useCallback(async f=>{l(!0),s(null);try{return await e.deleteModelServer(f),n(p=>p.filter(m=>m.id!==f)),!0}catch(p){return dT(p)==="model_server_in_use"?s("Ce serveur est encore utilisé par un profil : détache-le d'abord (choisis « aucun » ou un autre serveur) avant de le supprimer."):s(Du(p)),!1}finally{l(!1)}},[e]),h=g.useCallback(async f=>{try{return await e.previewModelServerCommand(f)}catch{return null}},[e]),d=g.useCallback(()=>s(null),[]);return{servers:t,error:r,busy:i,reload:a,save:c,remove:u,preview:h,clearError:d}}function fT(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function pT(e){return e.startsWith("/")||e.startsWith("\\")?!0:/^[a-zA-Z]:[/\\]/.test(e)}function mT(e){if(/\s/.test(e)||e.startsWith("http://")||e.startsWith("https://")||(e.match(/:/g)??[]).length>1)return!1;const[t,n]=e.includes(":")?[e.slice(0,e.indexOf(":")),e.slice(e.indexOf(":")+1)]:[e,void 0];if(n!==void 0&&n.length===0)return!1;const r=t.split("/");return r.length===2&&r[0].length>0&&r[1].length>0}function gT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),fT(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&(t.port="Port must be an integer between 1 and 65535."),e.servedModelName.trim().length===0&&(t.servedModelName="Le nom du modèle est requis."),(e.host.trim().length===0||/\s/.test(e.host))&&(t.host="L'adresse d'écoute est requise et ne doit pas contenir d'espace.");const n=e.modelSource;return n&&(n.type==="localPath"?n.path.trim().length===0?t.modelSource="Le chemin du fichier .gguf est requis.":pT(n.path.trim())||(t.modelSource="Le chemin du fichier doit être absolu."):n.repo.trim().length===0?t.modelSource="Le modèle Hugging Face est requis.":mT(n.repo.trim())||(t.modelSource="Format attendu : auteur/modèle ou auteur/modèle:quant (ex. unsloth/Qwen3.5-9B-GGUF:Q4_K_M).")),e.autoStart&&!n&&(t.modelSource="Le démarrage automatique nécessite une source de modèle."),t}function xT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`srv-${Math.random().toString(36).slice(2,10)}`}function vT(){return{id:xT(),kind:"llamaCpp",name:"",baseURL:"http://localhost:8080/v1",port:8080,servedModelName:"",host:"127.0.0.1",jinja:!1,args:[],autoStart:!1,stopPolicy:"stopOnAppExit"}}function _T(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function yT(e){if(!e)return"";if(e.type==="localPath"){const r=e.path.trim();return r.length===0?"":(r.split(/[/\\]/).pop()??"").replace(/\.gguf$/i,"")}const t=e.repo.trim();return t.length===0?"":(t.includes(":")?t.slice(0,t.indexOf(":")):t).split("/").pop()??""}const bT=["--model","-m","-hf","--port","--host","-ngl","--gpu-layers","-c","--ctx-size","--jinja"];function wT(e){const t=new Set(bT),n=new Set;for(const r of e){const s=r.includes("=")?r.slice(0,r.indexOf("=")):r;t.has(s)&&n.add(s)}return[...n]}function Et({children:e}){return o.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function Os({children:e}){return o.jsx("small",{className:"text-xs text-muted",children:e})}const ST=[{value:"stopOnAppExit",label:"Stop on app exit"},{value:"keepAlive",label:"Keep alive"},{value:"stopWhenUnused",label:"Stop when unused"}];function kT({vm:e}){const[t,n]=g.useState(null);function r(){e.clearError(),n(vT())}function s(l){e.clearError(),n({...l})}async function i(){if(!t)return;await e.save(t)&&n(null)}return o.jsx(ke,{"aria-label":"local model servers",title:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:"Local model servers"}),o.jsx(M,{size:"sm","aria-label":"add model server",onClick:r,className:"ml-auto",children:"Add server"})]}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[e.error&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error}),e.servers.length===0&&!t&&o.jsx("p",{className:"text-xs text-muted",children:"No local server declared yet. Add one to auto-manage a `llama-server`, or keep using an external endpoint."}),o.jsx("ul",{className:"flex list-none flex-col gap-2 p-0",children:e.servers.map(l=>o.jsxs("li",{className:"flex items-center gap-2 rounded-md border border-border bg-raised p-2",children:[o.jsxs("span",{className:"flex min-w-0 flex-col",children:[o.jsx("strong",{className:"truncate text-sm text-content",children:l.name}),o.jsxs("span",{className:"truncate text-xs text-muted",children:[l.baseURL," · ",l.servedModelName,l.autoStart?" · auto-start":""]})]}),o.jsxs("span",{className:"ml-auto flex items-center gap-1",children:[o.jsx(M,{size:"sm","aria-label":`edit ${l.name}`,onClick:()=>s(l),disabled:e.busy,children:"Edit"}),o.jsx(sr,{size:"sm","aria-label":`delete ${l.name}`,onClick:()=>void e.remove(l.id),disabled:e.busy,children:"×"})]})]},l.id))}),t&&o.jsx(NT,{draft:t,busy:e.busy,preview:e.preview,onChange:n,onCancel:()=>{e.clearError(),n(null)},onSubmit:()=>void i()})]})})}function CT({kind:e,onSelect:t}){const n=(r,s)=>{const i=e===r;return o.jsx("button",{type:"button","aria-pressed":i,onClick:()=>t(r),className:U("h-8 flex-1 rounded-md px-3 text-xs font-medium transition-colors",i?"bg-primary text-white":"bg-raised text-muted hover:text-content"),children:s})};return o.jsxs("div",{role:"group","aria-label":"source du modèle",className:"flex gap-1 rounded-md border border-border p-1",children:[n("huggingFace","Télécharger depuis Hugging Face"),n("localPath","Fichier .gguf local")]})}function jT({preview:e,autoStart:t}){const[n,r]=g.useState(!1),s=t?"Commande générée":"Commande à lancer manuellement";async function i(){if(e)try{await navigator.clipboard.writeText(e.display),r(!0),setTimeout(()=>r(!1),1500)}catch{}}return o.jsxs("section",{"aria-label":"command preview",className:"flex flex-col gap-1 rounded-md border border-border bg-raised p-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Et,{children:s}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"copier la commande",onClick:()=>void i(),disabled:!e,className:"ml-auto",children:n?"Copié":"Copier"})]}),e?o.jsx("code",{"aria-label":"preview command line",className:"whitespace-pre-wrap break-all font-mono text-xs text-content",children:e.display}):o.jsx("span",{className:"text-xs text-muted",children:"Renseigne une source de modèle pour voir la commande."})]})}function NT({draft:e,busy:t,preview:n,onChange:r,onCancel:s,onSubmit:i}){const l=gT(e),a=Object.keys(l).length===0,c=b=>r({...e,...b}),[u,h]=g.useState(e.modelSource?.type??"huggingFace"),d=e.modelSource?.type==="huggingFace"?e.modelSource.repo:"",f=e.modelSource?.type==="localPath"?e.modelSource.path:"";function p(b){const C={modelSource:b};if(e.servedModelName.trim().length===0){const S=yT(b);S.length>0&&(C.servedModelName=S)}c(C)}function m(b){b!==u&&(h(b),c({modelSource:void 0}))}const[x,w]=g.useState(null),v=JSON.stringify({modelSource:e.modelSource,port:e.port,host:e.host,gpuLayers:e.gpuLayers,contextSize:e.contextSize,jinja:e.jinja,binaryPath:e.binaryPath,args:e.args}),_=g.useRef(e);_.current=e,g.useEffect(()=>{if(!e.modelSource){w(null);return}let b=!1;const C=setTimeout(()=>{n(_.current).then(S=>{b||w(S)})},250);return()=>{b=!0,clearTimeout(C)}},[v,n]);const y=wT(e.args);return o.jsxs("fieldset",{"aria-label":"model server editor",className:"flex flex-col gap-3 rounded-md border border-primary/40 p-3",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:e.name.trim().length>0?e.name:"New server"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Nom"}),o.jsx(ce,{"aria-label":"server name",value:e.name,invalid:!!l.name,onChange:b=>c({name:b.target.value})}),l.name&&o.jsx("small",{className:"text-xs text-danger",children:l.name})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Source du modèle"}),o.jsx(CT,{kind:u,onSelect:m})]}),u==="huggingFace"?o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Modèle Hugging Face"}),o.jsx(ce,{"aria-label":"hugging face model",value:d,placeholder:"unsloth/Qwen3.5-9B-GGUF:Q4_K_M",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"huggingFace",repo:C})}}),o.jsx(Os,{children:"llama.cpp téléchargera/cache le fichier automatiquement."}),l.modelSource&&o.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}):o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Fichier .gguf"}),o.jsx(ce,{"aria-label":"local gguf file",value:f,placeholder:"/home/me/models/qwen.gguf",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"localPath",path:C})}}),o.jsx(Os,{children:"Chemin absolu vers un .gguf déjà présent."}),l.modelSource&&o.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Nom du modèle dans IdeA"}),o.jsx(ce,{"aria-label":"server served model name",value:e.servedModelName,placeholder:"qwen3-coder-30b",invalid:!!l.servedModelName,onChange:b=>c({servedModelName:b.target.value})}),o.jsx(Os,{children:"Nom envoyé aux clients OpenAI-compatible."}),l.servedModelName&&o.jsx("small",{className:"text-xs text-danger",children:l.servedModelName})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[12rem] flex-1 flex-col gap-1",children:[o.jsx(Et,{children:"Commande serveur"}),o.jsx(ce,{"aria-label":"server binary path",value:e.binaryPath??"",placeholder:"llama-server",onChange:b=>{const C=b.target.value;c({binaryPath:C.length===0?void 0:C})}}),o.jsx(Os,{children:"Laisse vide pour résoudre `llama-server` via le PATH."})]}),o.jsxs("label",{className:"flex min-w-[6rem] flex-col gap-1",children:[o.jsx(Et,{children:"Port"}),o.jsx(ce,{"aria-label":"server port",value:Number.isNaN(e.port)?"":e.port.toString(),inputMode:"numeric",invalid:!!l.port,onChange:b=>c({port:Number.parseInt(b.target.value,10)})}),l.port&&o.jsx("small",{className:"text-xs text-danger",children:l.port})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Base URL (OpenAI-compatible)"}),o.jsx(ce,{"aria-label":"server base url",value:e.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!l.baseURL,onChange:b=>c({baseURL:b.target.value})}),l.baseURL&&o.jsx("small",{className:"text-xs text-danger",children:l.baseURL})]}),o.jsxs("label",{className:"flex items-start gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":"server auto start",checked:e.autoStart,disabled:!e.modelSource,onChange:b=>c({autoStart:b.target.checked}),className:"mt-1 accent-primary disabled:opacity-50"}),o.jsxs("span",{className:"flex flex-col",children:[o.jsx(Et,{children:"Démarrer automatiquement"}),!e.modelSource&&o.jsx(Os,{children:"Renseigne d'abord une source de modèle pour l'activer."})]})]}),o.jsxs("details",{className:"rounded-md border border-border p-2",children:[o.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted",children:"Réglages llama.cpp"}),o.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsxs(Et,{children:["Couches GPU ",o.jsx("span",{className:"text-muted",children:"(-ngl)"})]}),o.jsx(ce,{"aria-label":"gpu layers",value:e.gpuLayers===void 0?"":String(e.gpuLayers),inputMode:"numeric",placeholder:"99",onChange:b=>{const C=b.target.value.trim();c({gpuLayers:C.length===0?void 0:Number.parseInt(C,10)})}}),o.jsx(Os,{children:"0 = CPU seul."})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsxs(Et,{children:["Taille de contexte ",o.jsx("span",{className:"text-muted",children:"(-c)"})]}),o.jsx(ce,{"aria-label":"context size",value:e.contextSize===void 0?"":String(e.contextSize),inputMode:"numeric",placeholder:"16384",onChange:b=>{const C=b.target.value.trim();c({contextSize:C.length===0?void 0:Number.parseInt(C,10)})}})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsxs(Et,{children:["Adresse d'écoute ",o.jsx("span",{className:"text-muted",children:"(--host)"})]}),o.jsx(ce,{"aria-label":"listen host",value:e.host,placeholder:"127.0.0.1",invalid:!!l.host,onChange:b=>c({host:b.target.value})}),l.host&&o.jsx("small",{className:"text-xs text-danger",children:l.host})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":"jinja template",checked:e.jinja,onChange:b=>c({jinja:b.target.checked}),className:"accent-primary"}),o.jsxs(Et,{children:["Template chat Jinja ",o.jsx("span",{className:"text-muted",children:"(--jinja)"})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Arguments supplémentaires"}),o.jsx(ce,{"aria-label":"extra arguments",value:e.args.join(" "),placeholder:"--flash-attn --parallel 2",onChange:b=>c({args:_T(b.target.value)})}),y.length>0&&o.jsxs("small",{className:"text-xs text-warning",role:"status",children:[y.join(", ")," : cette option est déjà pilotée par un champ ci-dessus."]})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx(Et,{children:"Stop policy"}),o.jsx("select",{"aria-label":"server stop policy",value:e.stopPolicy,onChange:b=>c({stopPolicy:b.target.value}),className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:ST.map(b=>o.jsx("option",{value:b.value,children:b.label},b.value))})]})]})]}),o.jsx(jT,{preview:x,autoStart:e.autoStart}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{variant:"primary",size:"sm","aria-label":"save model server",onClick:i,disabled:t||!a,children:"Save server"}),o.jsx(M,{variant:"ghost",size:"sm","aria-label":"cancel model server",onClick:s,disabled:t,children:"Cancel"})]})]})}const Ru="";function ET({servers:e,value:t,onChange:n,ariaLabel:r="local model server"}){const s=t!==void 0&&!e.some(i=>i.id===t);return o.jsxs("select",{"aria-label":r,value:t??Ru,onChange:i=>n(i.target.value===Ru?void 0:i.target.value),className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:[o.jsx("option",{value:Ru,children:"None (external endpoint)"}),e.map(i=>o.jsxs("option",{value:i.id,children:[i.name," — ",i.servedModelName]},i.id)),s&&o.jsxs("option",{value:t,children:[t," (unknown / removed)"]})]})}function PT({mode:e,configured:t,references:n}){if(e==="firstRun")return n.map(l=>({profile:l,selected:!1,available:null}));const r=new Set(t.map(l=>l.id)),s=t.map(l=>({profile:l,selected:!0,available:null})),i=n.filter(l=>!r.has(l.id)).map(l=>({profile:l,selected:!1,available:null}));return[...s,...i]}const AT=3e3;function Ro(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function TT(e="firstRun"){const{profile:t}=fe(),[n,r]=g.useState(null),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),f=g.useRef(0),p=g.useRef(null);g.useEffect(()=>()=>{f.current+=1,p.current!==null&&clearTimeout(p.current)},[]);const m=g.useCallback(async(S,N)=>{const L=f.current+1;f.current=L;const A=()=>f.current!==L;d(!0),p.current!==null&&clearTimeout(p.current),p.current=setTimeout(()=>{A()||d(!1)},AT);try{const k=await t.detectProfiles(S);if(A())return;const D=new Map(k.map(R=>[R.profile.id,R.available]));i(R=>R.map(E=>{const O=D.get(E.profile.id)??E.available;return{...E,available:O,selected:N.preselect?O===!0:E.selected}}))}catch(k){if(A())return;N.reportError&&a(Ro(k))}finally{A()||(p.current!==null&&clearTimeout(p.current),p.current=null,d(!1))}},[t]),x=g.useCallback(async()=>{u(!0),a(null);let S=null;try{const[N,L]=await Promise.all([t.firstRunState(),e==="edit"?t.listProfiles():Promise.resolve([])]);r(N.isFirstRun);const A=PT({mode:e,configured:L,references:N.referenceProfiles});S=A.map(k=>k.profile),i(A)}catch(N){a(Ro(N)),r(!1)}finally{u(!1)}S!==null&&m(S,{preselect:e==="firstRun",reportError:!1})},[t,m,e]);g.useEffect(()=>{x()},[x]);const w=g.useCallback(S=>{i(N=>N.map(L=>L.profile.id===S?{...L,selected:!L.selected}:L))},[]),v=g.useCallback((S,N)=>{i(L=>L.map(A=>A.profile.id===S?{...A,profile:N}:A))},[]),_=g.useCallback(async S=>{a(null);try{const N=await t.cloneOpenCodeProfileFromSeed(S);i(L=>[...L,{profile:N,selected:!0,available:null}])}catch(N){a(Ro(N))}},[t]),y=g.useCallback(S=>{i(N=>N.filter(L=>L.profile.id!==S))},[]),b=g.useCallback(async()=>{a(null),await m(s.map(S=>S.profile),{preselect:!1,reportError:!0})},[m,s]),C=g.useCallback(async()=>{u(!0),a(null);try{const S=s.filter(N=>N.selected).map(N=>N.profile);await t.configureProfiles(S),r(!1)}catch(S){a(Ro(S))}finally{u(!1)}},[t,s]);return{isFirstRun:n,entries:s,error:l,busy:c,detecting:h,toggle:w,updateProfile:v,addOpenCodeProfile:_,remove:y,detect:b,finish:C,reload:x}}function LT(e){return e.length===0||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:/.test(e)?!1:!e.split(/[/\\]/).includes("..")}function ww(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Sw(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function Mu(e,t){return e===void 0?!0:Number.isInteger(e)&&e>0&&e<=t}const _x=4294967295,DT=65535;function RT(e){const t={};return Sw(e.endpoint)||(t.endpoint="Endpoint must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),e.apiKeyEnv!==void 0&&e.apiKeyEnv.length>0&&!ww(e.apiKeyEnv)&&(t.apiKeyEnv="Must be a valid env var name (not the key itself)."),Mu(e.requestTimeoutMs,_x)||(t.requestTimeoutMs="Must be a positive integer (ms)."),Mu(e.connectTimeoutMs,_x)||(t.connectTimeoutMs="Must be a positive integer (ms)."),Mu(e.maxToolIterations,DT)||(t.maxToolIterations="Must be a positive integer."),t}function MT(e){const t={};return Sw(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),t}function IT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),e.command.trim().length===0&&(t.command="Command is required.");const n=e.contextInjection;return n.strategy==="conventionFile"?LT(n.target)||(t.target="Target must be a relative file name (no .. or absolute)."):n.strategy==="flag"?n.flag.trim().length===0&&(t.flag="Flag is required."):n.strategy==="env"&&(ww(n.var)||(t.var="Must be a valid env var identifier.")),e.structuredAdapter==="openAiCompatible"&&(e.chatHttp?Object.assign(t,RT(e.chatHttp)):(t.endpoint="Endpoint must start with http:// or https://.",t.model="Model is required.")),e.structuredAdapter==="openCode"&&!e.opencodeProvider&&(e.opencode?Object.assign(t,MT(e.opencode)):(t.baseURL="Base URL must start with http:// or https://.",t.model="Model is required.")),t}function OT(){return{endpoint:"http://localhost:11434/v1",model:"qwen2.5-coder",requestTimeoutMs:12e4,connectTimeoutMs:5e3,maxToolIterations:16}}function BT(){return{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}function zT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function qe({children:e}){return o.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function kw(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function FT(){const{profile:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useCallback(async()=>{s(!0),l(null);try{n(await e.listOpenCodeProviders())}catch(c){n(null),l(kw(c))}finally{s(!1)}},[e]);return g.useEffect(()=>{a()},[a]),{providers:t,loading:r,error:i,reload:()=>void a()}}function Cw({onDone:e,forceOpen:t=!1}){const n=TT(t?"edit":"firstRun"),r=hT(),s=FT();if(n.isFirstRun===null||!t&&n.isFirstRun===!1)return null;async function i(){await n.finish(),e?.()}return o.jsx(ke,{"aria-label":"first run setup",className:"border-primary/40",title:o.jsxs("div",{className:"flex flex-col",children:[o.jsx("h2",{className:"text-base font-semibold text-content",children:"Welcome to IdeA"}),o.jsx("p",{className:"text-sm text-muted",children:"Choose which AI CLIs to configure. Commands are pre-filled and editable."})]}),children:o.jsxs("div",{className:"flex flex-col gap-4",children:[n.error&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),o.jsxs(gw,{children:[o.jsx(M,{onClick:()=>void n.detect(),disabled:n.busy,className:"whitespace-nowrap",children:"Detect installed CLIs"}),n.detecting&&o.jsx("span",{role:"status",className:"text-xs text-muted",children:"Detecting…"}),o.jsx(M,{onClick:()=>void n.addOpenCodeProfile(),disabled:n.busy,className:"whitespace-nowrap",children:"Add OpenCode profile"})]}),o.jsx(kT,{vm:r}),o.jsx("ul",{className:"flex list-none flex-col gap-3 p-0",children:n.entries.map(l=>o.jsx($T,{entry:l,servers:r.servers,providerCatalog:s,onToggle:()=>n.toggle(l.profile.id),onChange:a=>n.updateProfile(l.profile.id,a),onRemove:()=>n.remove(l.profile.id),onDuplicate:l.profile.structuredAdapter==="openCode"?()=>n.addOpenCodeProfile({name:`${l.profile.name} (copy)`,opencode:l.profile.opencode}):void 0},l.profile.id))}),o.jsx("footer",{className:"flex gap-2",children:o.jsx(M,{variant:"primary",onClick:()=>void i(),disabled:n.busy,children:"Save and continue"})})]})})}function $T({entry:e,servers:t,providerCatalog:n,onToggle:r,onChange:s,onRemove:i,onDuplicate:l}){const{profile:a,selected:c,available:u}=e,h=IT(a),d=a.structuredAdapter==="openCode";return o.jsxs("li",{className:"flex flex-col gap-2 rounded-md border border-border bg-raised p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:r,"aria-label":`use ${a.name}`,className:"accent-primary"}),o.jsx("strong",{className:"text-sm text-content",children:a.name})]}),o.jsx("span",{"aria-label":`${a.name} availability`,className:U("text-xs",u===null?"text-faint":u?"text-success":"text-danger"),children:u===null?"—":u?"✓ installed":"✗ not found"}),o.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[l&&o.jsx(M,{size:"sm","aria-label":`duplicate ${a.name}`,onClick:l,children:"Duplicate"}),o.jsx(sr,{size:"sm","aria-label":`remove ${a.name}`,onClick:i,children:"×"})]})]}),d&&o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Name"}),o.jsx(ce,{"aria-label":`${a.name} name`,value:a.name,invalid:!!h.name,onChange:f=>s({...a,name:f.target.value})}),h.name&&o.jsx("small",{className:"text-xs text-danger",children:h.name})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Command"}),o.jsx(ce,{"aria-label":`${a.name} command`,value:a.command,invalid:!!h.command,onChange:f=>s({...a,command:f.target.value})}),h.command&&o.jsx("small",{className:"text-xs text-danger",children:h.command})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Arguments"}),o.jsx(ce,{"aria-label":`${a.name} args`,value:a.args.join(" "),onChange:f=>s({...a,args:zT(f.target.value)})})]}),a.structuredAdapter==="openAiCompatible"&&o.jsx(qT,{profile:a,errors:h,onChange:s}),a.structuredAdapter==="openCode"&&o.jsx(WT,{profile:a,errors:h,servers:t,providerCatalog:n,onChange:s})]})}function WT({profile:e,errors:t,servers:n,providerCatalog:r,onChange:s}){const[i,l]=g.useState(e.opencodeProvider?"cloud":"local");return o.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[o.jsx("div",{role:"radiogroup","aria-label":"mode du profil OpenCode",className:"flex w-fit gap-1 rounded-md border border-border bg-raised p-0.5",children:[{id:"local",label:"Local (llama.cpp)"},{id:"cloud",label:"Provider cloud"}].map(a=>{const c=i===a.id;return o.jsx("button",{type:"button",role:"radio","aria-checked":c,onClick:()=>l(a.id),className:U("rounded px-2.5 py-1 text-xs font-medium transition-colors",c?"bg-primary text-on-primary":"text-muted hover:text-content"),children:a.label},a.id)})}),i==="local"&&o.jsx(UT,{profile:e,errors:t,servers:n,onChange:s}),i==="cloud"&&o.jsx(HT,{profile:e,catalog:r,onChange:s})]})}const yx="__custom__",bx="@ai-sdk/openai-compatible";function HT({profile:e,catalog:t,onChange:n}){const{profile:r}=fe(),s=e.opencodeProvider,[i,l]=g.useState(s?.custom?"custom":"catalog"),[a,c]=g.useState(s?.providerId??""),[u,h]=g.useState(s?.model??""),[d,f]=g.useState(""),[p,m]=g.useState(s?.custom?.npm??bx),[x,w]=g.useState(s?.custom?.baseUrl??""),[v,_]=g.useState(s?.custom?.displayName??""),[y,b]=g.useState(""),[C,S]=g.useState(!1),[N,L]=g.useState(!1),[A,k]=g.useState(null),[D,R]=g.useState({}),E=s!==void 0,O=t.providers?.find(z=>z.providerId===a)?.models??[],I=t.providers!==null&&!t.loading,W=(t.providers??[]).filter(z=>{if(z.providerId===a)return!0;const j=d.trim().toLowerCase();return j.length===0?!0:z.displayName.toLowerCase().includes(j)||z.providerId.toLowerCase().includes(j)}),G=N||y.length===0||i==="catalog"&&(!I||!!t.error);async function P(){const z={};if(a.trim().length===0&&(z.providerId="Le provider est obligatoire."),u.trim().length===0&&(z.model="Le modèle est obligatoire."),i==="custom"&&(p.trim().length===0&&(z.npm="Le paquet npm est obligatoire."),x.trim().length===0&&(z.baseUrl="L'URL de base est obligatoire.")),y.length===0&&(z.apiKey="La clé API est obligatoire."),R(z),!(Object.keys(z).length>0)){L(!0),k(null);try{const j=await r.saveOpenCodeProviderProfile({profile:e,providerId:a.trim(),model:u.trim(),apiKey:y,...i==="custom"?{custom:{npm:p.trim(),baseUrl:x.trim(),displayName:v.trim().length>0?v.trim():void 0}}:{}});n(j),b("")}catch(j){k(kw(j))}finally{L(!1)}}}return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider cloud (OpenCode)"}),A&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:A}),t.loading&&o.jsx("p",{className:"text-xs text-faint",children:"Chargement des providers…"}),t.error&&o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"Impossible de charger la liste des providers cloud."}),o.jsx(M,{size:"sm",onClick:()=>t.reload(),className:"w-fit",children:"Réessayer"})]}),i==="catalog"&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Provider"}),I&&o.jsx("input",{type:"text","aria-label":`${e.name} provider search`,placeholder:"Rechercher un provider…",value:d,onChange:z=>f(z.target.value),className:"h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"}),o.jsxs("select",{"aria-label":`${e.name} provider`,value:a,disabled:!I,onChange:z=>{const j=z.target.value;j===yx?(l("custom"),c(""),h("")):(c(j),h("")),R(se=>({...se,providerId:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",D.providerId?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:t.loading?"Chargement des providers…":"Choisir un provider…"}),W.map(z=>o.jsx("option",{value:z.providerId,children:z.displayName},z.providerId)),o.jsx("option",{value:yx,children:"Autre / personnalisé…"})]}),D.providerId&&o.jsx("small",{className:"text-xs text-danger",children:D.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Modèle"}),o.jsxs("select",{"aria-label":`${e.name} model`,value:u,disabled:a.length===0,onChange:z=>{h(z.target.value),R(j=>({...j,model:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",D.model?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:a.length===0?"—":"Choisir un modèle…"}),O.map(z=>o.jsx("option",{value:z,children:z},z))]}),D.model&&o.jsx("small",{className:"text-xs text-danger",children:D.model})]})]}),i==="custom"&&o.jsxs("fieldset",{className:"flex flex-col gap-2 rounded-md border border-border/50 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider personnalisé"}),o.jsx(M,{variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{l("catalog"),c(""),h(""),R({})},children:"← Choisir un provider du catalogue"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Identifiant du provider"}),o.jsx(ce,{"aria-label":`${e.name} custom provider id`,value:a,placeholder:"ex. mon-provider",invalid:!!D.providerId,onChange:z=>{c(z.target.value),R(j=>({...j,providerId:void 0}))}}),D.providerId&&o.jsx("small",{className:"text-xs text-danger",children:D.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Paquet npm"}),o.jsx(ce,{"aria-label":`${e.name} custom npm package`,value:p,placeholder:bx,invalid:!!D.npm,onChange:z=>{m(z.target.value),R(j=>({...j,npm:void 0}))}}),D.npm&&o.jsx("small",{className:"text-xs text-danger",children:D.npm})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"URL de base"}),o.jsx(ce,{"aria-label":`${e.name} custom base url`,value:x,placeholder:"https://api.mon-provider.example/v1",invalid:!!D.baseUrl,onChange:z=>{w(z.target.value),R(j=>({...j,baseUrl:void 0}))}}),D.baseUrl&&o.jsx("small",{className:"text-xs text-danger",children:D.baseUrl})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Modèle"}),o.jsx(ce,{"aria-label":`${e.name} model`,value:u,placeholder:"ex. mon-modele-1",invalid:!!D.model,onChange:z=>{h(z.target.value),R(j=>({...j,model:void 0}))}}),D.model&&o.jsx("small",{className:"text-xs text-danger",children:D.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Libellé du modèle (optionnel)"}),o.jsx(ce,{"aria-label":`${e.name} custom display name`,value:v,placeholder:"ex. Mon modèle",onChange:z=>_(z.target.value)})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Clé API"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ce,{"aria-label":`${e.name} api key`,type:C?"text":"password",value:y,placeholder:E?"Ressaisissez la clé API pour confirmer l'enregistrement":"ex. sk-ant-…",invalid:!!D.apiKey,onChange:z=>{b(z.target.value),R(j=>({...j,apiKey:void 0}))}}),o.jsx(sr,{size:"sm","aria-label":"afficher/masquer la clé API",onClick:()=>S(z=>!z),children:C?"🙈":"👁"})]}),D.apiKey&&o.jsx("small",{className:"text-xs text-danger",children:D.apiKey}),o.jsx("small",{className:"text-xs text-faint",children:"Jamais affichée ni renvoyée par IdeA une fois enregistrée ; stockée chiffrée localement."}),E&&o.jsx("small",{className:"text-xs text-muted",children:"Pour des raisons de sécurité, la clé n'est jamais réaffichée : ressaisissez-la à chaque modification de ce profil."})]}),o.jsx(M,{variant:"primary",size:"sm",loading:N,disabled:G,onClick:()=>void P(),className:"w-fit",children:"Enregistrer"})]})}function UT({profile:e,errors:t,servers:n,onChange:r}){const s=e.opencode??BT(),i=l=>r({...e,opencode:{...s,...l}});return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local model (OpenCode + llama.cpp)"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Base URL"}),o.jsx(ce,{"aria-label":`${e.name} base url`,value:s.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!t.baseURL,onChange:l=>i({baseURL:l.target.value})}),t.baseURL&&o.jsx("small",{className:"text-xs text-danger",children:t.baseURL})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Model"}),o.jsx(ce,{"aria-label":`${e.name} model`,value:s.model,placeholder:"qwen3-coder-30b",invalid:!!t.model,onChange:l=>i({model:l.target.value})}),t.model&&o.jsx("small",{className:"text-xs text-danger",children:t.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"API key (optional — a local llama.cpp needs none)"}),o.jsx(ce,{"aria-label":`${e.name} api key`,value:s.apiKey??"",placeholder:"e.g. sk-no-key",onChange:l=>{const a=l.target.value;i({apiKey:a.length===0?void 0:a})}})]}),o.jsxs("div",{className:"flex flex-wrap gap-4",children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":`${e.name} reasoning`,checked:s.reasoning??!0,onChange:l=>i({reasoning:l.target.checked}),className:"accent-primary"}),o.jsx(qe,{children:"Reasoning"})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":`${e.name} attachment`,checked:s.attachment??!1,onChange:l=>i({attachment:l.target.checked}),className:"accent-primary"}),o.jsx(qe,{children:"Attachments"})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Local model server (bind to a managed llama.cpp server, or none)"}),o.jsx(ET,{ariaLabel:`${e.name} local model server`,servers:n,value:s.localModelServerId,onChange:l=>i({localModelServerId:l})})]})]})}function Iu(e){const t=e.trim();if(t.length===0)return;const n=Number(t);return Number.isFinite(n)?n:NaN}function qT({profile:e,errors:t,onChange:n}){const r=e.chatHttp??OT(),s=i=>n({...e,chatHttp:{...r,...i}});return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local / LAN model (OpenAI-compatible)"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Endpoint"}),o.jsx(ce,{"aria-label":`${e.name} endpoint`,value:r.endpoint,placeholder:"http://localhost:11434/v1",invalid:!!t.endpoint,onChange:i=>s({endpoint:i.target.value})}),t.endpoint&&o.jsx("small",{className:"text-xs text-danger",children:t.endpoint})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"Model"}),o.jsx(ce,{"aria-label":`${e.name} model`,value:r.model,placeholder:"qwen2.5-coder",invalid:!!t.model,onChange:i=>s({model:i.target.value})}),t.model&&o.jsx("small",{className:"text-xs text-danger",children:t.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(qe,{children:"API key — environment variable name (never the key itself)"}),o.jsx(ce,{"aria-label":`${e.name} api key env`,value:r.apiKeyEnv??"",placeholder:"e.g. OPENAI_API_KEY (variable name, not the secret)",invalid:!!t.apiKeyEnv,onChange:i=>{const l=i.target.value.trim();s({apiKeyEnv:l.length===0?void 0:l})}}),t.apiKeyEnv&&o.jsx("small",{className:"text-xs text-danger",children:t.apiKeyEnv})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(qe,{children:"Request timeout (ms)"}),o.jsx(ce,{"aria-label":`${e.name} request timeout`,value:r.requestTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.requestTimeoutMs,onChange:i=>s({requestTimeoutMs:Iu(i.target.value)})}),t.requestTimeoutMs&&o.jsx("small",{className:"text-xs text-danger",children:t.requestTimeoutMs})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(qe,{children:"Connect timeout (ms)"}),o.jsx(ce,{"aria-label":`${e.name} connect timeout`,value:r.connectTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.connectTimeoutMs,onChange:i=>s({connectTimeoutMs:Iu(i.target.value)})}),t.connectTimeoutMs&&o.jsx("small",{className:"text-xs text-danger",children:t.connectTimeoutMs})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(qe,{children:"Max tool iterations"}),o.jsx(ce,{"aria-label":`${e.name} max tool iterations`,value:r.maxToolIterations?.toString()??"",inputMode:"numeric",invalid:!!t.maxToolIterations,onChange:i=>s({maxToolIterations:Iu(i.target.value)})}),t.maxToolIterations&&o.jsx("small",{className:"text-xs text-danger",children:t.maxToolIterations})]})]})]})}function jw(){const{profile:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{s(null);try{n(await e.listProfiles())}catch(u){s(u&&typeof u=="object"&&"message"in u?String(u.message):String(u))}},[e]);g.useEffect(()=>{a()},[a]);async function c(u){await e.deleteProfile(u),await a()}return i?o.jsx(Cw,{forceOpen:!0,onDone:()=>{l(!1),a()}}):o.jsx(ke,{"aria-label":"ai profiles settings",title:"Profils IA",actions:o.jsx(M,{size:"sm",onClick:()=>l(!0),children:"Configurer les profils"}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[r&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:r}),t.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun profil configuré."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(u=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex items-baseline gap-2",children:[o.jsx("strong",{className:"text-sm text-content",children:u.name}),o.jsx("code",{className:"text-xs text-muted",children:u.command})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`supprimer ${u.name}`,onClick:()=>void c(u.id),children:"Supprimer"})]},u.id))})]})})}const VT=3e3,KT=2500;function wx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function GT(){const{device:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(!1),[a,c]=g.useState(!1),[u,h]=g.useState(null),[d,f]=g.useState([]),[p,m]=g.useState(!1),x=g.useRef(null),w=g.useCallback(async()=>{try{const L=await e.listDevices();return n(L),s(null),L}catch(L){return s(wx(L)),null}},[e]),v=g.useCallback(async()=>{const L=await w();L&&(x.current=new Set(L.map(A=>A.deviceId)))},[w]);g.useEffect(()=>{v()},[v]),g.useEffect(()=>{if(!u)return;const L=setInterval(()=>{(async()=>{const A=await w();if(!A)return;const k=x.current;if(x.current=new Set(A.map(R=>R.deviceId)),!k)return;const D=A.filter(R=>!k.has(R.deviceId)).map(R=>R.deviceId);D.length>0&&f(D)})()},VT);return()=>clearInterval(L)},[u,w]),g.useEffect(()=>{if(d.length===0)return;const L=setTimeout(()=>f([]),KT);return()=>clearTimeout(L)},[d]);const _=g.useCallback(async L=>{l(!0),s(null);try{return await L(),!0}catch(A){return s(wx(A)),!1}finally{l(!1)}},[]),y=g.useCallback(async()=>{c(!0);try{await _(async()=>{h(await e.createPairingCode())})}finally{c(!1)}},[e,_]),b=g.useCallback(()=>h(null),[]),C=g.useCallback(async(L,A)=>{await _(()=>e.renameDevice(L,A))&&await v()},[e,_,v]),S=g.useCallback(async L=>{const A=L.isCurrentDevice;await _(()=>e.revokeDevice(L.deviceId))&&(A?m(!0):await v())},[e,_,v]),N=g.useCallback(async()=>{const L=t?.some(A=>A.isCurrentDevice)??!1;await _(()=>e.revokeAllDevices())&&(L?m(!0):await v())},[t,e,_,v]);return{devices:t,error:r,busy:i,generating:a,code:u,freshDeviceIds:d,sessionEnded:p,refresh:v,generateCode:y,dismissCode:b,rename:C,revoke:S,revokeAll:N}}const YT=2*60*1e3;function Sx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function XT(e){return e.toLocaleTimeString("fr-FR",{hour:"2-digit",minute:"2-digit"})}function Nw(e,t=new Date){const n=new Date(e),r=n.getFullYear()===t.getFullYear();return n.toLocaleDateString("fr-FR",{day:"numeric",month:"short",...r?{}:{year:"numeric"}})}function QT(e,t=new Date){if(t.getTime()-eOu(e.expiresAtMs)),[i,l]=g.useState(!1);g.useEffect(()=>{s(Ou(e.expiresAtMs));const c=setInterval(()=>s(Ou(e.expiresAtMs)),1e3);return()=>clearInterval(c)},[e.expiresAtMs]),g.useEffect(()=>{l(!1)},[e.code]),g.useEffect(()=>{if(!i)return;const c=setTimeout(()=>l(!1),2e3);return()=>clearTimeout(c)},[i]);const a=r===null;return o.jsx(ke,{"data-testid":"pairing-code-panel",className:"flex flex-col gap-3",children:a?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm text-muted",children:"Ce code a expiré."}),o.jsx("div",{children:o.jsx(M,{size:"sm",onClick:t,children:"Générer un nouveau code"})})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm text-muted",children:"Saisissez ce code sur le nouvel appareil."}),o.jsx("p",{"data-testid":"pairing-code-value","aria-label":e.code,className:"flex gap-3 font-mono text-2xl font-semibold tracking-[0.2em] text-content sm:text-3xl",children:ZT(e.code).map((c,u)=>o.jsx("span",{"aria-hidden":"true",children:c},u))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void eL(e.code).then(c=>l(c)),children:i?"Copié":"Copier"}),o.jsx("span",{className:"text-xs text-faint","data-testid":"pairing-code-countdown",children:r}),o.jsx(M,{size:"sm",variant:"ghost",className:"ml-auto",onClick:n,children:"Fermer"})]})]})})}function kx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:s=!1,onConfirm:i,onCancel:l}){const a=g.useRef(null);return g.useEffect(()=>{a.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.floatingWindow},onClick:l,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),o.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:s,onClick:()=>void i(),children:n})]})]})})}const vp=40,Ew="Cet appareil",nL=[[/\bEdg(?:e|A|iOS)?\//,"Edge"],[/\bOPR\/|\bOpera\//,"Opera"],[/\bFirefox\/|\bFxiOS\//,"Firefox"],[/\bChrome\/|\bCriOS\//,"Chrome"],[/\bSafari\//,"Safari"]],rL=[[/\bWindows\b/,"Windows"],[/\bMac OS X\b|\bMacintosh\b/,"Mac"],[/\bCrOS\b/,"ChromeOS"],[/\bLinux\b|\bX11\b/,"Linux"]];function sL(e){const t=e??"";if(/\biPhone\b/.test(t))return"iPhone";if(/\biPad\b/.test(t))return"iPad";if(/\bAndroid\b/.test(t))return"Android";const n=nL.find(([s])=>s.test(t))?.[1],r=rL.find(([s])=>s.test(t))?.[1];return n&&r?`${n} sur ${r}`:n??r??Ew}function Cx(e){return Array.from(e.trim()).slice(0,vp).join("")}function iL(){return typeof navigator>"u"||!navigator.userAgent?Ew:sL(navigator.userAgent)}function Pw({onSessionEnded:e}){const t=GT(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[l,a]=g.useState(null);g.useEffect(()=>{t.sessionEnded&&e?.()},[t.sessionEnded,e]);const c=t.devices;return o.jsxs("section",{"data-testid":"devices-screen",className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Appareils"}),o.jsx("p",{className:"text-sm text-muted",children:"Les appareils autorisés à accéder à cette instance IdeA."})]}),o.jsx(M,{onClick:()=>void t.generateCode(),loading:t.generating,children:"Appairer"})]}),t.code&&o.jsx(tL,{code:t.code,onRegenerate:()=>void t.generateCode(),onDismiss:t.dismissCode}),t.error&&o.jsx(ke,{className:"border-danger/40",children:o.jsx("p",{role:"alert",className:"text-sm text-danger",children:t.error})}),c===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des appareils…"]}):c.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun appareil appairé."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"device-list",children:c.map(u=>o.jsx(lL,{device:u,fresh:t.freshDeviceIds.includes(u.deviceId),renaming:l===u.deviceId,onStartRename:()=>a(u.deviceId),onCancelRename:()=>a(null),onRename:async h=>{await t.rename(u.deviceId,h),a(null)},onRevoke:()=>r(u)},u.deviceId))}),c!==null&&c.length>0&&o.jsx("div",{className:"pt-1",children:o.jsx(M,{variant:"ghost",size:"sm",onClick:()=>i(!0),children:"Révoquer tous les appareils"})}),n&&o.jsx(kx,{title:"Révoquer cet appareil ?",body:n.isCurrentDevice?"Il devra être appairé à nouveau pour accéder à IdeA. Vous serez déconnecté immédiatement.":"Il devra être appairé à nouveau pour accéder à IdeA.",confirmLabel:"Révoquer",busy:t.busy,onConfirm:async()=>{const u=n;r(null),await t.revoke(u)},onCancel:()=>r(null)}),s&&o.jsx(kx,{title:"Révoquer tous les appareils ?",body:"Tous les appareils, y compris celui-ci, devront être appairés à nouveau. Vous serez déconnecté immédiatement.",confirmLabel:"Tout révoquer",danger:!0,busy:t.busy,onConfirm:async()=>{i(!1),await t.revokeAll()},onCancel:()=>i(!1)})]})}function lL({device:e,fresh:t,renaming:n,onStartRename:r,onCancelRename:s,onRename:i,onRevoke:l}){return o.jsx("li",{"data-testid":"device-row","data-fresh":t||void 0,className:U("py-3 transition-colors first:pt-0 last:pb-0",t&&"bg-success/10"),children:n?o.jsx(oL,{device:e,onSubmit:i,onCancel:s}):o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),e.isCurrentDevice&&o.jsx("span",{className:"shrink-0 rounded-full bg-primary/15 px-2 py-0.5 text-[0.65rem] font-medium text-primary",children:"Cet appareil"})]}),o.jsx("span",{className:"text-xs text-muted",children:QT(e.lastSeenAtMs)}),o.jsx("span",{className:"text-[0.7rem] text-faint",children:JT(e.pairedAtMs)})]}),o.jsx(aL,{deviceName:e.name,onRename:r,onRevoke:l})]})})}function oL({device:e,onSubmit:t,onCancel:n}){const[r,s]=g.useState(e.name),i=r.trim();return o.jsxs("form",{className:"flex flex-col gap-2",onSubmit:l=>{l.preventDefault(),i.length>0&&t(i)},children:[o.jsx(qt,{label:"Nom de l'appareil",hideLabel:!0,children:({id:l})=>o.jsx(ce,{id:l,value:r,autoFocus:!0,maxLength:vp,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Escape"&&n()}})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{type:"submit",size:"sm",disabled:i.length===0,children:"Renommer"}),o.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Annuler"})]})]})}function aL({deviceName:e,onRename:t,onRevoke:n}){const[r,s]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const i=()=>s(!1);return window.addEventListener("click",i),()=>window.removeEventListener("click",i)},[r]),o.jsxs("div",{className:"relative shrink-0",onClick:i=>i.stopPropagation(),children:[o.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":r,"aria-label":`Actions pour ${e}`,onClick:()=>s(i=>!i),className:"rounded-md px-2 py-1 text-sm text-muted transition-colors hover:bg-raised hover:text-content",children:"⋯"}),r&&o.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-10 mt-1 flex min-w-36 flex-col rounded-md border border-border bg-raised py-1 shadow-lg",children:[o.jsx("button",{type:"button",role:"menuitem",onClick:()=>{s(!1),t()},className:"px-3 py-1.5 text-left text-sm text-content transition-colors hover:bg-canvas",children:"Renommer"}),o.jsx("button",{type:"button",role:"menuitem",onClick:()=>{s(!1),n()},className:"px-3 py-1.5 text-left text-sm text-danger transition-colors hover:bg-canvas",children:"Révoquer"})]})]})}const cL=250;function Ki(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function uL(){const{desktopServer:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState({state:"stopped"}),[i,l]=g.useState([]),[a,c]=g.useState(),[u,h]=g.useState([]),[d,f]=g.useState(null),[p,m]=g.useState(null),[x,w]=g.useState(!1),[v,_]=g.useState(!1),y=g.useRef(0);g.useEffect(()=>{let E=!0;return(async()=>{try{const[O,I]=await Promise.all([e.getExposureSettings(),e.status()]);if(!E)return;n(O),s(I)}catch(O){E&&m(Ki(O))}})(),()=>{E=!1}},[e]),g.useEffect(()=>{let E=!0;return(async()=>{try{const O=await e.previewExposure({mode:"localOnly",autoStart:!1,port:0,trustedProxies:[]});E&&l(O.candidateLanAddresses)}catch{}})(),()=>{E=!1}},[e]),g.useEffect(()=>{let E,O=!1;return e.onStatusChanged(s).then(I=>{O?I():E=I}),()=>{O=!0,E?.()}},[e]),g.useEffect(()=>{if(!t)return;const E=++y.current,O=setTimeout(()=>{e.previewExposure(t).then(I=>{E===y.current&&(c(I.upstreamUrl),h(I.warnings),f(null))},I=>{E===y.current&&(c(void 0),h([]),f(Ki(I)))})},cL);return()=>clearTimeout(O)},[e,t]);const b=g.useCallback(E=>{m(null),n(O=>O&&{...O,...E})},[]),C=g.useCallback(E=>{b(E==="localOnly"?{mode:E,publicOrigin:void 0,lanBindAddress:void 0,trustedProxies:[]}:E==="remoteProxyLocal"?{mode:E,lanBindAddress:void 0,trustedProxies:[]}:{mode:E})},[b]),S=g.useCallback(E=>b({publicOrigin:E.trim()||void 0}),[b]),N=g.useCallback(E=>b({lanBindAddress:E||void 0}),[b]),L=g.useCallback(E=>b({trustedProxies:E.split(/[\s,]+/).map(O=>O.trim()).filter(Boolean)}),[b]),A=g.useCallback(E=>b({port:E}),[b]),k=g.useCallback(async E=>{if(!t)return;const O={...t,autoStart:E};_(!0),m(null);try{await e.saveExposureSettings(O),n(O)}catch(I){m(Ki(I))}finally{_(!1)}},[e,t]),D=g.useCallback(async()=>{if(t){w(!0),m(null);try{await e.saveExposureSettings(t),s(await e.start())}catch(E){m(Ki(E))}finally{w(!1)}}},[e,t]),R=g.useCallback(async()=>{w(!0),m(null);try{s(await e.stop())}catch(E){m(Ki(E))}finally{w(!1)}},[e]);return{ready:t!==null,settings:t,status:r,candidateLanAddresses:i,upstreamUrl:a,warnings:u,validationError:d,actionError:p,busy:x,autoStartBusy:v,setMode:C,setPublicOrigin:S,setLanBindAddress:N,setTrustedProxies:L,setPort:A,setAutoStart:k,start:D,stop:R}}const dL=[{mode:"localOnly",title:"Cet ordinateur uniquement",description:"Pour utiliser IdeA uniquement sur cet ordinateur. Les appareils distants ne peuvent pas se connecter."},{mode:"remoteProxyLocal",title:"Accès distant, proxy sur cet ordinateur",description:"À utiliser quand le proxy HTTPS tourne sur la même machine qu'IdeA Desktop."},{mode:"remoteProxyOtherMachine",title:"Accès distant, proxy sur une autre machine",description:"À utiliser quand le proxy HTTPS tourne sur une autre machine. IdeA n'acceptera que le trafic provenant de ce proxy."}],hL={stopped:"Arrêté",starting:"Démarrage…",running:"En cours d'exécution",stopping:"Arrêt…",failed:"Échec"};function fL({value:e,label:t}){const[n,r]=g.useState(!1),s=typeof navigator<"u"&&!!navigator.clipboard;return o.jsx(M,{size:"sm",variant:"ghost","aria-label":t,disabled:!s,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),window.setTimeout(()=>r(!1),1500)},()=>r(!1))},children:n?"Copié":"Copier"})}function pL({value:e,copyLabel:t}){return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"flex-1 truncate rounded-md border border-border bg-raised px-2 py-1.5 font-mono text-xs text-content",children:e}),o.jsx(fL,{value:e,label:t})]})}function mL(){const e=uL(),t=g.useRef(null);if(!e.ready||!e.settings)return o.jsx(ke,{"aria-label":"deployment settings",title:"Déploiement",children:o.jsx("p",{className:"text-sm text-muted",children:"Chargement…"})});const{settings:n,status:r}=e,s=r.state==="running",i=n.mode!=="localOnly",l=n.mode==="remoteProxyOtherMachine",a=r.state==="starting"||r.state==="stopping";return o.jsxs("div",{"aria-label":"deployment settings",className:"flex flex-col gap-4",children:[o.jsx(ke,{title:"Serveur",actions:s||r.state==="stopping"?o.jsx(M,{size:"sm",onClick:()=>void e.stop(),disabled:e.busy||a,children:"Arrêter"}):o.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy||a,children:"Démarrer"}),children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{"aria-hidden":!0,className:U("size-2 rounded-full",s&&"bg-success",r.state==="failed"&&"bg-danger",(r.state==="stopped"||a)&&"bg-faint")}),o.jsx("span",{className:"text-content",children:hL[r.state]})]}),r.localUrl&&o.jsxs("p",{className:"text-xs text-muted",children:["URL locale : ",o.jsx("code",{className:"font-mono text-content",children:r.localUrl})]}),r.publicUrl&&o.jsxs("p",{className:"text-xs text-muted",children:["URL publique : ",o.jsx("code",{className:"font-mono text-content",children:r.publicUrl})]}),r.state==="failed"&&r.error&&(r.error.code==="PORT_IN_USE"?o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("p",{role:"alert",className:"text-sm text-danger",children:["Le serveur n'a pas démarré automatiquement. ",r.error.message]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>{t.current?.scrollIntoView?.({behavior:"smooth",block:"center"}),t.current?.focus()},children:"Modifier le port"}),o.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy,children:"Réessayer"})]})]}):o.jsx("p",{role:"alert",className:"text-sm text-danger",children:r.error.message})),e.actionError&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.actionError}),o.jsxs("label",{className:"flex cursor-pointer items-start gap-2 pt-2",children:[o.jsx("input",{type:"checkbox",className:"mt-0.5","aria-label":"Démarrer le serveur au lancement d'IdeA",checked:n.autoStart,disabled:e.autoStartBusy,onChange:c=>void e.setAutoStart(c.target.checked)}),o.jsxs("span",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-sm text-content",children:"Démarrer le serveur au lancement d'IdeA"}),o.jsx("span",{className:"text-xs text-muted",children:"IdeA utilisera les réglages réseau enregistrés ci-dessous au prochain démarrage de l'application desktop."})]})]})]})}),o.jsx(ke,{title:"Accès réseau",children:o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx("div",{role:"radiogroup","aria-label":"mode d'accès réseau",className:"flex flex-col gap-2",children:dL.map(c=>{const u=n.mode===c.mode;return o.jsxs("label",{className:U("flex cursor-pointer gap-3 rounded-lg border p-3 transition-colors",u?"border-border-strong bg-raised":"border-border hover:bg-raised"),children:[o.jsx("input",{type:"radio",name:"exposure-mode",className:"mt-1",checked:u,onChange:()=>e.setMode(c.mode)}),o.jsxs("span",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),o.jsx("span",{className:"text-xs text-muted",children:c.description})]})]},c.mode)})}),o.jsx(qt,{label:"Port",children:({id:c})=>o.jsx(ce,{ref:t,id:c,type:"number",value:String(n.port),onChange:u=>e.setPort(Number(u.target.value))})}),i&&o.jsx(qt,{label:"Origine publique",hint:"Exemple : https://idea.example.com",children:({id:c,describedBy:u})=>o.jsx(ce,{id:c,"aria-describedby":u,placeholder:"https://idea.example.com",value:n.publicOrigin??"",onChange:h=>e.setPublicOrigin(h.target.value)})}),l&&o.jsxs(o.Fragment,{children:[o.jsx(qt,{label:"Adresse LAN d'écoute",hint:"L'adresse de cette machine à laquelle le proxy se connectera.",children:({id:c,describedBy:u})=>e.candidateLanAddresses.length>0?o.jsxs("select",{id:c,"aria-describedby":u,className:"rounded-md border border-border bg-surface px-2 py-1.5 text-sm text-content",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value),children:[o.jsx("option",{value:"",children:"Sélectionner une adresse…"}),e.candidateLanAddresses.map(h=>o.jsx("option",{value:h,children:h},h))]}):o.jsx(ce,{id:c,"aria-describedby":u,placeholder:"192.168.1.42",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value)})}),o.jsx(qt,{label:"IP/CIDR du proxy autorisé",hint:"Ce n'est pas l'adresse d'écoute d'IdeA. C'est la machine autorisée à contacter IdeA.",children:({id:c,describedBy:u})=>o.jsx(ce,{id:c,"aria-describedby":u,placeholder:"203.0.113.7 or 203.0.113.0/24",value:n.trustedProxies.join(", "),onChange:h=>e.setTrustedProxies(h.target.value)})}),o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Si votre proxy n'est pas sur cet ordinateur, choisissez ce mode. Sinon, le proxy peut expirer sans erreur IdeA."})]}),e.warnings.map(c=>o.jsx("p",{className:"text-xs text-warning",children:c.message},c.code)),e.validationError&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.validationError})]})}),i&&o.jsx(ke,{title:"Configuration du proxy",children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("p",{className:"text-xs text-muted",children:"Faites pointer votre proxy inverse HTTPS vers cet upstream."}),e.upstreamUrl?o.jsx(pL,{value:e.upstreamUrl,copyLabel:"copier l'URL upstream"}):o.jsx("p",{className:"text-xs text-faint",children:"Complétez les paramètres ci-dessus pour obtenir l'URL upstream."})]})}),o.jsx(ke,{title:"Appairage",children:o.jsxs("p",{className:"text-sm text-muted",children:["L'appairage est géré dans"," ",o.jsx("span",{className:"text-content",children:"Paramètres → Appareils"}),", où vous pouvez générer un code et révoquer des appareils."]})})]})}const Aw={aiProfiles:"Profils IA",deployment:"Déploiement",devices:"Appareils",plugins:"Plugins"},Tw=["aiProfiles","deployment","devices","plugins"];function gL({section:e,onSectionChange:t,onClose:n}){return o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsxs("nav",{"aria-label":"settings sections",className:"flex w-52 shrink-0 flex-col gap-1 border-r border-border p-3",children:[Tw.map(r=>{const s=r===e;return o.jsx("button",{type:"button","aria-current":s?"page":void 0,onClick:()=>t(r),className:U("rounded-md px-3 py-2 text-left text-sm transition-colors",s?"bg-raised font-semibold text-content":"text-muted hover:bg-raised hover:text-content"),children:Aw[r]},r)}),o.jsx("div",{className:"mt-auto pt-2",children:o.jsx(M,{size:"sm",variant:"ghost",className:"w-full",onClick:n,children:"Fermer les paramètres"})})]}),o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-2xl",children:e==="aiProfiles"?o.jsx(jw,{}):e==="deployment"?o.jsx(mL,{}):e==="plugins"?o.jsx(hA,{}):o.jsx(Pw,{})})})]})}function Gi(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const xL={branches:[],current:null},jx=20;function vL(e){const{git:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(xL),[l,a]=g.useState([]),[c,u]=g.useState(!1),[h,d]=g.useState(null),f=g.useCallback(async()=>{u(!0),d(null);try{const[v,_,y]=await Promise.all([t.status(e),t.branches(e),t.log(e,jx)]);r(v),i(_),a(y)}catch(v){d(Gi(v))}finally{u(!1)}},[t,e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async v=>{u(!0),d(null);try{await t.stage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!0}:y))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async v=>{u(!0),d(null);try{await t.unstage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!1}:y))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]),x=g.useCallback(async v=>{u(!0),d(null);try{const _=await t.commit(e,v);r(y=>y.filter(b=>!b.staged)),a(y=>[_,...y].slice(0,jx))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]),w=g.useCallback(async v=>{u(!0),d(null);try{await t.checkout(e,v),i(_=>({branches:_.branches.includes(v)?_.branches:[..._.branches,v],current:v}))}catch(_){d(Gi(_))}finally{u(!1)}},[t,e]);return{files:n,branches:s,log:l,busy:c,error:h,refresh:f,stage:p,unstage:m,commit:x,checkout:w}}function Nx(e){const t={children:[]};for(const n of e){const r=n.path.split("/").filter(Boolean);let s=t;r.forEach((i,l)=>{const a=l===r.length-1,c=r.slice(0,l+1).join("/");let u=s.children.find(h=>h.name===i&&h.isDir===!a);u||(u={name:i,path:c,isDir:!a,staged:n.staged,children:[]},s.children.push(u)),s=u})}return Lw(t),t.children}function Lw(e){e.children.sort((t,n)=>t.isDir!==n.isDir?t.isDir?-1:1:t.name.localeCompare(n.name)),e.children.forEach(Lw)}function $h({nodes:e,depth:t,action:n,onAction:r,busy:s}){return o.jsx("ul",{className:"flex flex-col gap-0.5",children:e.map(i=>i.isDir?o.jsxs("li",{children:[o.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-xs text-muted",style:{paddingLeft:`${t*14+8}px`},children:[o.jsx("span",{"aria-hidden":!0,className:"text-faint",children:"▸"}),o.jsx("span",{className:"truncate",children:i.name})]}),o.jsx($h,{nodes:i.children,depth:t+1,action:n,onAction:r,busy:s})]},i.path):o.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:bg-raised",style:{paddingLeft:`${t*14+8}px`},children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{"aria-hidden":!0,className:U("size-1.5 shrink-0 rounded-full",n==="unstage"?"bg-success":"bg-warning")}),o.jsx("code",{className:"min-w-0 truncate text-xs text-content",children:i.name})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`${n} ${i.path}`,disabled:s,onClick:()=>r(i.path),className:"shrink-0 text-muted hover:text-content",children:n==="unstage"?"Unstage":"Stage"})]},i.path))})}function Dw({projectId:e}){const t=vL(e),[n,r]=g.useState(""),[s,i]=g.useState(""),l=t.files.filter(f=>f.staged),a=t.files.filter(f=>!f.staged),c=n.trim().length>0&&l.length>0&&!t.busy;async function u(f){f.preventDefault(),c&&(await t.commit(n.trim()),r(""))}async function h(f){await t.checkout(f)}async function d(f){f.preventDefault();const p=s.trim();!p||t.busy||(await t.checkout(p),i(""))}return o.jsxs(ke,{title:"Git",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("section",{"aria-label":"Changes",className:"border-b border-border p-4",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Changes"}),t.busy&&o.jsx(Me,{size:12})]}),t.files.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No changes."}):o.jsxs("div",{className:"flex flex-col gap-3",children:[l.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Staged"}),o.jsx($h,{nodes:Nx(l),depth:0,action:"unstage",onAction:f=>void t.unstage(f),busy:t.busy})]}),a.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Unstaged"}),o.jsx($h,{nodes:Nx(a),depth:0,action:"stage",onAction:f=>void t.stage(f),busy:t.busy})]})]})]}),o.jsxs("section",{"aria-label":"Commit",className:"border-b border-border p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Commit"}),o.jsxs("form",{onSubmit:u,className:"flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"commit message",placeholder:"Commit message",value:n,onChange:f=>r(f.target.value)}),o.jsx(M,{type:"submit",variant:"primary",disabled:!c,loading:t.busy,className:"self-end",children:"Commit"})]})]}),o.jsxs("section",{"aria-label":"Branches",className:"border-b border-border p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Branches"}),o.jsxs("p",{className:"mb-2 text-sm text-content",children:["Current:"," ",o.jsx("span",{className:"font-medium",children:t.branches.current??"(none)"})]}),t.branches.branches.length>0&&o.jsx("ul",{className:"mb-3 flex flex-col gap-0.5",children:t.branches.branches.map(f=>{const p=f===t.branches.current;return o.jsxs("li",{className:U("flex items-center justify-between gap-2 rounded-md px-2 py-1",p&&"bg-raised"),children:[o.jsx("span",{className:U("text-sm",p?"font-semibold text-primary":"text-content"),children:f}),!p&&o.jsx(M,{size:"sm",variant:"ghost","aria-label":`checkout ${f}`,disabled:t.busy,onClick:()=>void h(f),className:"shrink-0 text-muted hover:text-content",children:"Checkout"})]},f)})}),o.jsxs("form",{onSubmit:d,className:"flex items-center gap-2",children:[o.jsx(ce,{"aria-label":"new branch name",placeholder:"New branch",value:s,onChange:f=>i(f.target.value),className:"flex-1"}),o.jsx(M,{type:"submit",variant:"ghost",disabled:!s.trim()||t.busy,children:"Create & checkout"})]})]}),o.jsxs("section",{"aria-label":"Log",className:"p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Log"}),t.log.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No commits yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.log.map(f=>o.jsxs("li",{className:"flex items-baseline gap-2 py-1.5",children:[o.jsx("code",{className:"shrink-0 text-xs text-faint",children:f.hash.slice(0,7)}),o.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:f.summary})]},f.hash))})]})]})}const Ex=["#4f9cf9","#a78bfa","#34d399","#fbbf24","#f87171","#38bdf8","#fb923c","#c084fc","#f472b6","#2dd4bf"];function Yi(e){return Ex[e%Ex.length]}function _L(e){return e.indexOf(null)}function Px(e,t){const n=_L(e);return n!==-1?(e[n]=t,n):(e.push(t),e.length-1)}function yL(e){const t=[],n=[];for(const r of e){const{hash:s,parents:i}=r,l=t.slice();let a=t.indexOf(s);a===-1&&(a=Px(t,s));for(let f=0;f{a(!0),u(null);try{const d=await t.graph(e,bL);r(d),i(yL(d))}catch(d){u(d&&typeof d=="object"&&"message"in d?String(d.message):String(d))}finally{a(!1)}},[t,e]);return g.useEffect(()=>{h()},[h]),{commits:n,rows:s,busy:l,error:c,refresh:h}}const tc=16,ma=36,Ax=4.5,Wh=e=>e*tc+tc/2;function Tx(e,t,n){const r=Wh(e.fromLane),s=Wh(e.toLane);if(r===s)return`M ${r} ${t} L ${s} ${n}`;const i=(t+n)/2;return`M ${r} ${t} C ${r} ${i} ${s} ${i} ${s} ${n}`}function SL({row:e,laneCount:t}){const n=t*tc+tc/2,r=ma/2,s=Wh(e.lane);return o.jsxs("svg",{width:n,height:ma,"aria-hidden":!0,className:"shrink-0 overflow-visible",children:[e.incoming.map((i,l)=>o.jsx("path",{d:Tx(i,0,r),fill:"none",stroke:i.color,strokeWidth:2},`in-${l}`)),e.outgoing.map((i,l)=>o.jsx("path",{d:Tx(i,r,ma),fill:"none",stroke:i.color,strokeWidth:2},`out-${l}`)),o.jsx("circle",{cx:s,cy:r,r:Ax+1.5,className:"fill-canvas"}),o.jsx("circle",{cx:s,cy:r,r:Ax,fill:e.color,stroke:"var(--color-canvas)",strokeWidth:1})]})}function kL(e){const t=Math.floor(Date.now()/1e3)-e;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:t<31536e3?`${Math.floor(t/2592e3)}mo ago`:`${Math.floor(t/31536e3)}y ago`}function CL({commit:e,onClose:t}){const n=r=>r.startsWith("tag:");return o.jsxs("aside",{"aria-label":"commit detail",className:"flex w-80 shrink-0 flex-col gap-3 overflow-y-auto border-l border-border bg-surface p-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e.summary}),o.jsx("button",{type:"button","aria-label":"close commit detail",onClick:t,className:"shrink-0 text-muted hover:text-content",children:"×"})]}),o.jsxs("dl",{className:"flex flex-col gap-2 text-xs",children:[o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Hash"}),o.jsx("dd",{children:o.jsx("code",{className:"text-content break-all",children:e.hash})})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Author"}),o.jsx("dd",{className:"text-content",children:e.author})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Date"}),o.jsx("dd",{className:"text-content",children:new Date(e.timestamp*1e3).toLocaleString()})]}),e.parents.length>0&&o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Parents"}),o.jsx("dd",{className:"flex flex-col gap-0.5",children:e.parents.map(r=>o.jsx("code",{className:"text-content",children:r.slice(0,8)},r))})]}),e.refs.length>0&&o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Refs"}),o.jsx("dd",{className:"flex flex-wrap gap-1",children:e.refs.map(r=>o.jsx("span",{className:U("rounded px-1 py-0.5 text-xs font-medium text-base",n(r)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:r},r))})]})]})]})}function jL({projectId:e}){const t=wL(e),[n,r]=g.useState(null),s=n!=null?t.commits.find(a=>a.hash===n)??null:null,i=t.rows.reduce((a,c)=>Math.max(a,c.laneCount),1),l=a=>a.startsWith("tag:");return o.jsxs("div",{className:"flex flex-1 overflow-hidden","aria-label":"git graph",children:[o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:"Git Graph"}),t.busy&&o.jsx(Me,{size:14}),o.jsx("button",{type:"button","aria-label":"refresh git graph",onClick:()=>void t.refresh(),disabled:t.busy,className:"ml-auto text-xs text-muted hover:text-content disabled:opacity-40",children:"Refresh"})]}),t.error&&o.jsx("p",{role:"alert",className:"mx-3 mt-2 shrink-0 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger",children:t.error}),o.jsxs("div",{className:"flex-1 overflow-y-auto",role:"list","aria-label":"commits",children:[t.rows.length===0&&!t.busy&&o.jsx("p",{className:"p-4 text-sm text-muted",children:"No commits found."}),t.rows.map(a=>{const c=a.commit.hash===n;return o.jsxs("div",{role:"listitem","aria-label":`commit ${a.commit.hash.slice(0,8)}: ${a.commit.summary}`,onClick:()=>r(c?null:a.commit.hash),className:U("flex cursor-pointer items-center gap-2 border-b border-border/50 px-2 hover:bg-raised",c&&"bg-raised"),style:{height:ma},children:[o.jsx(SL,{row:a,laneCount:i}),a.commit.refs.length>0&&o.jsx("div",{className:"flex shrink-0 flex-wrap gap-1",children:a.commit.refs.map(u=>o.jsx("span",{className:U("rounded px-1 py-0.5 text-xs font-medium",l(u)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:u},u))}),o.jsx("code",{className:"shrink-0 text-xs text-faint",children:a.commit.hash.slice(0,8)}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:a.commit.summary}),o.jsx("span",{className:"shrink-0 text-xs text-muted",children:a.commit.author}),o.jsx("span",{className:"shrink-0 text-xs text-faint",children:kL(a.commit.timestamp)})]},a.commit.hash)})]})]}),s&&o.jsx(CL,{commit:s,onClose:()=>r(null)})]})}function Mo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NL(){const{project:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useCallback(async()=>{h(!0),c(null);try{n(await e.listProjects())}catch(v){c(Mo(v))}finally{h(!1)}},[e]);g.useEffect(()=>{d()},[d]);const f=g.useCallback(v=>{s(_=>_.some(y=>y.id===v.id)?_:[..._,v]),l(v.id)},[]),p=g.useCallback(async v=>{h(!0),c(null);try{const _=await e.openProject(v);f(_)}catch(_){c(Mo(_))}finally{h(!1)}},[e,f]),m=g.useCallback(async(v,_)=>{h(!0),c(null);try{const y=await e.createProject(v,_);n(b=>[...b,y]),f(y)}catch(y){c(Mo(y))}finally{h(!1)}},[e,f]),x=g.useCallback(async v=>{c(null);try{await e.closeProject(v)}catch(_){c(Mo(_))}s(_=>{const y=_.filter(b=>b.id!==v);return l(b=>b===v?y.at(-1)?.id??null:b),y})},[e]),w=g.useCallback(v=>{l(v)},[]);return{projects:t,openTabs:r,activeTabId:i,error:a,busy:u,refresh:d,createProject:m,openProject:p,closeTab:x,activateTab:w}}function EL({items:e,activeTabId:t,onSelect:n,onClose:r,projectsPanelOpen:s,onOpenProjectsPanel:i,className:l}){return o.jsxs("div",{className:U("flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",l),children:[e.length===0?o.jsx("p",{className:"px-2 text-sm text-muted",children:"No open tabs."}):o.jsx(WP,{items:e,value:t,onSelect:n,onClose:r}),o.jsx(M,{size:"sm",variant:"secondary",onClick:i,"aria-label":"open projects panel","aria-pressed":s,title:"Ajouter un projet",className:U("shrink-0",s&&"ring-1 ring-border-strong"),children:"+"})]})}function PL(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const AL=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,TL=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,LL={};function Lx(e,t){return(LL.jsx?TL:AL).test(e)}const DL=/[ \t\n\f\r]/g;function RL(e){return typeof e=="object"?e.type==="text"?Dx(e.value):!1:Dx(e)}function Dx(e){return e.replace(DL,"")===""}class to{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}to.prototype.normal={};to.prototype.property={};to.prototype.space=void 0;function Rw(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new to(n,r,t)}function Hh(e){return e.toLowerCase()}class Qt{constructor(t,n){this.attribute=n,this.property=t}}Qt.prototype.attribute="";Qt.prototype.booleanish=!1;Qt.prototype.boolean=!1;Qt.prototype.commaOrSpaceSeparated=!1;Qt.prototype.commaSeparated=!1;Qt.prototype.defined=!1;Qt.prototype.mustUseProperty=!1;Qt.prototype.number=!1;Qt.prototype.overloadedBoolean=!1;Qt.prototype.property="";Qt.prototype.spaceSeparated=!1;Qt.prototype.space=void 0;let ML=0;const ve=Es(),tt=Es(),Uh=Es(),Z=Es(),De=Es(),gs=Es(),tn=Es();function Es(){return 2**++ML}const qh=Object.freeze(Object.defineProperty({__proto__:null,boolean:ve,booleanish:tt,commaOrSpaceSeparated:tn,commaSeparated:gs,number:Z,overloadedBoolean:Uh,spaceSeparated:De},Symbol.toStringTag,{value:"Module"})),Bu=Object.keys(qh);class _p extends Qt{constructor(t,n,r,s){let i=-1;if(super(t,n),Rx(this,"space",s),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&FL.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Mx,HL);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Mx.test(i)){let l=i.replace(zL,WL);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}s=_p}return new s(r,t)}function WL(e){return"-"+e.toLowerCase()}function HL(e){return e.charAt(1).toUpperCase()}const UL=Rw([Mw,IL,Bw,zw,Fw],"html"),yp=Rw([Mw,OL,Bw,zw,Fw],"svg");function qL(e){return e.join(" ").trim()}var bp={},Ix=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,VL=/\n/g,KL=/^\s*/,GL=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,YL=/^:\s*/,XL=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,QL=/^[;\s]*/,JL=/^\s+|\s+$/g,ZL=` -`,Ox="/",Bx="*",os="",eD="comment",tD="declaration";function nD(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function s(m){var x=m.match(VL);x&&(n+=x.length);var w=m.lastIndexOf(ZL);r=~w?m.length-w:r+m.length}function i(){var m={line:n,column:r};return function(x){return x.position=new l(m),u(),x}}function l(m){this.start=m,this.end={line:n,column:r},this.source=t.source}l.prototype.content=e;function a(m){var x=new Error(t.source+":"+n+":"+r+": "+m);if(x.reason=m,x.filename=t.source,x.line=n,x.column=r,x.source=e,!t.silent)throw x}function c(m){var x=m.exec(e);if(x){var w=x[0];return s(w),e=e.slice(w.length),x}}function u(){c(KL)}function h(m){var x;for(m=m||[];x=d();)x!==!1&&m.push(x);return m}function d(){var m=i();if(!(Ox!=e.charAt(0)||Bx!=e.charAt(1))){for(var x=2;os!=e.charAt(x)&&(Bx!=e.charAt(x)||Ox!=e.charAt(x+1));)++x;if(x+=2,os===e.charAt(x-1))return a("End of comment missing");var w=e.slice(2,x-2);return r+=2,s(w),e=e.slice(x),r+=2,m({type:eD,comment:w})}}function f(){var m=i(),x=c(GL);if(x){if(d(),!c(YL))return a("property missing ':'");var w=c(XL),v=m({type:tD,property:zx(x[0].replace(Ix,os)),value:w?zx(w[0].replace(Ix,os)):os});return c(QL),v}}function p(){var m=[];h(m);for(var x;x=f();)x!==!1&&(m.push(x),h(m));return m}return u(),p()}function zx(e){return e?e.replace(JL,os):os}var rD=nD,sD=_a&&_a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(bp,"__esModule",{value:!0});bp.default=lD;const iD=sD(rD);function lD(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,iD.default)(e),s=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:l,value:a}=i;s?t(l,a,i):a&&(n=n||{},n[l]=a)}),n}var jc={};Object.defineProperty(jc,"__esModule",{value:!0});jc.camelCase=void 0;var oD=/^--[a-zA-Z0-9_-]+$/,aD=/-([a-z])/g,cD=/^[^-]+$/,uD=/^-(webkit|moz|ms|o|khtml)-/,dD=/^-(ms)-/,hD=function(e){return!e||cD.test(e)||oD.test(e)},fD=function(e,t){return t.toUpperCase()},Fx=function(e,t){return"".concat(t,"-")},pD=function(e,t){return t===void 0&&(t={}),hD(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(dD,Fx):e=e.replace(uD,Fx),e.replace(aD,fD))};jc.camelCase=pD;var mD=_a&&_a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},gD=mD(bp),xD=jc;function Vh(e,t){var n={};return!e||typeof e!="string"||(0,gD.default)(e,function(r,s){r&&s&&(n[(0,xD.camelCase)(r,t)]=s)}),n}Vh.default=Vh;var vD=Vh;const _D=nf(vD),$w=Ww("end"),wp=Ww("start");function Ww(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function yD(e){const t=wp(e),n=$w(e);if(t&&n)return{start:t,end:n}}function _l(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?$x(e.position):"start"in e||"end"in e?$x(e):"line"in e||"column"in e?Kh(e):""}function Kh(e){return Wx(e&&e.line)+":"+Wx(e&&e.column)}function $x(e){return Kh(e&&e.start)+"-"+Kh(e&&e.end)}function Wx(e){return e&&typeof e=="number"?e:1}class Lt extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?s=t:!i.cause&&t&&(l=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const a=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=_l(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=l&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Lt.prototype.file="";Lt.prototype.name="";Lt.prototype.reason="";Lt.prototype.message="";Lt.prototype.stack="";Lt.prototype.column=void 0;Lt.prototype.line=void 0;Lt.prototype.ancestors=void 0;Lt.prototype.cause=void 0;Lt.prototype.fatal=void 0;Lt.prototype.place=void 0;Lt.prototype.ruleId=void 0;Lt.prototype.source=void 0;const Sp={}.hasOwnProperty,bD=new Map,wD=/[A-Z]/g,SD=new Set(["table","tbody","thead","tfoot","tr"]),kD=new Set(["td","th"]),Hw="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function CD(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=DD(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=LD(n,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?yp:UL,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Uw(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function Uw(e,t,n){if(t.type==="element")return jD(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return ND(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return PD(e,t,n);if(t.type==="mdxjsEsm")return ED(e,t);if(t.type==="root")return AD(e,t,n);if(t.type==="text")return TD(e,t)}function jD(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=yp,e.schema=s),e.ancestors.push(t);const i=Vw(e,t.tagName,!1),l=RD(e,t);let a=Cp(e,t);return SD.has(t.tagName)&&(a=a.filter(function(c){return typeof c=="string"?!RL(c):!0})),qw(e,l,i,t),kp(l,a),e.ancestors.pop(),e.schema=r,e.create(t,i,l,n)}function ND(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Hl(e,t.position)}function ED(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Hl(e,t.position)}function PD(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=yp,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:Vw(e,t.name,!0),l=MD(e,t),a=Cp(e,t);return qw(e,l,i,t),kp(l,a),e.ancestors.pop(),e.schema=r,e.create(t,i,l,n)}function AD(e,t,n){const r={};return kp(r,Cp(e,t)),e.create(t,e.Fragment,r,n)}function TD(e,t){return t.value}function qw(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function kp(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function LD(e,t,n){return r;function r(s,i,l,a){const u=Array.isArray(l.children)?n:t;return a?u(i,l,a):u(i,l)}}function DD(e,t){return n;function n(r,s,i,l){const a=Array.isArray(i.children),c=wp(r);return t(s,i,l,a,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function RD(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&Sp.call(t.properties,s)){const i=ID(e,s,t.properties[s]);if(i){const[l,a]=i;e.tableCellAlignToStyle&&l==="align"&&typeof a=="string"&&kD.has(t.tagName)?r=a:n[l]=a}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function MD(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const a=l.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Hl(e,t.position);else{const s=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const a=r.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else Hl(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function Cp(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:bD;for(;++rs?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),e.splice(...l);else for(n&&e.splice(t,n);i0?(on(e,e.length,0,t),e):t}const qx={}.hasOwnProperty;function Gw(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ln(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const It=Gr(/[A-Za-z]/),At=Gr(/[\dA-Za-z]/),qD=Gr(/[#-'*+\--9=?A-Z^-~]/);function nc(e){return e!==null&&(e<32||e===127)}const Gh=Gr(/\d/),VD=Gr(/[\dA-Fa-f]/),KD=Gr(/[!-/:-@[-`{-~]/);function de(e){return e!==null&&e<-2}function Re(e){return e!==null&&(e<0||e===32)}function we(e){return e===-2||e===-1||e===32}const Nc=Gr(/\p{P}|\p{S}/u),ks=Gr(/\s/);function Gr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ji(e){const t=[];let n=-1,r=0,s=0;for(;++n55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(l=String.fromCharCode(i,a),s=1):l="�"}else l=String.fromCharCode(i);l&&(t.push(e.slice(r,n),encodeURIComponent(l)),r=n+s+1,l=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function je(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return we(c)?(e.enter(n),a(c)):t(c)}function a(c){return we(c)&&i++l))return;const N=t.events.length;let L=N,A,k;for(;L--;)if(t.events[L][0]==="exit"&&t.events[L][1].type==="chunkFlow"){if(A){k=t.events[L][1].end;break}A=!0}for(v(r),S=N;Sy;){const C=n[b];t.containerState=C[1],C[0].exit.call(t,e)}n.length=y}function _(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function JD(e,t,n){return je(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function vi(e){if(e===null||Re(e)||ks(e))return 1;if(Nc(e))return 2}function Ec(e,t,n){const r=[];let s=-1;for(;++s1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},f={...e[n][1].start};Kx(d,-c),Kx(f,c),l={type:c>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},a={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},i={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},s={type:c>1?"strong":"emphasis",start:{...l.start},end:{...a.end}},e[r][1].end={...l.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=xn(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=xn(u,[["enter",s,t],["enter",l,t],["exit",l,t],["enter",i,t]]),u=xn(u,Ec(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=xn(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(h=2,u=xn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):h=0,on(e,r-1,n-r+3,u),n=r+u.length-h-2;break}}for(n=-1;++n0&&we(S)?je(e,_,"linePrefix",i+1)(S):_(S)}function _(S){return S===null||de(S)?e.check(Gx,x,b)(S):(e.enter("codeFlowValue"),y(S))}function y(S){return S===null||de(S)?(e.exit("codeFlowValue"),_(S)):(e.consume(S),y)}function b(S){return e.exit("codeFenced"),t(S)}function C(S,N,L){let A=0;return k;function k(I){return S.enter("lineEnding"),S.consume(I),S.exit("lineEnding"),D}function D(I){return S.enter("codeFencedFence"),we(I)?je(S,R,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):R(I)}function R(I){return I===a?(S.enter("codeFencedFenceSequence"),E(I)):L(I)}function E(I){return I===a?(A++,S.consume(I),E):A>=l?(S.exit("codeFencedFenceSequence"),we(I)?je(S,O,"whitespace")(I):O(I)):L(I)}function O(I){return I===null||de(I)?(S.exit("codeFencedFence"),N(I)):L(I)}}}function uR(e,t,n){const r=this;return s;function s(l){return l===null?n(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const Fu={name:"codeIndented",tokenize:hR},dR={partial:!0,tokenize:fR};function hR(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),je(e,i,"linePrefix",5)(u)}function i(u){const h=r.events[r.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(u):n(u)}function l(u){return u===null?c(u):de(u)?e.attempt(dR,l,c)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||de(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),a)}function c(u){return e.exit("codeIndented"),t(u)}}function fR(e,t,n){const r=this;return s;function s(l){return r.parser.lazy[r.now().line]?n(l):de(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s):je(e,i,"linePrefix",5)(l)}function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(l):de(l)?s(l):n(l)}}const pR={name:"codeText",previous:gR,resolve:mR,tokenize:xR};function mR(e){let t=e.length-4,n=3,r,s;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const s=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return r&&Xi(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Xi(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Xi(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):e.interrupt(r.parser.constructs.flow,n,t)(l)}}function eS(e,t,n,r,s,i,l,a,c){const u=c||Number.POSITIVE_INFINITY;let h=0;return d;function d(v){return v===60?(e.enter(r),e.enter(s),e.enter(i),e.consume(v),e.exit(i),f):v===null||v===32||v===41||nc(v)?n(v):(e.enter(r),e.enter(l),e.enter(a),e.enter("chunkString",{contentType:"string"}),x(v))}function f(v){return v===62?(e.enter(i),e.consume(v),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(a),f(v)):v===null||v===60||de(v)?n(v):(e.consume(v),v===92?m:p)}function m(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function x(v){return!h&&(v===null||v===41||Re(v))?(e.exit("chunkString"),e.exit(a),e.exit(l),e.exit(r),t(v)):h999||p===null||p===91||p===93&&!c||p===94&&!a&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(e.exit(i),e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):de(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||de(p)||a++>999?(e.exit("chunkString"),h(p)):(e.consume(p),c||(c=!we(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),a++,d):d(p)}}function nS(e,t,n,r,s,i){let l;return a;function a(f){return f===34||f===39||f===40?(e.enter(r),e.enter(s),e.consume(f),e.exit(s),l=f===40?41:f,c):n(f)}function c(f){return f===l?(e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):(e.enter(i),u(f))}function u(f){return f===l?(e.exit(i),c(l)):f===null?n(f):de(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),je(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===l||f===null||de(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:h)}function d(f){return f===l||f===92?(e.consume(f),h):h(f)}}function yl(e,t){let n;return r;function r(s){return de(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):we(s)?je(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const CR={name:"definition",tokenize:NR},jR={partial:!0,tokenize:ER};function NR(e,t,n){const r=this;let s;return i;function i(p){return e.enter("definition"),l(p)}function l(p){return tS.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return s=Ln(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),c):n(p)}function c(p){return Re(p)?yl(e,u)(p):u(p)}function u(p){return eS(e,h,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(jR,d,d)(p)}function d(p){return we(p)?je(e,f,"whitespace")(p):f(p)}function f(p){return p===null||de(p)?(e.exit("definition"),r.parser.defined.push(s),t(p)):n(p)}}function ER(e,t,n){return r;function r(a){return Re(a)?yl(e,s)(a):n(a)}function s(a){return nS(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return we(a)?je(e,l,"whitespace")(a):l(a)}function l(a){return a===null||de(a)?t(a):n(a)}}const PR={name:"hardBreakEscape",tokenize:AR};function AR(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return de(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const TR={name:"headingAtx",resolve:LR,tokenize:DR};function LR(e,t){let n=e.length-2,r=3,s,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(s={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},on(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function DR(e,t,n){let r=0;return s;function s(h){return e.enter("atxHeading"),i(h)}function i(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&r++<6?(e.consume(h),l):h===null||Re(h)?(e.exit("atxHeadingSequence"),a(h)):n(h)}function a(h){return h===35?(e.enter("atxHeadingSequence"),c(h)):h===null||de(h)?(e.exit("atxHeading"),t(h)):we(h)?je(e,a,"whitespace")(h):(e.enter("atxHeadingText"),u(h))}function c(h){return h===35?(e.consume(h),c):(e.exit("atxHeadingSequence"),a(h))}function u(h){return h===null||h===35||Re(h)?(e.exit("atxHeadingText"),a(h)):(e.consume(h),u)}}const RR=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Xx=["pre","script","style","textarea"],MR={concrete:!0,name:"htmlFlow",resolveTo:BR,tokenize:zR},IR={partial:!0,tokenize:$R},OR={partial:!0,tokenize:FR};function BR(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function zR(e,t,n){const r=this;let s,i,l,a,c;return u;function u(T){return h(T)}function h(T){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(T),d}function d(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),i=!0,x):T===63?(e.consume(T),s=3,r.interrupt?t:j):It(T)?(e.consume(T),l=String.fromCharCode(T),w):n(T)}function f(T){return T===45?(e.consume(T),s=2,p):T===91?(e.consume(T),s=5,a=0,m):It(T)?(e.consume(T),s=4,r.interrupt?t:j):n(T)}function p(T){return T===45?(e.consume(T),r.interrupt?t:j):n(T)}function m(T){const re="CDATA[";return T===re.charCodeAt(a++)?(e.consume(T),a===re.length?r.interrupt?t:R:m):n(T)}function x(T){return It(T)?(e.consume(T),l=String.fromCharCode(T),w):n(T)}function w(T){if(T===null||T===47||T===62||Re(T)){const re=T===47,ee=l.toLowerCase();return!re&&!i&&Xx.includes(ee)?(s=1,r.interrupt?t(T):R(T)):RR.includes(l.toLowerCase())?(s=6,re?(e.consume(T),v):r.interrupt?t(T):R(T)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(T):i?_(T):y(T))}return T===45||At(T)?(e.consume(T),l+=String.fromCharCode(T),w):n(T)}function v(T){return T===62?(e.consume(T),r.interrupt?t:R):n(T)}function _(T){return we(T)?(e.consume(T),_):k(T)}function y(T){return T===47?(e.consume(T),k):T===58||T===95||It(T)?(e.consume(T),b):we(T)?(e.consume(T),y):k(T)}function b(T){return T===45||T===46||T===58||T===95||At(T)?(e.consume(T),b):C(T)}function C(T){return T===61?(e.consume(T),S):we(T)?(e.consume(T),C):y(T)}function S(T){return T===null||T===60||T===61||T===62||T===96?n(T):T===34||T===39?(e.consume(T),c=T,N):we(T)?(e.consume(T),S):L(T)}function N(T){return T===c?(e.consume(T),c=null,A):T===null||de(T)?n(T):(e.consume(T),N)}function L(T){return T===null||T===34||T===39||T===47||T===60||T===61||T===62||T===96||Re(T)?C(T):(e.consume(T),L)}function A(T){return T===47||T===62||we(T)?y(T):n(T)}function k(T){return T===62?(e.consume(T),D):n(T)}function D(T){return T===null||de(T)?R(T):we(T)?(e.consume(T),D):n(T)}function R(T){return T===45&&s===2?(e.consume(T),W):T===60&&s===1?(e.consume(T),G):T===62&&s===4?(e.consume(T),se):T===63&&s===3?(e.consume(T),j):T===93&&s===5?(e.consume(T),z):de(T)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(IR,q,E)(T)):T===null||de(T)?(e.exit("htmlFlowData"),E(T)):(e.consume(T),R)}function E(T){return e.check(OR,O,q)(T)}function O(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),I}function I(T){return T===null||de(T)?E(T):(e.enter("htmlFlowData"),R(T))}function W(T){return T===45?(e.consume(T),j):R(T)}function G(T){return T===47?(e.consume(T),l="",P):R(T)}function P(T){if(T===62){const re=l.toLowerCase();return Xx.includes(re)?(e.consume(T),se):R(T)}return It(T)&&l.length<8?(e.consume(T),l+=String.fromCharCode(T),P):R(T)}function z(T){return T===93?(e.consume(T),j):R(T)}function j(T){return T===62?(e.consume(T),se):T===45&&s===2?(e.consume(T),j):R(T)}function se(T){return T===null||de(T)?(e.exit("htmlFlowData"),q(T)):(e.consume(T),se)}function q(T){return e.exit("htmlFlow"),t(T)}}function FR(e,t,n){const r=this;return s;function s(l){return de(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i):n(l)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function $R(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(no,t,n)}}const WR={name:"htmlText",tokenize:HR};function HR(e,t,n){const r=this;let s,i,l;return a;function a(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),c}function c(j){return j===33?(e.consume(j),u):j===47?(e.consume(j),C):j===63?(e.consume(j),y):It(j)?(e.consume(j),L):n(j)}function u(j){return j===45?(e.consume(j),h):j===91?(e.consume(j),i=0,m):It(j)?(e.consume(j),_):n(j)}function h(j){return j===45?(e.consume(j),p):n(j)}function d(j){return j===null?n(j):j===45?(e.consume(j),f):de(j)?(l=d,G(j)):(e.consume(j),d)}function f(j){return j===45?(e.consume(j),p):d(j)}function p(j){return j===62?W(j):j===45?f(j):d(j)}function m(j){const se="CDATA[";return j===se.charCodeAt(i++)?(e.consume(j),i===se.length?x:m):n(j)}function x(j){return j===null?n(j):j===93?(e.consume(j),w):de(j)?(l=x,G(j)):(e.consume(j),x)}function w(j){return j===93?(e.consume(j),v):x(j)}function v(j){return j===62?W(j):j===93?(e.consume(j),v):x(j)}function _(j){return j===null||j===62?W(j):de(j)?(l=_,G(j)):(e.consume(j),_)}function y(j){return j===null?n(j):j===63?(e.consume(j),b):de(j)?(l=y,G(j)):(e.consume(j),y)}function b(j){return j===62?W(j):y(j)}function C(j){return It(j)?(e.consume(j),S):n(j)}function S(j){return j===45||At(j)?(e.consume(j),S):N(j)}function N(j){return de(j)?(l=N,G(j)):we(j)?(e.consume(j),N):W(j)}function L(j){return j===45||At(j)?(e.consume(j),L):j===47||j===62||Re(j)?A(j):n(j)}function A(j){return j===47?(e.consume(j),W):j===58||j===95||It(j)?(e.consume(j),k):de(j)?(l=A,G(j)):we(j)?(e.consume(j),A):W(j)}function k(j){return j===45||j===46||j===58||j===95||At(j)?(e.consume(j),k):D(j)}function D(j){return j===61?(e.consume(j),R):de(j)?(l=D,G(j)):we(j)?(e.consume(j),D):A(j)}function R(j){return j===null||j===60||j===61||j===62||j===96?n(j):j===34||j===39?(e.consume(j),s=j,E):de(j)?(l=R,G(j)):we(j)?(e.consume(j),R):(e.consume(j),O)}function E(j){return j===s?(e.consume(j),s=void 0,I):j===null?n(j):de(j)?(l=E,G(j)):(e.consume(j),E)}function O(j){return j===null||j===34||j===39||j===60||j===61||j===96?n(j):j===47||j===62||Re(j)?A(j):(e.consume(j),O)}function I(j){return j===47||j===62||Re(j)?A(j):n(j)}function W(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):n(j)}function G(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),P}function P(j){return we(j)?je(e,z,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):z(j)}function z(j){return e.enter("htmlTextData"),l(j)}}const Ep={name:"labelEnd",resolveAll:KR,resolveTo:GR,tokenize:YR},UR={tokenize:XR},qR={tokenize:QR},VR={tokenize:JR};function KR(e){let t=-1;const n=[];for(;++t=3&&(u===null||de(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===s?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),we(u)?je(e,a,"whitespace")(u):a(u))}}const Ht={continuation:{tokenize:aM},exit:uM,name:"list",tokenize:oM},iM={partial:!0,tokenize:dM},lM={partial:!0,tokenize:cM};function oM(e,t,n){const r=this,s=r.events[r.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,l=0;return a;function a(p){const m=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Gh(p)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(ga,n,u)(p):u(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(p)}return n(p)}function c(p){return Gh(p)&&++l<10?(e.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(no,r.interrupt?n:h,e.attempt(iM,f,d))}function h(p){return r.containerState.initialBlankLine=!0,i++,f(p)}function d(p){return we(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function aM(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(no,s,i);function s(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,je(e,t,"listItemIndent",r.containerState.size+1)(a)}function i(a){return r.containerState.furtherBlankLines||!we(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(lM,t,l)(a))}function l(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,je(e,e.attempt(Ht,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function cM(e,t,n){const r=this;return je(e,s,"listItemIndent",r.containerState.size+1);function s(i){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(i):n(i)}}function uM(e){e.exit(this.containerState.type)}function dM(e,t,n){const r=this;return je(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const l=r.events[r.events.length-1];return!we(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Qx={name:"setextUnderline",resolveTo:hM,tokenize:fM};function hM(e,t){let n=e.length,r,s,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(s=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const l={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",l,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=l,e.push(["exit",l,t]),e}function fM(e,t,n){const r=this;let s;return i;function i(u){let h=r.events.length,d;for(;h--;)if(r.events[h][1].type!=="lineEnding"&&r.events[h][1].type!=="linePrefix"&&r.events[h][1].type!=="content"){d=r.events[h][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),s=u,l(u)):n(u)}function l(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===s?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),we(u)?je(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||de(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const pM={tokenize:mM};function mM(e){const t=this,n=e.attempt(no,r,e.attempt(this.parser.constructs.flowInitial,s,je(e,e.attempt(this.parser.constructs.flow,s,e.attempt(yR,s)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const gM={resolveAll:sS()},xM=rS("string"),vM=rS("text");function rS(e){return{resolveAll:sS(e==="text"?_M:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,l,a);return l;function l(h){return u(h)?i(h):a(h)}function a(h){if(h===null){n.consume(h);return}return n.enter("data"),n.consume(h),c}function c(h){return u(h)?(n.exit("data"),i(h)):(n.consume(h),c)}function u(h){if(h===null)return!0;const d=s[h];let f=-1;if(d)for(;++f-1){const a=l[0];typeof a=="string"?l[0]=a.slice(r):l.shift()}i>0&&l.push(e[s].slice(0,i))}return l}function LM(e,t){let n=-1;const r=[];let s;for(;++n0){const kn=xe.tokenStack[xe.tokenStack.length-1];(kn[1]||Zx).call(xe,void 0,kn[0])}for(te.position={start:wr(H.length>0?H[0][1].start:{line:1,column:1,offset:0}),end:wr(H.length>0?H[H.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le0&&(r.className=["language-"+s[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function VM(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function KM(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function GM(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),s=ji(r.toLowerCase()),i=e.footnoteOrder.indexOf(r);let l,a=e.footnoteCounts.get(r);a===void 0?(a=0,e.footnoteOrder.push(r),l=e.footnoteOrder.length):l=i+1,a+=1,e.footnoteCounts.set(r,a);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+s,id:n+"fnref-"+s+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function YM(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function XM(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function oS(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const s=e.all(t),i=s[0];i&&i.type==="text"?i.value="["+i.value:s.unshift({type:"text",value:"["});const l=s[s.length-1];return l&&l.type==="text"?l.value+=r:s.push({type:"text",value:r}),s}function QM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return oS(e,t);const s={src:ji(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(t,i),e.applyData(t,i)}function JM(e,t){const n={src:ji(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function ZM(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function eI(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return oS(e,t);const s={href:ji(r.url||"")};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"a",properties:s,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tI(e,t){const n={href:ji(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function nI(e,t,n){const r=e.all(t),s=n?rI(n):aS(t),i={},l=[];if(typeof t.checked=="boolean"){const h=r[0];let d;h&&h.type==="element"&&h.tagName==="p"?d=h:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let a=-1;for(;++a1}function sI(e,t){const n={},r=e.all(t);let s=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++s0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},a=wp(t.children[1]),c=$w(t.children[t.children.length-1]);a&&c&&(l.position={start:a,end:c}),s.push(l)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function cI(e,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,a=l?l.length:t.children.length;let c=-1;const u=[];for(;++c0,!0),r[0]),s=r.index+r[0].length,r=n.exec(t);return i.push(nv(t.slice(s),s>0,!1)),i.join("")}function nv(e,t,n){let r=0,s=e.length;if(t){let i=e.codePointAt(r);for(;i===ev||i===tv;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(s-1);for(;i===ev||i===tv;)s--,i=e.codePointAt(s-1)}return s>r?e.slice(r,s):""}function hI(e,t){const n={type:"text",value:dI(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function fI(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const pI={blockquote:HM,break:UM,code:qM,delete:VM,emphasis:KM,footnoteReference:GM,heading:YM,html:XM,imageReference:QM,image:JM,inlineCode:ZM,linkReference:eI,link:tI,listItem:nI,list:sI,paragraph:iI,root:lI,strong:oI,table:aI,tableCell:uI,tableRow:cI,text:hI,thematicBreak:fI,toml:Io,yaml:Io,definition:Io,footnoteDefinition:Io};function Io(){}const cS=-1,Pc=0,bl=1,rc=2,Pp=3,Ap=4,Tp=5,Lp=6,uS=7,dS=8,mI=typeof self=="object"?self:globalThis,rv=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new mI[e](t)},gI=(e,t)=>{const n=(s,i)=>(e.set(i,s),s),r=s=>{if(e.has(s))return e.get(s);const[i,l]=t[s];switch(i){case Pc:case cS:return n(l,s);case bl:{const a=n([],s);for(const c of l)a.push(r(c));return a}case rc:{const a=n({},s);for(const[c,u]of l)a[r(c)]=r(u);return a}case Pp:return n(new Date(l),s);case Ap:{const{source:a,flags:c}=l;return n(new RegExp(a,c),s)}case Tp:{const a=n(new Map,s);for(const[c,u]of l)a.set(r(c),r(u));return a}case Lp:{const a=n(new Set,s);for(const c of l)a.add(r(c));return a}case uS:{const{name:a,message:c}=l;return n(rv(a,c),s)}case dS:return n(BigInt(l),s);case"BigInt":return n(Object(BigInt(l)),s);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:a}=new Uint8Array(l);return n(new DataView(a),l)}}return n(rv(i,l),s)};return r},sv=e=>gI(new Map,e)(0),Bs="",{toString:xI}={},{keys:vI}=Object,Qi=e=>{const t=typeof e;if(t!=="object"||!e)return[Pc,t];const n=xI.call(e).slice(8,-1);switch(n){case"Array":return[bl,Bs];case"Object":return[rc,Bs];case"Date":return[Pp,Bs];case"RegExp":return[Ap,Bs];case"Map":return[Tp,Bs];case"Set":return[Lp,Bs];case"DataView":return[bl,n]}return n.includes("Array")?[bl,n]:n.includes("Error")?[uS,n]:[rc,n]},Oo=([e,t])=>e===Pc&&(t==="function"||t==="symbol"),_I=(e,t,n,r)=>{const s=(l,a)=>{const c=r.push(l)-1;return n.set(a,c),c},i=l=>{if(n.has(l))return n.get(l);let[a,c]=Qi(l);switch(a){case Pc:{let h=l;switch(c){case"bigint":a=dS,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);h=null;break;case"undefined":return s([cS],l)}return s([a,h],l)}case bl:{if(c){let f=l;return c==="DataView"?f=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(f=new Uint8Array(l)),s([c,[...f]],l)}const h=[],d=s([a,h],l);for(const f of l)h.push(i(f));return d}case rc:{if(c)switch(c){case"BigInt":return s([c,l.toString()],l);case"Boolean":case"Number":case"String":return s([c,l.valueOf()],l)}if(t&&"toJSON"in l)return i(l.toJSON());const h=[],d=s([a,h],l);for(const f of vI(l))(e||!Oo(Qi(l[f])))&&h.push([i(f),i(l[f])]);return d}case Pp:return s([a,l.toISOString()],l);case Ap:{const{source:h,flags:d}=l;return s([a,{source:h,flags:d}],l)}case Tp:{const h=[],d=s([a,h],l);for(const[f,p]of l)(e||!(Oo(Qi(f))||Oo(Qi(p))))&&h.push([i(f),i(p)]);return d}case Lp:{const h=[],d=s([a,h],l);for(const f of l)(e||!Oo(Qi(f)))&&h.push(i(f));return d}}const{message:u}=l;return s([a,{name:c,message:u}],l)};return i},iv=(e,{json:t,lossy:n}={})=>{const r=[];return _I(!(t||n),!!t,new Map,r)(e),r},sc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?sv(iv(e,t)):structuredClone(e):(e,t)=>sv(iv(e,t));function yI(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function bI(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function wI(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||yI,r=e.options.footnoteBackLabel||bI,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let c=-1;for(;++c0&&m.push({type:"text",value:" "});let _=typeof n=="string"?n:n(c,p);typeof _=="string"&&(_={type:"text",value:_}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const w=h[h.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const _=w.children[w.children.length-1];_&&_.type==="text"?_.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...m)}else h.push(...m);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(h,!0)};e.patch(u,v),a.push(v)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...sc(l),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:` -`}]}}const Ac=function(e){if(e==null)return jI;if(typeof e=="function")return Tc(e);if(typeof e=="object")return Array.isArray(e)?SI(e):kI(e);if(typeof e=="string")return CI(e);throw new Error("Expected function, string, or object as test")};function SI(e){const t=[];let n=-1;for(;++n":""))+")"})}return f;function f(){let p=hS,m,x,w;if((!t||i(c,u,h[h.length-1]||void 0))&&(p=AI(n(c,h)),p[0]===Xh))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==PI)for(x=(r?v.children.length:-1)+l,w=h.concat(v);x>-1&&x0&&n.push({type:"text",value:` -`}),n}function lv(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function ov(e,t){const n=LI(e,t),r=n.one(e,void 0),s=wI(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return s&&i.children.push({type:"text",value:` -`},s),i}function OI(e,t){return e&&"run"in e?async function(n,r){const s=ov(n,{file:r,...t});await e.run(s,r)}:function(n,r){return ov(n,{file:r,...e||t})}}function av(e){if(e)throw e}var xa=Object.prototype.hasOwnProperty,pS=Object.prototype.toString,cv=Object.defineProperty,uv=Object.getOwnPropertyDescriptor,dv=function(t){return typeof Array.isArray=="function"?Array.isArray(t):pS.call(t)==="[object Array]"},hv=function(t){if(!t||pS.call(t)!=="[object Object]")return!1;var n=xa.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&xa.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var s;for(s in t);return typeof s>"u"||xa.call(t,s)},fv=function(t,n){cv&&n.name==="__proto__"?cv(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},pv=function(t,n){if(n==="__proto__")if(xa.call(t,n)){if(uv)return uv(t,n).value}else return;return t[n]},BI=function e(){var t,n,r,s,i,l,a=arguments[0],c=1,u=arguments.length,h=!1;for(typeof a=="boolean"&&(h=a,a=arguments[1]||{},c=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});cl.length;let c;a&&l.push(s);try{c=e.apply(this,l)}catch(u){const h=u;if(a&&n)throw h;return s(h)}a||(c&&c.then&&typeof c.then=="function"?c.then(i,s):c instanceof Error?s(c):i(c))}function s(l,...a){n||(n=!0,t(l,...a))}function i(l){s(null,l)}}const $n={basename:$I,dirname:WI,extname:HI,join:UI,sep:"/"};function $I(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ro(e);let n=0,r=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else r<0&&(i=!0,r=s+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,a=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else l<0&&(i=!0,l=s+1),a>-1&&(e.codePointAt(s)===t.codePointAt(a--)?a<0&&(r=s):(a=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function WI(e){if(ro(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function HI(e){ro(e);let t=e.length,n=-1,r=0,s=-1,i=0,l;for(;t--;){const a=e.codePointAt(t);if(a===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),a===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||n<0||i===0||i===1&&s===n-1&&s===r+1?"":e.slice(s,n)}function UI(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function VI(e,t){let n="",r=0,s=-1,i=0,l=-1,a,c;for(;++l<=e.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,i=0;continue}}else if(n.length>0){n="",r=0,s=l,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,i=0}else a===46&&i>-1?i++:i=-1}return n}function ro(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const KI={cwd:GI};function GI(){return"/"}function Zh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function YI(e){if(typeof e=="string")e=new URL(e);else if(!Zh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return XI(e)}function XI(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[p,...m]=h;const x=r[f][1];Jh(x)&&Jh(p)&&(p=Wu(!0,x,p)),r[f]=[u,p,...m]}}}}const e3=new Rp().freeze();function Vu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ku(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Gu(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function gv(e){if(!Jh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function xv(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Bo(e){return t3(e)?e:new mS(e)}function t3(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function n3(e){return typeof e=="string"||r3(e)}function r3(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const s3="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",vv=[],_v={allowDangerousHtml:!0},i3=/^(https?|ircs?|mailto|xmpp)$/i,l3=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function gS(e){const t=o3(e),n=a3(e);return c3(t.runSync(t.parse(n),n),e)}function o3(e){const t=e.rehypePlugins||vv,n=e.remarkPlugins||vv,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,..._v}:_v;return e3().use(WM).use(n).use(OI,r).use(t)}function a3(e){const t=e.children||"",n=new mS;return typeof t=="string"&&(n.value=t),n}function c3(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,l=t.skipHtml,a=t.unwrapDisallowed,c=t.urlTransform||u3;for(const h of l3)Object.hasOwn(t,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+s3+h.id,void 0);return Dp(e,u),CD(e,{Fragment:o.Fragment,components:s,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(h,d,f){if(h.type==="raw"&&f&&typeof d=="number")return l?f.children.splice(d,1):f.children[d]={type:"text",value:h.value},d;if(h.type==="element"){let p;for(p in zu)if(Object.hasOwn(zu,p)&&Object.hasOwn(h.properties,p)){const m=h.properties[p],x=zu[p];(x===null||x.includes(h.tagName))&&(h.properties[p]=c(String(m||""),p,h))}}if(h.type==="element"){let p=n?!n.includes(h.tagName):i?i.includes(h.tagName):!1;if(!p&&r&&typeof d=="number"&&(p=!r(h,d,f)),p&&f&&typeof d=="number")return a&&h.children?f.children.splice(d,1,...h.children):f.children.splice(d,1),d}}}function u3(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),s=e.indexOf("/");return t===-1||s!==-1&&t>s||n!==-1&&t>n||r!==-1&&t>r||i3.test(e.slice(0,t))?e:""}function yv(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,s=n.indexOf(t);for(;s!==-1;)r++,s=n.indexOf(t,s+t.length);return r}function d3(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function h3(e,t,n){const s=Ac((n||{}).ignore||[]),i=f3(t);let l=-1;for(;++l0?{type:"text",value:S}:void 0),S===!1?f.lastIndex=b+1:(m!==b&&_.push({type:"text",value:u.value.slice(m,b)}),Array.isArray(S)?_.push(...S):S&&_.push(S),m=b+y[0].length,v=!0),!f.global)break;y=f.exec(u.value)}return v?(m?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const s=yv(e,"(");let i=yv(e,")");for(;r!==-1&&s>i;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[e,n]}function xS(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||ks(n)||Nc(n))&&(!t||n!==47)}vS.peek=I3;function E3(){this.buffer()}function P3(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function A3(){this.buffer()}function T3(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function L3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ln(this.sliceSerialize(e)).toLowerCase(),n.label=t}function D3(e){this.exit(e)}function R3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ln(this.sliceSerialize(e)).toLowerCase(),n.label=t}function M3(e){this.exit(e)}function I3(){return"["}function vS(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const l=n.enter("footnoteReference"),a=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),a(),l(),i+=s.move("]"),i}function O3(){return{enter:{gfmFootnoteCallString:E3,gfmFootnoteCall:P3,gfmFootnoteDefinitionLabelString:A3,gfmFootnoteDefinition:T3},exit:{gfmFootnoteCallString:L3,gfmFootnoteCall:D3,gfmFootnoteDefinitionLabelString:R3,gfmFootnoteDefinition:M3}}}function B3(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:vS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,l){const a=i.createTracker(l);let c=a.move("[^");const u=i.enter("footnoteDefinition"),h=i.enter("label");return c+=a.move(i.safe(i.associationId(r),{before:c,after:"]"})),h(),c+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),c+=a.move((t?` -`:" ")+i.indentLines(i.containerFlow(r,a.current()),t?_S:z3))),u(),c}}function z3(e,t,n){return t===0?e:_S(e,t,n)}function _S(e,t,n){return(n?"":" ")+e}const F3=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];yS.peek=q3;function $3(){return{canContainEols:["delete"],enter:{strikethrough:H3},exit:{strikethrough:U3}}}function W3(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:F3}],handlers:{delete:yS}}}function H3(e){this.enter({type:"delete",children:[]},e)}function U3(e){this.exit(e)}function yS(e,t,n,r){const s=n.createTracker(r),i=n.enter("strikethrough");let l=s.move("~~");return l+=n.containerPhrasing(e,{...s.current(),before:l,after:"~"}),l+=s.move("~~"),i(),l}function q3(){return"~"}function V3(e){return e.length}function K3(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||V3,i=[],l=[],a=[],c=[];let u=0,h=-1;for(;++hu&&(u=e[h].length);++vc[v])&&(c[v]=y)}x.push(_)}l[h]=x,a[h]=w}let d=-1;if(typeof r=="object"&&"length"in r)for(;++dc[d]&&(c[d]=_),p[d]=_),f[d]=y}l.splice(1,0,f),a.splice(1,0,p),h=-1;const m=[];for(;++h "),i.shift(2);const l=n.indentLines(n.containerFlow(e,i.current()),X3);return s(),l}function X3(e,t,n){return">"+(n?"":" ")+e}function Q3(e,t){return wv(e,t.inConstruct,!0)&&!wv(e,t.notInConstruct,!1)}function wv(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++rl&&(l=i):i=1,s=r+t.length,r=n.indexOf(t,s);return l}function Z3(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function e5(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function t5(e,t,n,r){const s=e5(n),i=e.value||"",l=s==="`"?"GraveAccent":"Tilde";if(Z3(e,n)){const d=n.enter("codeIndented"),f=n.indentLines(i,n5);return d(),f}const a=n.createTracker(r),c=s.repeat(Math.max(J3(i,s)+1,3)),u=n.enter("codeFenced");let h=a.move(c);if(e.lang){const d=n.enter(`codeFencedLang${l}`);h+=a.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...a.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${l}`);h+=a.move(" "),h+=a.move(n.safe(e.meta,{before:h,after:` -`,encode:["`"],...a.current()})),d()}return h+=a.move(` -`),i&&(h+=a.move(i+` -`)),h+=a.move(c),u(),h}function n5(e,t,n){return(n?"":" ")+e}function Mp(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function r5(e,t,n,r){const s=Mp(n),i=s==='"'?"Quote":"Apostrophe",l=n.enter("definition");let a=n.enter("label");const c=n.createTracker(r);let u=c.move("[");return u+=c.move(n.safe(n.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),a(),!e.url||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(a=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":` -`,...c.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(n.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),a()),l(),u}function s5(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ul(e){return"&#x"+e.toString(16).toUpperCase()+";"}function ic(e,t,n){const r=vi(e),s=vi(t);return r===void 0?s===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}bS.peek=i5;function bS(e,t,n,r){const s=s5(n),i=n.enter("emphasis"),l=n.createTracker(r),a=l.move(s);let c=l.move(n.containerPhrasing(e,{after:s,before:a,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,s);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,s);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},a+c+p}function i5(e,t,n){return n.options.emphasis||"*"}function l5(e,t){let n=!1;return Dp(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Xh}),!!((!e.depth||e.depth<3)&&jp(e)&&(t.options.setext||n))}function o5(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(l5(e,n)){const h=n.enter("headingSetext"),d=n.enter("phrasing"),f=n.containerPhrasing(e,{...i.current(),before:` -`,after:` -`});return d(),h(),f+` -`+(s===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(` -`))+1))}const l="#".repeat(s),a=n.enter("headingAtx"),c=n.enter("phrasing");i.move(l+" ");let u=n.containerPhrasing(e,{before:"# ",after:` -`,...i.current()});return/^[\t ]/.test(u)&&(u=Ul(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,n.options.closeAtx&&(u+=" "+l),c(),a(),u}wS.peek=a5;function wS(e){return e.value||""}function a5(){return"<"}SS.peek=c5;function SS(e,t,n,r){const s=Mp(n),i=s==='"'?"Quote":"Apostrophe",l=n.enter("image");let a=n.enter("label");const c=n.createTracker(r);let u=c.move("![");return u+=c.move(n.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),a(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(a=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(n.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),a()),u+=c.move(")"),l(),u}function c5(){return"!"}kS.peek=u5;function kS(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let l=n.enter("label");const a=n.createTracker(r);let c=a.move("![");const u=n.safe(e.alt,{before:c,after:"]",...a.current()});c+=a.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...a.current()});return l(),n.stack=h,i(),s==="full"||!u||u!==d?c+=a.move(d+"]"):s==="shortcut"?c=c.slice(0,-1):c+=a.move("]"),c}function u5(){return"!"}CS.peek=d5;function CS(e,t,n){let r=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i\u007F]/.test(e.url))}NS.peek=h5;function NS(e,t,n,r){const s=Mp(n),i=s==='"'?"Quote":"Apostrophe",l=n.createTracker(r);let a,c;if(jS(e,n)){const h=n.stack;n.stack=[],a=n.enter("autolink");let d=l.move("<");return d+=l.move(n.containerPhrasing(e,{before:d,after:">",...l.current()})),d+=l.move(">"),a(),n.stack=h,d}a=n.enter("link"),c=n.enter("label");let u=l.move("[");return u+=l.move(n.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(c=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),c(),e.title&&(c=n.enter(`title${i}`),u+=l.move(" "+s),u+=l.move(n.safe(e.title,{before:u,after:s,...l.current()})),u+=l.move(s),c()),u+=l.move(")"),a(),u}function h5(e,t,n){return jS(e,n)?"<":"["}ES.peek=f5;function ES(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let l=n.enter("label");const a=n.createTracker(r);let c=a.move("[");const u=n.containerPhrasing(e,{before:c,after:"]",...a.current()});c+=a.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...a.current()});return l(),n.stack=h,i(),s==="full"||!u||u!==d?c+=a.move(d+"]"):s==="shortcut"?c=c.slice(0,-1):c+=a.move("]"),c}function f5(){return"["}function Ip(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function p5(e){const t=Ip(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function m5(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function PS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function g5(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let l=e.ordered?m5(n):Ip(n);const a=e.ordered?l==="."?")":".":p5(n);let c=t&&n.bulletLastUsed?l===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),PS(n)===l&&h){let d=-1;for(;++d-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let l=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(l=Math.ceil(l/4)*4);const a=n.createTracker(r);a.move(i+" ".repeat(l-i.length)),a.shift(l);const c=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,a.current()),h);return c(),u;function h(d,f,p){return f?(p?"":" ".repeat(l))+d:(p?i:i+" ".repeat(l-i.length))+d}}function _5(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),l=n.containerPhrasing(e,r);return i(),s(),l}const y5=Ac(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function b5(e,t,n,r){return(e.children.some(function(l){return y5(l)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function w5(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}AS.peek=S5;function AS(e,t,n,r){const s=w5(n),i=n.enter("strong"),l=n.createTracker(r),a=l.move(s+s);let c=l.move(n.containerPhrasing(e,{after:s,before:a,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,s);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,s);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},a+c+p}function S5(e,t,n){return n.options.strong||"*"}function k5(e,t,n,r){return n.safe(e.value,r)}function C5(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function j5(e,t,n){const r=(PS(n)+(n.options.ruleSpaces?" ":"")).repeat(C5(n));return n.options.ruleSpaces?r.slice(0,-1):r}const TS={blockquote:Y3,break:Sv,code:t5,definition:r5,emphasis:bS,hardBreak:Sv,heading:o5,html:wS,image:SS,imageReference:kS,inlineCode:CS,link:NS,linkReference:ES,list:g5,listItem:v5,paragraph:_5,root:b5,strong:AS,text:k5,thematicBreak:j5};function N5(){return{enter:{table:E5,tableData:kv,tableHeader:kv,tableRow:A5},exit:{codeText:T5,table:P5,tableData:Ju,tableHeader:Ju,tableRow:Ju}}}function E5(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function P5(e){this.exit(e),this.data.inTable=void 0}function A5(e){this.enter({type:"tableRow",children:[]},e)}function Ju(e){this.exit(e)}function kv(e){this.enter({type:"tableCell",children:[]},e)}function T5(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,L5));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function L5(e,t){return t==="|"?t:e}function D5(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:c,tableRow:a}};function l(p,m,x,w){return u(h(p,x,w),p.align)}function a(p,m,x,w){const v=d(p,x,w),_=u([v]);return _.slice(0,_.indexOf(` -`))}function c(p,m,x,w){const v=x.enter("tableCell"),_=x.enter("phrasing"),y=x.containerPhrasing(p,{...w,before:i,after:i});return _(),v(),y}function u(p,m){return K3(p,{align:m,alignDelimiters:r,padding:n,stringLength:s})}function h(p,m,x){const w=p.children;let v=-1;const _=[],y=m.enter("table");for(;++v0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const Q5={tokenize:iO,partial:!0};function J5(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:nO,continuation:{tokenize:rO},exit:sO}},text:{91:{name:"gfmFootnoteCall",tokenize:tO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Z5,resolveTo:eO}}}}function Z5(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let l;for(;s--;){const c=r.events[s][1];if(c.type==="labelImage"){l=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return a;function a(c){if(!l||!l._balanced)return n(c);const u=Ln(r.sliceSerialize({start:l.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function eO(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",l,t],["exit",l,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function tO(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,l;return a;function a(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),c}function c(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(i>999||d===93&&!l||d===null||d===91||Re(d))return n(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return s.includes(Ln(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return Re(d)||(l=!0),i++,e.consume(d),d===92?h:u}function h(d){return d===91||d===92||d===93?(e.consume(d),i++,u):u(d)}}function nO(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,l=0,a;return c;function c(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):n(m)}function h(m){if(l>999||m===93&&!a||m===null||m===91||Re(m))return n(m);if(m===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return i=Ln(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Re(m)||(a=!0),l++,e.consume(m),m===92?d:h}function d(m){return m===91||m===92||m===93?(e.consume(m),l++,h):h(m)}function f(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),s.includes(i)||s.push(i),je(e,p,"gfmFootnoteDefinitionWhitespace")):n(m)}function p(m){return t(m)}}function rO(e,t,n){return e.check(no,t,e.attempt(Q5,t,n))}function sO(e){e.exit("gfmFootnoteDefinition")}function iO(e,t,n){const r=this;return je(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const l=r.events[r.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?t(i):n(i)}}function lO(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(l,a){let c=-1;for(;++c1?c(m):(l.consume(m),d++,p);if(d<2&&!n)return c(m);const w=l.exit("strikethroughSequenceTemporary"),v=vi(m);return w._open=!v||v===2&&!!x,w._close=!x||x===2&&!!v,a(m)}}}class oO{constructor(){this.map=[]}add(t,n,r){aO(this,t,n,r)}consume(t){if(this.map.sort(function(i,l){return i[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function aO(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s-1;){const O=r.events[D][1].type;if(O==="lineEnding"||O==="linePrefix")D--;else break}const R=D>-1?r.events[D][1].type:null,E=R==="tableHead"||R==="tableRow"?S:c;return E===S&&r.parser.lazy[r.now().line]?n(k):E(k)}function c(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(l=!0,i+=1),h(k)}function h(k){return k===null?n(k):de(k)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),p):n(k):we(k)?je(e,h,"whitespace")(k):(i+=1,l&&(l=!1,s+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),d(k)))}function d(k){return k===null||k===124||Re(k)?(e.exit("data"),h(k)):(e.consume(k),k===92?f:d)}function f(k){return k===92||k===124?(e.consume(k),d):d(k)}function p(k){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(k):(e.enter("tableDelimiterRow"),l=!1,we(k)?je(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):m(k))}function m(k){return k===45||k===58?w(k):k===124?(l=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),x):C(k)}function x(k){return we(k)?je(e,w,"whitespace")(k):w(k)}function w(k){return k===58?(i+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),v):k===45?(i+=1,v(k)):k===null||de(k)?b(k):C(k)}function v(k){return k===45?(e.enter("tableDelimiterFiller"),_(k)):C(k)}function _(k){return k===45?(e.consume(k),_):k===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),y):(e.exit("tableDelimiterFiller"),y(k))}function y(k){return we(k)?je(e,b,"whitespace")(k):b(k)}function b(k){return k===124?m(k):k===null||de(k)?!l||s!==i?C(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):C(k)}function C(k){return n(k)}function S(k){return e.enter("tableRow"),N(k)}function N(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),N):k===null||de(k)?(e.exit("tableRow"),t(k)):we(k)?je(e,N,"whitespace")(k):(e.enter("data"),L(k))}function L(k){return k===null||k===124||Re(k)?(e.exit("data"),N(k)):(e.consume(k),k===92?A:L)}function A(k){return k===92||k===124?(e.consume(k),L):L(k)}}function hO(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],l=[0,0,0,0],a=!1,c=0,u,h,d;const f=new oO;for(;++nn[2]+1){const m=n[2]+1,x=n[3]-n[2]-1;e.add(m,x,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},Ws(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function jv(e,t,n,r,s){const i=[],l=Ws(t.events,n);s&&(s.end=Object.assign({},l),i.push(["exit",s,t])),r.end=Object.assign({},l),i.push(["exit",r,t]),e.add(n+1,0,i)}function Ws(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const fO={name:"tasklistCheck",tokenize:mO};function pO(){return{text:{91:fO}}}function mO(e,t,n){const r=this;return s;function s(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),i)}function i(c){return Re(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),l):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),l):n(c)}function l(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(c)}function a(c){return de(c)?t(c):we(c)?e.check({tokenize:gO},t,n)(c):n(c)}}function gO(e,t,n){return je(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function xO(e){return Gw([W5(),J5(),lO(e),uO(),pO()])}const vO={};function FS(e){const t=this,n=e||vO,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),l=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(xO(n)),i.push(B5()),l.push(z5(n))}function _O({template:e,profiles:t,onSave:n,onClose:r,busy:s=!1}){const[i,l]=g.useState(e?.name??""),[a,c]=g.useState(e?.contentMd??""),[u,h]=g.useState(e?.defaultProfileId??""),[d,f]=g.useState("edit"),p=i.trim().length>0&&!s;async function m(x){x.preventDefault(),p&&await n(i.trim(),a,u)}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"template editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:e?`Edit template — ${e.name}`:"New template"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close template editor",onClick:r,disabled:s,children:"✕"})]}),o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"te-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"te-name","aria-label":"template name",placeholder:"My template",value:i,onChange:x=>l(x.target.value),disabled:s,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"te-profile",className:"text-xs font-medium text-muted",children:"Default profile"}),t.length>0?o.jsxs("select",{id:"te-profile","aria-label":"template default profile",value:u,onChange:x=>h(x.target.value),disabled:s,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— none —"}),t.map(x=>o.jsx("option",{value:x.id,children:x.name},x.id))]}):o.jsx(ce,{id:"te-profile","aria-label":"template default profile",placeholder:"profile-id (optional)",value:u,onChange:x=>h(x.target.value),disabled:s,className:"min-w-48"})]})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>o.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":d===x,onClick:()=>f(x),className:U("px-4 py-2 text-sm font-medium capitalize transition-colors",d===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:d==="edit"?o.jsx("textarea",{"aria-label":"template content",value:a,onChange:x=>c(x.target.value),disabled:s,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Agent instructions - -...`}):o.jsx("div",{className:U("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:a.trim()?o.jsx(gS,{remarkPlugins:[FS],children:a}):o.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:r,disabled:s,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save template",disabled:!p,loading:s,children:"Save"})]})]})]})}function Ji(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function yO(){const{template:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{l(!0),s(null);try{const f=await e.listTemplates();n(f)}catch(f){s(Ji(f))}finally{l(!1)}},[e]);g.useEffect(()=>{a()},[a]);const c=g.useCallback(async f=>{l(!0),s(null);try{const p=await e.createTemplate(f);n(m=>[...m,p])}catch(p){s(Ji(p))}finally{l(!1)}},[e]),u=g.useCallback(async(f,p)=>{l(!0),s(null);try{const m=await e.updateTemplate(f,p);n(x=>x.map(w=>w.id===f?m:w))}catch(m){s(Ji(m))}finally{l(!1)}},[e]),h=g.useCallback(async f=>{l(!0),s(null);try{await e.deleteTemplate(f),n(p=>p.filter(m=>m.id!==f))}catch(p){s(Ji(p))}finally{l(!1)}},[e]),d=g.useCallback(async(f,p,m)=>{l(!0),s(null);try{await e.createAgentFromTemplate(f,p,m)}catch(x){s(Ji(x))}finally{l(!1)}},[e]);return{templates:t,error:r,busy:i,refresh:a,createTemplate:c,updateTemplate:u,deleteTemplate:h,createAgentFromTemplate:d}}function $S({projectId:e}){const t=yO(),{profile:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(!1),[a,c]=g.useState(null),[u,h]=g.useState(!1);async function d(p){if(!i){try{const m=await n.listProfiles();s(m)}catch{}l(!0)}c(p)}async function f(p,m,x){if(a){h(!0);try{a.mode==="create"?await t.createTemplate({name:p,content:m,defaultProfileId:x}):await t.updateTemplate(a.template.id,m),c(null)}finally{h(!1)}}}return o.jsxs(o.Fragment,{children:[a!==null&&o.jsx(_O,{template:a.mode==="edit"?a.template:null,profiles:r,onSave:f,onClose:()=>c(null),busy:u}),o.jsxs(ke,{title:"Templates",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Templates"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Me,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create template",disabled:t.busy,onClick:()=>void d({mode:"create"}),children:"New template"})]})]}),o.jsx("div",{className:"p-4",children:t.templates.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No templates yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.templates.map(p=>o.jsx("li",{className:"flex flex-col gap-2 py-3 first:pt-0 last:pb-0",children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"font-medium text-content",children:p.name}),o.jsxs("span",{className:"text-xs text-muted",children:["v",p.version]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit ${p.name}`,disabled:t.busy,onClick:()=>void d({mode:"edit",template:p}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"primary","aria-label":`create agent from ${p.name}`,disabled:t.busy,onClick:()=>void t.createAgentFromTemplate(e,p.id),children:"Create agent"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete template ${p.name}`,disabled:t.busy,onClick:()=>void t.deleteTemplate(p.id),className:"text-danger hover:text-danger",children:"Delete"})]})]})},p.id))})})]})]})}function bO({skill:e,onSave:t,onClose:n,busy:r=!1}){const[s,i]=g.useState(e?.name??""),[l,a]=g.useState(e?.contentMd??""),[c,u]=g.useState(e?.scope??"project"),[h,d]=g.useState("edit"),f=e!=null,p=s.trim().length>0&&l.trim().length>0&&!r;async function m(x){x.preventDefault(),p&&await t(s.trim(),l,c)}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"skill editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:f?`Edit skill — ${e.name}`:"New skill"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close skill editor",onClick:n,disabled:r,children:"✕"})]}),o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"se-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"se-name","aria-label":"skill name",placeholder:"My skill",value:s,onChange:x=>i(x.target.value),disabled:r,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"se-scope",className:"text-xs font-medium text-muted",children:"Scope"}),o.jsxs("select",{id:"se-scope","aria-label":"skill scope",value:c,onChange:x=>u(x.target.value),disabled:r||f,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"project",children:"Project"}),o.jsx("option",{value:"global",children:"Global"})]})]})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>o.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":h===x,onClick:()=>d(x),className:U("px-4 py-2 text-sm font-medium capitalize transition-colors",h===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:h==="edit"?o.jsx("textarea",{"aria-label":"skill content",value:l,onChange:x=>a(x.target.value),disabled:r,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Skill workflow - -...`}):o.jsx("div",{className:U("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:l.trim()?o.jsx(gS,{remarkPlugins:[FS],children:l}):o.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:n,disabled:r,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save skill",disabled:!p,loading:r,children:"Save"})]})]})]})}function Fo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function wO(e){const{skill:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState(!1),h=g.useCallback(async()=>{if(e){u(!0),a(null);try{const[x,w]=await Promise.all([t.listSkills(e,"global"),t.listSkills(e,"project")]);r(x),i(w)}catch(x){a(Fo(x))}finally{u(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=x=>x==="global"?r:i,f=g.useCallback(async x=>{u(!0),a(null);try{const w=await t.createSkill({...x,projectId:e});d(x.scope)(v=>[...v,w])}catch(w){a(Fo(w))}finally{u(!1)}},[t,e]),p=g.useCallback(async(x,w,v)=>{u(!0),a(null);try{const _=await t.updateSkill(e,x,w,v);d(x)(y=>y.map(b=>b.id===w?_:b))}catch(_){a(Fo(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async(x,w)=>{u(!0),a(null);try{await t.deleteSkill(e,x,w),d(x)(v=>v.filter(_=>_.id!==w))}catch(v){a(Fo(v))}finally{u(!1)}},[t,e]);return{globalSkills:n,projectSkills:s,error:l,busy:c,refresh:h,createSkill:f,updateSkill:p,deleteSkill:m}}function WS({projectId:e}){const t=wO(e),[n,r]=g.useState(null),[s,i]=g.useState(!1);async function l(c,u,h){if(n){i(!0);try{n.mode==="create"?await t.createSkill({name:c,content:u,scope:h}):await t.updateSkill(n.skill.scope,n.skill.id,u),r(null)}finally{i(!1)}}}function a(c,u){return o.jsx("div",{className:"p-4",children:u.length===0?o.jsxs("p",{className:"text-sm text-muted",children:["No ",c," skills yet."]}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.map(h=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[o.jsx("span",{className:"min-w-0 font-medium text-content",children:h.name}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit skill ${h.name}`,disabled:t.busy,onClick:()=>r({mode:"edit",skill:h}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete skill ${h.name}`,disabled:t.busy,onClick:()=>void t.deleteSkill(h.scope,h.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},h.id))})})}return o.jsxs(o.Fragment,{children:[n!==null&&o.jsx(bO,{skill:n.mode==="edit"?n.skill:null,onSave:l,onClose:()=>r(null),busy:s}),o.jsxs(ke,{title:"Skills",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Skills"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Me,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create skill",disabled:t.busy,onClick:()=>r({mode:"create"}),children:"New skill"})]})]}),o.jsx("div",{className:"border-b border-border px-4 pt-3",children:o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Project"})}),a("project",t.projectSkills),o.jsx("div",{className:"border-y border-border px-4 pt-3",children:o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Global"})}),a("global",t.globalSkills)]})]})}function Zu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function HS(){const{embedder:e}=fe(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{const[p,m]=await Promise.all([e.listEmbedderProfiles(),e.describeEmbedderEngines()]);n(p),s(m)}catch(p){l(Zu(p))}finally{c(!1)}},[e]);g.useEffect(()=>{u()},[u]);const h=g.useCallback(async p=>{c(!0),l(null);try{await e.saveEmbedderProfile(p),await u()}catch(m){l(Zu(m)),c(!1)}},[e,u]),d=g.useCallback(async p=>{c(!0),l(null);try{await e.deleteEmbedderProfile(p),await u()}catch(m){l(Zu(m)),c(!1)}},[e,u]),f=t.find(p=>p.strategy!=="none")??null;return{profiles:t,engines:r,active:f,error:i,busy:a,refresh:u,saveProfile:h,deleteProfile:d}}const US="http://localhost:11434/api/embeddings",qS="https://api.openai.com/v1/embeddings",ed=[{strategy:"none",key:"none",label:"None (naïve recall)"},{strategy:"localOnnx",key:"localOnnx",label:"Local ONNX"},{strategy:"localServer",key:"localServer",label:"Ollama (local server)"},{strategy:"api",key:"api",label:"API"},{strategy:"api",key:"custom",label:"Custom"}],Hs={id:"",name:"",model:"",endpoint:"",apiKeyEnv:"",dimension:"",onnxEngineId:""};function SO(e,t,n){if(n)return{id:n.id,name:n.name,model:n.model??"",endpoint:n.endpoint??"",apiKeyEnv:n.apiKeyEnv??"",dimension:String(n.dimension),onnxEngineId:e==="localOnnx"?t.find(r=>r.id===n.model)?.id??t[0]?.id??"":""};switch(e){case"localOnnx":{const r=t.find(s=>s.recommended)??t[0];return{...Hs,id:"onnx-local",name:r?.displayName??"Local ONNX",model:r?.id??"",dimension:r?String(r.dimension):"",onnxEngineId:r?.id??""}}case"localServer":return{...Hs,id:"ollama",name:"Ollama",endpoint:US,model:"nomic-embed-text",dimension:"768"};case"api":return{...Hs,id:"api",name:"API embedder",endpoint:qS,apiKeyEnv:"OPENAI_API_KEY",model:"text-embedding-3-small",dimension:"1536"};case"custom":return{...Hs,id:"custom",name:"Custom embedder"};default:return{...Hs}}}function kO(e,t){switch(e){case"none":return!0;case"localOnnx":return t.vectorOnnxEnabled;case"localServer":case"api":return t.vectorHttpEnabled}}function VS(){const e=HS(),[t,n]=g.useState("localOnnx"),[r,s]=g.useState(Hs),i=e.engines?.recommendedOnnx??[],l={vectorOnnxEnabled:e.engines?.vectorOnnxEnabled??!1,vectorHttpEnabled:e.engines?.vectorHttpEnabled??!1};g.useEffect(()=>{if(!e.engines)return;const _=ed.find(b=>b.key===t),y=e.active&&_&&e.active.strategy===_.strategy?e.active:null;s(SO(t,e.engines.recommendedOnnx,y))},[e.engines,e.active,t]);const c=ed.find(_=>_.key===t).strategy;function u(_){s(y=>({...y,..._}))}function h(_){const y=i.find(b=>b.id===_);u({onnxEngineId:_,model:y?.id??_,dimension:y?String(y.dimension):r.dimension})}const d=Number.parseInt(r.dimension,10),f=g.useMemo(()=>c==="none"?{ok:!0}:r.id.trim()?r.name.trim()?!Number.isFinite(d)||d<=0?{ok:!1,msg:"Dimension must be a positive number."}:(c==="localServer"||c==="api")&&!r.endpoint.trim()?{ok:!1,msg:"Endpoint is required."}:{ok:!0}:{ok:!1,msg:"Name is required."}:{ok:!1,msg:"Id is required."},[c,r,d]);function p(){return{id:r.id.trim(),name:r.name.trim(),strategy:c,dimension:d,model:r.model.trim()||void 0,endpoint:(c==="localServer"||c==="api")&&r.endpoint.trim()||void 0,apiKeyEnv:c==="api"&&r.apiKeyEnv.trim()||void 0}}async function m(){f.ok&&await e.saveProfile(p())}async function x(){for(const _ of e.profiles)await e.deleteProfile(_.id);n("none")}const w=U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),v=e.active!==null;return o.jsxs(ke,{title:"Memory / Embedder",className:"flex flex-col gap-0",children:[e.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[o.jsx("p",{className:"rounded-md border border-border bg-raised px-3 py-2 text-xs text-muted","data-testid":"embedder-restart-note",children:"The embedder change takes effect at the next app start."}),o.jsxs("p",{className:"text-xs text-faint","data-testid":"embedder-active",children:["Current:"," ",v?o.jsxs("span",{className:"text-content",children:["Vector — ",e.active.strategy,e.active.model?` ${e.active.model}`:""]}):o.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),o.jsxs("fieldset",{className:"flex flex-col gap-2","aria-label":"embedder strategy",children:[o.jsx("legend",{className:"mb-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Strategy"}),ed.map(_=>{const y=kO(_.strategy,l),b=_.key==="localOnnx";return o.jsxs("label",{className:U("flex items-center gap-2 rounded-md border px-3 py-2 text-sm",t===_.key?"border-primary bg-raised":"border-border",!y&&"opacity-50"),"data-testid":`embedder-strategy-${_.key}`,children:[o.jsx("input",{type:"radio",name:"embedder-strategy",value:_.key,checked:t===_.key,disabled:!y,onChange:()=>n(_.key),"aria-label":_.label}),o.jsx("span",{className:"text-content",children:_.label}),b&&o.jsx("span",{className:"rounded border border-primary/40 bg-primary/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-primary",children:"Recommended"}),!y&&o.jsx("span",{className:"text-[11px] text-faint",children:"not available in this build"})]},_.key)})]}),c!=="none"&&o.jsxs("div",{className:"flex flex-col gap-3",children:[c==="localOnnx"&&o.jsx(qt,{label:"ONNX model",children:({id:_})=>o.jsx("select",{id:_,"aria-label":"onnx model",className:w,value:r.onnxEngineId,disabled:e.busy,onChange:y=>h(y.target.value),children:i.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName,y.recommended?" — recommended":""," (dim"," ",y.dimension,", ~",y.approxSizeMb," MB)"]},y.id))})}),(c==="localServer"||c==="api")&&o.jsx(qt,{label:"Endpoint",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"endpoint",placeholder:c==="localServer"?US:qS,value:r.endpoint,disabled:e.busy,onChange:y=>u({endpoint:y.target.value})})}),c==="api"&&o.jsx(qt,{label:"API key environment variable",hint:"Name of the env var holding the key — never the key itself.",children:({id:_,describedBy:y})=>o.jsx(ce,{id:_,"aria-label":"api key env var",placeholder:"OPENAI_API_KEY","aria-describedby":y,value:r.apiKeyEnv,disabled:e.busy,onChange:b=>u({apiKeyEnv:b.target.value})})}),c!=="localOnnx"&&o.jsx(qt,{label:"Model",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"model",placeholder:"model name",value:r.model,disabled:e.busy,onChange:y=>u({model:y.target.value})})}),o.jsx(qt,{label:"Dimension",error:f.ok?void 0:f.msg,children:({id:_,describedBy:y})=>o.jsx(ce,{id:_,"aria-label":"dimension",type:"number",min:1,value:r.dimension,"aria-describedby":y,disabled:e.busy,onChange:b=>u({dimension:b.target.value})})}),o.jsx(qt,{label:"Profile id",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"profile id",placeholder:"my-embedder",value:r.id,disabled:e.busy,onChange:y=>u({id:y.target.value})})}),o.jsx(qt,{label:"Profile name",children:({id:_})=>o.jsx(ce,{id:_,"aria-label":"profile name",placeholder:"My embedder",value:r.name,disabled:e.busy,onChange:y=>u({name:y.target.value})})})]}),o.jsxs("div",{className:"flex items-center gap-2 border-t border-border pt-3",children:[e.busy&&o.jsx(Me,{size:14}),c!=="none"&&o.jsx(M,{type:"button",variant:"primary","aria-label":"save embedder",disabled:e.busy||!f.ok,onClick:()=>void m(),children:"Save"}),o.jsx(M,{type:"button","aria-label":"back to none",disabled:e.busy,onClick:()=>void x(),children:"Back to None"})]})]})]})}const CO=["user","feedback","project","reference"];function jO({entry:e,loadContent:t,resolveLinks:n,onCreate:r,onUpdate:s,onClose:i,busy:l=!1}){const a=e!=null,[c,u]=g.useState(e?.title??""),[h,d]=g.useState(e?.hook??""),[f,p]=g.useState(e?.type??"project"),[m,x]=g.useState(""),[w,v]=g.useState([]);g.useEffect(()=>{if(!e)return;let C=!1;return(async()=>{try{if(t){const S=await t(e.slug);C||x(S)}if(n){const S=await n(e.slug);C||v(S)}}catch{}})(),()=>{C=!0}},[e,t,n]);const _=h.trim().length>0&&m.trim().length>0&&!l&&(a||c.trim().length>0);async function y(C){C.preventDefault(),_&&(a?await s(e.slug,h.trim(),f,m):await r(c.trim(),h.trim(),f,m))}const b=U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"memory editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:a?`Edit note — ${e.title}`:"New note"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close memory editor",onClick:i,disabled:l,children:"✕"})]}),o.jsxs("form",{onSubmit:C=>void y(C),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a?o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Slug"}),o.jsx("code",{className:"truncate rounded-md border border-border bg-raised px-3 py-2 text-sm text-muted",children:e.slug})]}):o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"me-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ce,{id:"me-name","aria-label":"memory name",placeholder:"My note",value:c,onChange:C=>u(C.target.value),disabled:l,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"me-type",className:"text-xs font-medium text-muted",children:"Type"}),o.jsx("select",{id:"me-type","aria-label":"memory type",value:f,onChange:C=>p(C.target.value),disabled:l,className:b,children:CO.map(C=>o.jsx("option",{value:C,children:C},C))})]})]}),o.jsxs("div",{className:"flex shrink-0 flex-col gap-1 border-b border-border px-4 py-3",children:[o.jsx("label",{htmlFor:"me-description",className:"text-xs font-medium text-muted",children:"Description"}),o.jsx(ce,{id:"me-description","aria-label":"memory description",placeholder:"One-line hook",value:h,onChange:C=>d(C.target.value),disabled:l})]}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:[o.jsx("label",{htmlFor:"me-content",className:"mb-1 text-xs font-medium text-muted",children:"Content"}),o.jsx("textarea",{id:"me-content","aria-label":"memory content",value:m,onChange:C=>x(C.target.value),disabled:l,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Note - -Use [[other-slug]] to link…`}),a&&o.jsxs("div",{className:"mt-3 shrink-0",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Links"}),w.length===0?o.jsx("p",{className:"mt-1 text-sm text-muted",children:"No resolved links."}):o.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:w.map(C=>o.jsx("li",{className:"rounded-md border border-border bg-raised px-2 py-0.5 text-xs text-muted",children:C},C))})]})]}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:i,disabled:l,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save note",disabled:!_,loading:l,children:"Save"})]})]})]})}function $o(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NO(e){const{memory:t,system:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{if(e){c(!0),l(null);try{s(await t.readIndex(e))}catch(m){l($o(m))}finally{c(!1)}}},[t,e]);g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let m,x=!1;return n.onDomainEvent(w=>{w.type==="memorySaved"&&u()}).then(w=>{x?w():m=w}),()=>{x=!0,m?.()}},[u,n]);const h=g.useCallback(async m=>{c(!0),l(null);try{await t.createMemory({...m,projectId:e}),await u()}catch(x){l($o(x)),c(!1)}},[t,e,u]),d=g.useCallback(async(m,x,w,v)=>{c(!0),l(null);try{await t.updateMemory(e,m,x,w,v),await u()}catch(_){l($o(_)),c(!1)}},[t,e,u]),f=g.useCallback(async m=>{c(!0),l(null);try{await t.deleteMemory(e,m),await u()}catch(x){l($o(x)),c(!1)}},[t,e,u]),p=g.useCallback(m=>t.resolveLinks(e,m),[t,e]);return{entries:r,error:i,busy:a,refresh:u,createMemory:h,updateMemory:d,deleteMemory:f,resolveLinks:p}}function KS({projectId:e}){const t=NO(e),n=HS(),{memory:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState(!1),c=g.useCallback(async d=>(await r.getMemory(e,d)).content,[r,e]);async function u(d,f,p,m){a(!0);try{await t.createMemory({name:d,description:f,type:p,content:m}),i(null)}finally{a(!1)}}async function h(d,f,p,m){a(!0);try{await t.updateMemory(d,f,p,m),i(null)}finally{a(!1)}}return o.jsxs(o.Fragment,{children:[s!==null&&o.jsx(jO,{entry:s.mode==="edit"?s.entry:null,loadContent:c,resolveLinks:t.resolveLinks,onCreate:u,onUpdate:h,onClose:()=>i(null),busy:l}),o.jsxs(ke,{title:"Memory",className:"flex flex-col gap-0",children:[o.jsxs("p",{className:"border-b border-border px-4 py-2 text-xs text-faint","data-testid":"memory-tier",children:["Tier:"," ",n.active?o.jsxs("span",{className:"text-content",children:["Vector — ",n.active.strategy,n.active.model?` ${n.active.model}`:""]}):o.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Notes"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Me,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create memory",disabled:t.busy,onClick:()=>i({mode:"create"}),children:"New note"})]})]}),o.jsx("div",{className:"p-4",children:t.entries.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No memory notes yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.entries.map(d=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"min-w-0 truncate font-medium text-content",children:d.title}),o.jsx("span",{className:"shrink-0 rounded border border-border bg-raised px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted",children:d.type})]}),o.jsx("span",{className:"truncate text-xs text-muted",children:d.hook})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit memory ${d.title}`,disabled:t.busy,onClick:()=>i({mode:"edit",entry:d}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete memory ${d.title}`,disabled:t.busy,onClick:()=>void t.deleteMemory(d.slug),className:"text-danger hover:text-danger",children:"Delete"})]})]},d.slug))})})]})]})}const Nv=[{id:"readProject",label:"Lecture projet",tools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read"]},{id:"readTickets",label:"Lecture tickets",tools:["idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"]},{id:"delegation",label:"Délégation agents",tools:["idea_ask_agent","idea_launch_agent","idea_stop_agent"]},{id:"contextMemory",label:"Contexte et mémoire",tools:["idea_update_context","idea_context_propose","idea_memory_write"]},{id:"tickets",label:"Tickets",tools:["idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]},{id:"work",label:"Travail et exécution",tools:["idea_run_in_background","idea_workstate_set"]},{id:"skills",label:"Skills",tools:["idea_create_skill"]}],EO={idea_list_agents:"Lister les agents",idea_context_read:"Lire le contexte d'un agent",idea_memory_read:"Lire la mémoire projet",idea_skill_read:"Lire un skill",idea_workstate_read:"Lire l'état de travail",idea_ticket_read:"Lire un ticket",idea_ticket_list:"Lister les tickets",idea_ticket_read_carnet:"Lire le carnet d'un ticket",idea_sprint_list:"Lister les sprints",idea_ask_agent:"Déléguer à un agent",idea_launch_agent:"Lancer un agent",idea_stop_agent:"Arrêter un agent",idea_update_context:"Modifier le contexte d'un agent",idea_context_propose:"Proposer un contexte",idea_memory_write:"Écrire la mémoire projet",idea_workstate_set:"Écrire l'état de travail",idea_create_skill:"Créer un skill",idea_ticket_create:"Créer un ticket",idea_ticket_update:"Modifier un ticket",idea_ticket_update_status:"Modifier le statut d'un ticket",idea_ticket_update_priority:"Modifier la priorité d'un ticket",idea_ticket_update_carnet:"Modifier le carnet d'un ticket",idea_ticket_link:"Lier des tickets",idea_ticket_unlink:"Délier des tickets",idea_run_in_background:"Exécuter une commande en arrière-plan"};function PO(e){return EO[e]??e}function Wo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function AO(e){const{permission:t}=fe(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[l,a]=g.useState(!1),[c,u]=g.useState(null),h=g.useCallback(async()=>{if(t){i(!0),u(null);try{r(await t.getMcpToolPermissions(e))}catch(m){u(Wo(m))}finally{i(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=g.useCallback(async m=>{if(t){a(!0),u(null);try{r(await t.updateProjectMcpToolPermissions(e,m))}catch(x){throw u(Wo(x)),x}finally{a(!1)}}},[t,e]),f=g.useCallback(async(m,x)=>{if(t){a(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,x))}catch(w){throw u(Wo(w)),w}finally{a(!1)}}},[t,e]),p=g.useCallback(async m=>{if(t){a(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,null))}catch(x){throw u(Wo(x)),x}finally{a(!1)}}},[t,e]);return{doc:n,loading:s,busy:l,error:c,refresh:h,saveProjectDefault:d,saveAgentOverride:f,resetAgentOverride:p}}const TO=new Set(["readProject","readTickets"]);function LO(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function DO(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(r=>n.has(r))}function RO({projectId:e,agents:t}){const n=AO(e),[r,s]=g.useState({type:"project"}),i=g.useRef(!1);function l(u){i.current&&!window.confirm("Des modifications non enregistrées seront perdues. Continuer ?")||(i.current=!1,s(u))}if(n.loading&&!n.doc)return o.jsxs("div",{"data-testid":"mcp-tool-permissions-skeleton",className:"flex flex-col gap-3 p-4",children:[o.jsx("div",{className:"h-4 w-40 animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-32 w-full animate-pulse rounded bg-raised"})]});if(n.error&&!n.doc)return o.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),o.jsx(M,{size:"sm",onClick:()=>void n.refresh(),children:"Réessayer"})]});if(!n.doc)return null;const a=n.doc,c=r.type==="agent"?a.agents.find(u=>u.agentId===r.agentId)??null:null;return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4 md:flex-row",children:[o.jsxs("nav",{"aria-label":"cibles des permissions MCP",className:"flex w-full shrink-0 flex-col gap-2 md:w-56",children:[o.jsxs("button",{type:"button","aria-pressed":r.type==="project",onClick:()=>l({type:"project"}),className:U("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",r.type==="project"?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsx("span",{className:"font-medium text-content",children:"Défaut projet"}),o.jsx("span",{className:"text-xs text-muted",children:a.projectDefault?"Personnalisé":"Lecture seule"})]}),o.jsx("h4",{className:"mt-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun agent dans ce projet."}):o.jsx("ul",{className:"flex flex-col gap-1.5",children:t.map(u=>{const h=a.agents.some(f=>f.agentId===u.id),d=r.type==="agent"&&r.agentId===u.id;return o.jsx("li",{children:o.jsxs("button",{type:"button","aria-pressed":d,onClick:()=>l({type:"agent",agentId:u.id,agentName:u.name}),className:U("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",d?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsx("span",{className:"truncate font-medium text-content",children:u.name}),o.jsx("span",{className:U("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",h?"bg-warning/15 text-warning":"bg-primary/10 text-muted"),children:h?"Override":"Hérité"})]})},u.id)})})]}),o.jsx("div",{className:"min-w-0 flex-1",children:r.type==="project"?o.jsx(Ev,{targetKind:"project",title:"Tools MCP IdeA — Défaut projet",catalogue:a.catalogue,storedAllowed:a.projectDefault?.allowedTools??null,comparisonBaseline:a.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{i.current=u},onSaveProjectDefault:async u=>{await n.saveProjectDefault({allowedTools:u})}},"project"):o.jsx(Ev,{targetKind:"agent",title:`Tools MCP IdeA — ${r.agentName}`,catalogue:a.catalogue,storedAllowed:c?.policy.allowedTools??null,comparisonBaseline:a.projectDefault?.allowedTools??a.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{i.current=u},onSaveAgentOverride:async u=>{await n.saveAgentOverride(r.agentId,{allowedTools:u})},onResetOverride:async()=>{await n.resetAgentOverride(r.agentId)}},r.agentId)})]})}function Ev({targetKind:e,title:t,catalogue:n,storedAllowed:r,comparisonBaseline:s,busy:i,onDirtyChange:l,onSaveProjectDefault:a,onSaveAgentOverride:c,onResetOverride:u}){const h=r??s,[d,f]=g.useState(e==="project"||r!=null),[p,m]=g.useState(r!=null),[x,w]=g.useState(h),[v,_]=g.useState(h),[y,b]=g.useState(!1),[C,S]=g.useState(!1),[N,L]=g.useState(null),[A,k]=g.useState(()=>Object.fromEntries(Nv.map(re=>[re.id,TO.has(re.id)?e==="project":!0]))),D=e==="project"||d,R=D?x:s,E=D&&!DO(x,v);g.useEffect(()=>{l(E)},[E]),g.useEffect(()=>{if(!C)return;const re=window.setTimeout(()=>S(!1),2e3);return()=>window.clearTimeout(re)},[C]);const O=n.readOnlyTools.filter(re=>R.includes(re)).length,I=n.writeActionTools.filter(re=>R.includes(re)).length,W=g.useMemo(()=>new Set([...n.readOnlyTools,...n.writeActionTools]),[n]),G=g.useMemo(()=>Array.from(new Set([...R,...s])).filter(re=>!W.has(re)),[R,s,W]);function P(re){L(null),w(ee=>LO(ee,re))}function z(re){k(ee=>({...ee,[re]:!ee[re]}))}function j(){f(!0),w(s),_(s)}function se(){w(v),b(!1),L(null)}async function q(){if(L(null),e==="project"){if(x.some(ee=>n.writeActionTools.includes(ee)&&!v.includes(ee))&&!y){b(!0);return}b(!1);try{await a?.(x),_(x),S(!0)}catch(ee){L(td(ee))}return}try{await c?.(x),_(x),m(!0),S(!0)}catch(re){L(td(re))}}async function T(){L(null);try{await u?.(),f(!1),m(!1),w(s),_(s),S(!0)}catch(re){L(td(re))}}return o.jsx(ke,{title:t,className:"flex h-full flex-col",flush:!0,children:o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e==="agent"&&o.jsx("p",{className:"text-xs text-muted",children:d?"Override personnalisé":"Hérite du défaut projet"}),e==="agent"&&!d&&o.jsx(M,{size:"sm",onClick:j,disabled:i,children:"Créer un override"}),o.jsxs("div",{children:[o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Résumé effectif"}),o.jsxs("p",{className:"text-sm text-content",children:[O," lecture autorisés · ",I," écriture autorisé",I>1?"s":""]})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Détail des tools"}),Nv.map(re=>o.jsx(Pv,{group:re,expanded:A[re.id]??!0,onToggle:()=>z(re.id),catalogue:n,editable:D,targetKind:e,draftSet:x,displaySet:R,comparisonBaseline:s,onToggleTool:P},re.id)),G.length>0&&o.jsx(Pv,{group:{id:"unknown",label:"Tools inconnus",tools:G},expanded:A.unknown??!0,onToggle:()=>z("unknown"),catalogue:n,editable:!1,targetKind:e,draftSet:x,displaySet:R,comparisonBaseline:s,onToggleTool:P,unknown:!0})]}),y&&o.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning",children:[o.jsx("p",{children:"Ce tool sera autorisé pour tous les agents sans override. Confirmer cette modification ?"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>b(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"primary",onClick:()=>void q(),children:"Confirmer"})]})]}),N&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:N}),C&&o.jsx("p",{role:"status",className:"text-sm text-success",children:"Permissions enregistrées"}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[o.jsx("div",{children:E&&o.jsx("span",{className:"text-xs text-warning",children:"Modifications non enregistrées"})}),o.jsxs("div",{className:"flex gap-2",children:[e==="agent"&&p&&o.jsx(M,{size:"sm",variant:"ghost",disabled:i,onClick:()=>void T(),children:"Réinitialiser l'override"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:i||!E,onClick:se,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"primary",disabled:i||!D||!E,loading:i&&E,onClick:()=>void q(),children:"Enregistrer"})]})]})]})})}function Pv({group:e,expanded:t,onToggle:n,catalogue:r,editable:s,targetKind:i,displaySet:l,comparisonBaseline:a,onToggleTool:c,unknown:u}){const h=e.tools.filter(f=>l.includes(f)).length,d=e.tools.length;return o.jsxs("div",{className:"rounded-md border border-border",children:[o.jsxs("button",{type:"button","aria-expanded":t,"aria-label":`${e.label}, ${h} sur ${d} autorisé${d>1?"s":""}`,onClick:n,className:"flex min-h-[32px] w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-raised",children:[o.jsx("span",{className:"font-medium text-content",children:e.label}),o.jsxs("span",{className:"text-xs text-muted",children:[h,"/",d," autorisés"]})]}),t&&o.jsx("ul",{className:"flex flex-col divide-y divide-border border-t border-border",children:e.tools.map(f=>o.jsx(OO,{tool:f,isRead:r.readOnlyTools.includes(f),unknown:u,editable:s,checked:l.includes(f),status:MO(f,s,i,l,a,u),onToggle:()=>c(f)},f))})]})}function MO(e,t,n,r,s,i){if(i)return"unknown";if(n==="agent"&&!t)return"inherited";if(n==="agent"&&t){const l=r.includes(e),a=s.includes(e);return l&&!a?"added":!l&&a?"removed":l?"allowed":"denied"}return r.includes(e)?"allowed":"denied"}const IO={allowed:"Autorisé",denied:"Refusé",inherited:"Hérité",added:"Ajouté",removed:"Retiré",unknown:"Inconnu"};function OO({tool:e,isRead:t,unknown:n,editable:r,checked:s,status:i,onToggle:l}){const a=PO(e),c=`mcp-tool-${e}`;return o.jsxs("li",{className:"flex min-h-[32px] items-center gap-2 px-3 py-1.5",children:[o.jsx("input",{id:c,type:"checkbox",checked:s,disabled:!r||n,onChange:l,"aria-label":`${a}, ${e}`}),o.jsxs("label",{htmlFor:c,className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"font-mono text-xs text-content",children:e}),!n&&o.jsx("span",{className:U("rounded-full px-1.5 py-0.5 text-[10px] font-medium",t?"bg-primary/10 text-primary":"bg-warning/15 text-warning"),children:t?"Lecture":"Écriture"})]}),o.jsx("span",{className:"text-xs text-muted",children:a})]}),o.jsx("span",{className:U("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",i==="allowed"||i==="added"?"bg-success/15 text-success":i==="denied"||i==="removed"?"bg-danger/10 text-muted":i==="unknown"?"bg-danger/15 text-danger":"bg-primary/10 text-muted"),children:IO[i]})]})}function td(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Av={fallback:"ask",read:"none",write:"none",delete:"none",executeBash:"none"},GS=["read","write","delete","executeBash"];function ts(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function YS(e){if(!e)return{...Av};const t={...Av,fallback:e.fallback};for(const n of GS)t[n]=BO(e.rules,n);return t}function BO(e,t){const n=e.filter(r=>r.capability===t);return n.some(r=>r.effect==="deny")?"deny":n.some(r=>r.effect==="allow")?"allow":"none"}function Tv(e){const t=[];for(const n of GS){const r=e[n];r!=="none"&&t.push(zO(n,r))}return{fallback:e.fallback,rules:t}}function zO(e,t){return e==="executeBash"?{capability:e,effect:t,commands:[]}:{capability:e,effect:t,paths:["**"]}}function Ho(e){return e?e.rules.some(t=>{if(t.capability==="executeBash")return(t.commands??[]).length>0;const n=t.paths??[];return n.length!==1||n[0]!=="**"}):!1}function FO(e){const{agent:t,permission:n}=fe(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(null),[u,h]=g.useState({}),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useCallback(async()=>{f(!0),m(null);try{const[L,A,k]=await Promise.all([t.listAgents(e),n.getProjectPermissions(e),n.getProjectSystemPermissions(e)]),D=await Promise.all(L.map(async R=>{try{return[R.id,await n.resolveAgentSystemPermissions(e,R.id)]}catch{return[R.id,null]}}));s(L),l(A),c(k),h(Object.fromEntries(D.filter(R=>R[1]!==null)))}catch(L){m(ts(L))}finally{f(!1)}},[t,n,e]);g.useEffect(()=>{x()},[x]);const w=g.useMemo(()=>{const L=new Map((i?.agents??[]).map(k=>[k.agentId,k.permissions])),A=new Map((a?.agents??[]).map(k=>[k.agentId,k.permissions]));return r.map(k=>({agent:k,override:L.get(k.id)??null,systemOverride:A.get(k.id)??null,resolvedSystem:u[k.id]??null}))},[r,i,a,u]),v=g.useMemo(()=>YS(i?.projectDefaults??null),[i]),_=g.useCallback(async L=>{f(!0),m(null);try{l(await n.updateProjectPermissions(e,Tv(L)))}catch(A){m(ts(A))}finally{f(!1)}},[n,e]),y=g.useCallback(async()=>{f(!0),m(null);try{l(await n.updateProjectPermissions(e,null))}catch(L){m(ts(L))}finally{f(!1)}},[n,e]),b=g.useCallback(async(L,A)=>{f(!0),m(null);try{l(await n.updateAgentPermissions(e,L,Tv(A)))}catch(k){m(ts(k))}finally{f(!1)}},[n,e]),C=g.useCallback(async L=>{f(!0),m(null);try{l(await n.updateAgentPermissions(e,L,null))}catch(A){m(ts(A))}finally{f(!1)}},[n,e]),S=g.useCallback(async L=>{f(!0),m(null);try{const A=await n.updateProjectSystemPermissions(e,L);c(A),await x()}catch(A){m(ts(A))}finally{f(!1)}},[n,e,x]),N=g.useCallback(async(L,A)=>{f(!0),m(null);try{const k=await n.updateAgentSystemPermissions(e,L,A);c(k),await x()}catch(k){m(ts(k))}finally{f(!1)}},[n,e,x]);return{agents:r,rows:w,document:i,systemDocument:a,projectDraft:v,busy:d,error:p,refresh:x,saveProjectDefaults:_,clearProjectDefaults:y,saveAgentOverride:b,clearAgentOverride:C,saveProjectSystemPermissions:S,saveAgentSystemPermissions:N}}const zs=[{id:"system",label:"Système"},{id:"mcpTools",label:"Tools MCP IdeA"}],$O=[{key:"read",label:"Read"},{key:"write",label:"Write"},{key:"delete",label:"Delete"},{key:"executeBash",label:"Bash"}],WO={ask:"Ask",allow:"Allow",deny:"Deny"},nd={allow:"Autorisé",deny:"Interdit",ask:"Demande"};function XS({projectId:e}){const t=FO(e),[n,r]=g.useState({type:"project"}),[s,i]=g.useState("system"),l=n.type==="agent"?t.rows.find(w=>w.agent.id===n.agentId)??null:null,a=l?.override??t.document?.projectDefaults??null,c=n.type==="project"?t.systemDocument?.projectDefault??null:l?.systemOverride??t.systemDocument?.projectDefault??null,u=n.type==="project"?t.rows[0]?.resolvedSystem??null:l?.resolvedSystem??null,h=n.type==="project"?t.projectDraft:YS(l?.override??t.document?.projectDefaults??null),d=n.type==="project"?Ho(t.document?.projectDefaults):Ho(l?.override),f=t.document?.projectDefaults!=null;async function p(w){n.type==="project"?await t.saveProjectDefaults(w):await t.saveAgentOverride(n.agentId,w)}async function m(){n.type==="project"?await t.clearProjectDefaults():await t.clearAgentOverride(n.agentId)}async function x(w){n.type==="project"?await t.saveProjectSystemPermissions(w):await t.saveAgentSystemPermissions(n.agentId,w)}return o.jsxs(ke,{title:"Permissions",actions:o.jsx(M,{size:"sm",variant:"ghost",disabled:t.busy,onClick:()=>void t.refresh(),children:"Refresh"}),className:"flex min-h-0 flex-1 flex-col",flush:!0,children:[o.jsx("div",{role:"tablist","aria-label":"Permissions",className:"flex gap-1 border-b border-border px-4 pt-2",children:zs.map(w=>o.jsx("button",{type:"button",role:"tab",id:`permissions-tab-${w.id}`,"aria-selected":s===w.id,"aria-controls":`permissions-tabpanel-${w.id}`,tabIndex:s===w.id?0:-1,onClick:()=>i(w.id),onKeyDown:v=>{if(v.key!=="ArrowRight"&&v.key!=="ArrowLeft")return;v.preventDefault();const _=zs.findIndex(b=>b.id===s),y=v.key==="ArrowRight"?(_+1)%zs.length:(_-1+zs.length)%zs.length;i(zs[y].id)},className:U("min-h-[32px] rounded-t-md border-b-2 px-3 py-1.5 text-sm font-medium transition-colors",s===w.id?"border-primary text-content":"border-transparent text-muted hover:text-content"),children:w.label},w.id))}),t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{role:"tabpanel",id:"permissions-tabpanel-system","aria-labelledby":"permissions-tab-system",hidden:s!=="system",className:"flex flex-col gap-4 p-4",children:[o.jsx(Lv,{title:"Project defaults",subtitle:f?"Configured":"Native CLI behavior",active:n.type==="project",custom:Ho(t.document?.projectDefaults),onSelect:()=>r({type:"project"}),policy:t.document?.projectDefaults??null}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.busy&&o.jsx(Me,{size:14})]}),t.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):o.jsx("ul",{className:"flex flex-col gap-2",children:t.rows.map(w=>{const v=n.type==="agent"&&n.agentId===w.agent.id;return o.jsx("li",{children:o.jsx(Lv,{title:w.agent.name,subtitle:w.override?"Override":"Inherited",active:v,custom:Ho(w.override),onSelect:()=>r({type:"agent",agentId:w.agent.id,agentName:w.agent.name}),policy:w.override})},w.agent.id)})})]}),o.jsx(UO,{title:n.type==="project"?"Project defaults":`Override — ${n.agentName}`,draft:h,sourcePolicy:a,custom:d,canClear:n.type==="project"?t.document?.projectDefaults!=null:l?.override!=null,busy:t.busy,onSave:w=>void p(w),onClear:()=>void m()},n.type==="project"?"project":n.agentId),o.jsx(HO,{title:n.type==="project"?"Réseau — defaults projet":`Réseau — ${n.agentName}`,source:c,resolved:u,inherited:n.type==="agent"&&l?.systemOverride==null?t.systemDocument?.projectDefault??null:null,busy:t.busy,onSave:w=>void x(w)},`network-${n.type==="project"?"project":n.agentId}`)]}),o.jsx("div",{role:"tabpanel",id:"permissions-tabpanel-mcpTools","aria-labelledby":"permissions-tab-mcpTools",hidden:s!=="mcpTools",className:"flex min-h-0 flex-1 flex-col",children:s==="mcpTools"&&o.jsx(RO,{projectId:e,agents:t.agents})})]})}function Lv({title:e,subtitle:t,active:n,custom:r,policy:s,onSelect:i}){return o.jsxs("button",{type:"button",onClick:i,"aria-pressed":n,className:U("flex w-full min-w-0 items-center justify-between gap-3 rounded-md border px-3 py-2 text-left","transition-colors hover:border-border-strong hover:bg-raised",n?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e}),o.jsx("span",{className:"text-xs text-muted",children:t})]}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[r&&o.jsx("span",{className:"rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Custom"}),s&&o.jsx("span",{className:"rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary",children:WO[s.fallback]})]})]})}function HO({title:e,source:t,inherited:n,resolved:r,busy:s,onSave:i}){const l=t?.network??"",[a,c]=g.useState(l);g.useEffect(()=>{c(l)},[l]);const u=r?.control.mode==="readOnly",h=a!==l,d=r?.wanted??t?.network??n?.network??null,f=r?.effective??null,p=r?.runtimeLock.state==="locked",m=r?.runtimeLock.reason??r?.control.reason??null;return o.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[o.jsxs("header",{className:"border-b border-border px-3 py-2.5",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-xs text-muted",children:"Politique voulue, état effectif et verrou runtime."})]}),o.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[o.jsxs("div",{className:"grid grid-cols-1 gap-2 text-xs sm:grid-cols-2",children:[o.jsx(Uo,{label:"Wanted",value:d?`Réseau ${nd[d].toLowerCase()}`:"Non configuré"}),o.jsx(Uo,{label:"Effective",value:f?`Réseau ${nd[f].toLowerCase()}`:"Indisponible"}),o.jsx(Uo,{label:"Runtime",value:p?"Verrouillé par le runtime":"Aucun verrou connu"}),o.jsx(Uo,{label:"Control",value:u?"Lecture seule":"Modifiable"})]}),u&&o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:m??"Le runtime actif ne permet pas de modifier cette permission."}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Réseau"}),o.jsxs("select",{"aria-label":`${e} network`,value:a,disabled:s||u,onChange:x=>c(x.target.value),className:U("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"Non configuré"}),o.jsx("option",{value:"allow",children:"Réseau autorisé"}),o.jsx("option",{value:"deny",children:"Réseau interdit"}),o.jsx("option",{value:"ask",children:"Demande d'autorisation"})]})]}),n?.network&&!t?.network&&o.jsxs("p",{className:"text-xs text-muted",children:["Hérite du projet : Réseau ",nd[n.network].toLowerCase(),"."]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"Clear network",disabled:s||u||!t?.network,onClick:()=>i(null),children:"Clear"}),o.jsx(M,{size:"sm",variant:"primary","aria-label":"Save network",disabled:s||u||!h,loading:s&&h,onClick:()=>i(a?{network:a}:null),children:"Save"})]})]})]})}function Uo({label:e,value:t}){return o.jsxs("div",{className:"rounded-md border border-border/70 bg-raised px-3 py-2",children:[o.jsx("span",{className:"block text-[11px] font-medium uppercase text-faint",children:e}),o.jsx("span",{className:"text-xs text-content",children:t})]})}function UO({title:e,draft:t,sourcePolicy:n,custom:r,canClear:s,busy:i,onSave:l,onClear:a}){const[c,u]=g.useState(t),h=g.useRef(t);g.useEffect(()=>{u(p=>JSON.stringify(p)===JSON.stringify(h.current)?t:p),h.current=t},[t]);const d=g.useMemo(()=>JSON.stringify(c)!==JSON.stringify(t),[t,c]);function f(p,m){u(x=>({...x,[p]:m}))}return o.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[o.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-3 py-2.5",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:"truncate text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-xs text-muted",children:n?`${n.rules.length} rules`:"Not configured"})]}),r&&o.jsx("span",{className:"shrink-0 rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Advanced"})]}),o.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Fallback"}),o.jsxs("select",{"aria-label":`${e} fallback`,value:c.fallback,disabled:i,onChange:p=>u(m=>({...m,fallback:p.target.value})),className:U("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"ask",children:"Ask"}),o.jsx("option",{value:"allow",children:"Allow"}),o.jsx("option",{value:"deny",children:"Deny"})]})]}),o.jsx("div",{className:"grid grid-cols-1 gap-2",children:$O.map(p=>o.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:p.label}),o.jsx(qO,{value:c[p.key],disabled:i,label:p.label,onChange:m=>f(p.key,m)})]},p.key))}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:i||!s,onClick:a,children:"Clear"}),o.jsx(M,{size:"sm",variant:"primary",disabled:i||!d,loading:i&&d,onClick:()=>l(c),children:"Save"})]})]})]})}function qO({value:e,disabled:t,label:n,onChange:r}){const s=[{value:"none",label:"None"},{value:"allow",label:"Allow"},{value:"deny",label:"Deny"}];return o.jsx("div",{role:"group","aria-label":`${n} permission`,className:"grid grid-cols-3 overflow-hidden rounded-md border border-border",children:s.map(i=>o.jsx("button",{type:"button",disabled:t,"aria-pressed":e===i.value,onClick:()=>r(i.value),className:U("h-8 min-w-0 border-r border-border px-2 text-xs font-medium last:border-r-0","transition-colors disabled:cursor-not-allowed disabled:opacity-50",e===i.value?i.value==="deny"?"bg-danger/20 text-danger":i.value==="allow"?"bg-success/20 text-success":"bg-raised text-content":"bg-surface text-muted hover:bg-raised hover:text-content"),children:i.label},i.value))})}function Bp(e){return e.type.startsWith("issue")}function QS(e){return e.type.startsWith("sprint")}function VO(e){return e.replace(/[\s-]+/g,"").toUpperCase()}const KO=["open","inProgress","QA","closed"],GO=["low","medium","high","critical"],YO=["number","priority","status","title"],XO=["asc","desc"];function JS(e){return`tickets:listFilters:${e}`}function QO(e){return`tickets:pickerFilters:${e}`}function ZS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dv(e,t){if(!Array.isArray(e))return;const n=new Set(t),r=[];for(const s of e)typeof s=="string"&&n.has(s)&&!r.includes(s)&&r.push(s);return r.length>0?r:void 0}function JO(e){if(!ZS(e))return;const{field:t,direction:n}=e;if(typeof t=="string"&&YO.includes(t)&&typeof n=="string"&&XO.includes(n))return{field:t,direction:n}}function e0(e,t={}){if(!ZS(e))return{};const n={};typeof e.text=="string"&&e.text.length>0&&(n.text=e.text);const r=Dv(e.statuses,KO);r&&(n.statuses=r);const s=Dv(e.priorities,GO);if(s&&(n.priorities=s),typeof e.assignedAgentId=="string"&&e.assignedAgentId){const{validAgentIds:l}=t;(!l||l.has(e.assignedAgentId))&&(n.assignedAgentId=e.assignedAgentId)}const i=JO(e.sort);return i&&(n.sort=i),typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0&&(n.limit=e.limit),n}function ZO(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.assignedAgentId&&(t.assignedAgentId=e.assignedAgentId),e.sort&&(t.sort=e.sort),typeof e.limit=="number"&&(t.limit=e.limit),Object.keys(t).length>0?t:null}function eB(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.sort&&(t.sort=e.sort),Object.keys(t).length>0?t:null}function Rv(e,t,n){return e?e0(e.read(JS(t)),n):{}}function tB(e,t,n){if(!e)return;const r=ZO(n),s=JS(t);r?e.write(s,r):e.remove(s)}function Sr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function zp(e){const{ticket:t,system:n,uiPreferences:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(!1),[f,p]=g.useState(()=>Rv(r,e)),m=g.useRef(e);g.useEffect(()=>{m.current!==e&&(m.current=e,p(Rv(r,e)))},[e,r]),g.useEffect(()=>{tB(r,e,f)},[r,e,f]);const x=g.useMemo(()=>JSON.stringify(f),[f]),w=g.useCallback(async()=>{d(!0),u(null);try{i(await t.list(e,f))}catch(D){u(Sr(D))}finally{d(!1)}},[e,t,x]),v=g.useCallback(D=>{p(R=>{const E=R.statuses??[],O=E.includes(D)?E.filter(G=>G!==D):[...E,D],{statuses:I,...W}=R;return O.length>0?{...W,statuses:O}:W})},[]),_=g.useCallback(D=>{p(R=>{const E=R.priorities??[],O=E.includes(D)?E.filter(G=>G!==D):[...E,D],{priorities:I,...W}=R;return O.length>0?{...W,priorities:O}:W})},[]),y=g.useCallback(()=>{p(({statuses:D,priorities:R,...E})=>E)},[]),b=g.useCallback(async()=>{try{a(await t.listSprints(e))}catch(D){u(Sr(D))}},[e,t]),C=g.useCallback(async D=>{u(null);try{const R=await t.create(e,D);return await w(),R}catch(R){return u(Sr(R)),null}},[e,t,w]),S=g.useCallback(async(D,R)=>{u(null);try{const E=await t.read(e,D);return await t.setTicketSprint(e,D,R,E.version),await Promise.all([w(),b()]),!0}catch(E){return u(Sr(E)),!1}},[e,t,w,b]),N=g.useCallback(async D=>{u(null);try{const R=await t.createSprint(e,D);return await b(),R}catch(R){return u(Sr(R)),null}},[e,t,b]),L=g.useCallback(async(D,R)=>{u(null);try{const E=l.find(O=>O.id===D);return E?(await t.renameSprint(e,D,R,E.version),await b(),!0):!1}catch(E){return u(Sr(E)),!1}},[e,t,l,b]),A=g.useCallback(async(D,R)=>{u(null);const E=[...l].sort((G,P)=>G.order-P.order),O=E.findIndex(G=>G.id===D),I=R==="up"?O-1:O+1;if(O===-1||I<0||I>=E.length)return!1;const W=[...E];[W[O],W[I]]=[W[I],W[O]];try{return await t.reorderSprints(e,W.map(G=>G.id)),await b(),!0}catch(G){return u(Sr(G)),!1}},[e,t,l,b]),k=g.useCallback(async D=>{u(null);try{return await t.deleteSprint(e,D),await Promise.all([w(),b()]),!0}catch(R){return u(Sr(R)),!1}},[e,t,w,b]);return g.useEffect(()=>{w()},[w]),g.useEffect(()=>{b()},[b]),g.useEffect(()=>{if(!n)return;let D,R=!1;return n.onDomainEvent(E=>{Bp(E)&&w(),(QS(E)||E.type==="issueSprintChanged")&&b()}).then(E=>{R?E():D=E}),()=>{R=!0,D?.()}},[w,b,n]),{list:s,sprints:l,error:c,busy:h,query:f,setQuery:p,toggleStatus:v,togglePriority:_,clearFacets:y,refresh:w,create:C,assignSprint:S,createSprint:N,renameSprint:L,moveSprint:A,deleteSprint:k}}function t0(e){const{agent:t}=fe(),[n,r]=g.useState([]),[s,i]=g.useState(!1);g.useEffect(()=>{let c=!1;return i(!1),t.listAgents(e).then(u=>{c||(r(u),i(!0))}).catch(()=>{c||(r([]),i(!0))}),()=>{c=!0}},[e,t]);const l=g.useMemo(()=>new Map(n.map(c=>[c.id,c.name])),[n]);return{agents:n,nameOf:c=>l.get(c)??`${c.slice(0,8)}…`,loaded:s}}const Lc=["open","inProgress","QA","closed"],Ni=["low","medium","high","critical"],n0=["relatesTo","blocks","blockedBy","duplicates","dependsOn"];function Fp(e){switch(e){case"open":return"Open";case"inProgress":return"In progress";case"QA":return"QA";case"closed":return"Closed"}}function Dc(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Mv(e){switch(e){case"relatesTo":return"relates to";case"blocks":return"blocks";case"blockedBy":return"blocked by";case"duplicates":return"duplicates";case"dependsOn":return"depends on"}}function nB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function rB(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function r0(e){return U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function so({status:e}){return o.jsx("span",{className:r0(nB(e)),children:Fp(e)})}function io({priority:e}){return o.jsx("span",{className:r0(rB(e)),children:Dc(e)})}function _i({ticketRef:e,onOpen:t,className:n}){const r=U("inline-flex shrink-0 items-center rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",n);return t?o.jsx("button",{type:"button","aria-label":`open ticket ${e}`,className:U(r,"transition-colors hover:bg-primary/15 hover:text-primary"),onClick:()=>t(e),children:e}):o.jsx("code",{className:r,children:e})}const sB=/#\d+/g;function iB(e,t){const n=[];let r=0,s=0;for(const i of e.matchAll(sB)){const l=i.index??0;l>r&&n.push(e.slice(r,l)),n.push(o.jsx(_i,{ticketRef:i[0],onOpen:t},`ref-${s++}-${l}`)),r=l+i[0].length}return r0||r.length>0;return o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"search tickets",placeholder:a,value:e,onChange:d=>t(d.target.value)}),o.jsxs("fieldset",{"aria-label":"filter by status",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Statut"}),Lc.map(d=>o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[o.jsx("input",{type:"checkbox","aria-label":`filter status ${Fp(d)}`,className:"accent-primary",checked:n.includes(d),onChange:()=>s(d)}),o.jsx(so,{status:d})]},d))]}),o.jsxs("fieldset",{"aria-label":"filter by priority",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Priorité"}),Ni.map(d=>o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[o.jsx("input",{type:"checkbox","aria-label":`filter priority ${Dc(d)}`,className:"accent-primary",checked:r.includes(d),onChange:()=>i(d)}),o.jsx(io,{priority:d})]},d))]}),u&&o.jsxs("div",{"aria-label":"sort tickets",className:"flex flex-wrap items-center gap-2",children:[o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted",children:["Trier par",o.jsxs("select",{"aria-label":"sort tickets by",className:lB,value:c?.field??"",onChange:d=>{const f=d.target.value;u(f===""?void 0:{field:f,direction:c?.direction??"asc"})},children:[o.jsx("option",{value:"",children:"Par défaut"}),oB.map(d=>o.jsx("option",{value:d,children:s0[d]},d))]})]}),c&&o.jsx(M,{size:"sm",variant:"ghost","aria-label":`sort direction ${c.direction==="asc"?"ascending":"descending"}`,onClick:()=>u({field:c.field,direction:c.direction==="asc"?"desc":"asc"}),children:c.direction==="asc"?"Croissant ↑":"Décroissant ↓"})]}),l&&h&&o.jsx("div",{children:o.jsx(M,{size:"sm",variant:"ghost","aria-label":"clear filters",onClick:l,children:"Effacer"})})]})}function Iv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Rc(e,t={}){const{initialQuery:n,excludeRefs:r,debounceMs:s=200,refreshOnEvents:i,persistenceKey:l}=t,{ticket:a,system:c,uiPreferences:u}=fe(),h=g.useRef(null);if(h.current===null){const V=l&&u?e0(u.read(l)):{};h.current={statuses:n?.statuses??V.statuses,priorities:n?.priorities??V.priorities,assignedAgentId:n?.assignedAgentId??V.assignedAgentId,text:n?.text??V.text,sort:n?.sort??V.sort}}const d=h.current,[f,p]=g.useState({statuses:d.statuses,priorities:d.priorities,assignedAgentId:d.assignedAgentId}),[m,x]=g.useState(d.text??""),[w,v]=g.useState(m),[_,y]=g.useState(d.sort),[b,C]=g.useState([]),[S,N]=g.useState(void 0),[L,A]=g.useState(!1),[k,D]=g.useState(null),[R,E]=g.useState(0),O=g.useCallback(()=>E(V=>V+1),[]),I=n?.limit,W=(r??[]).join(","),G=g.useMemo(()=>new Set(r??[]),[W]);g.useEffect(()=>{const V=setTimeout(()=>v(m),s);return()=>clearTimeout(V)},[m,s]),g.useEffect(()=>{if(!l||!u)return;const V=w.trim(),Y=eB({...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...V?{text:V}:{},..._?{sort:_}:{}});Y?u.write(l,Y):u.remove(l)},[l,u,f,w,_]);const P=g.useMemo(()=>JSON.stringify({facets:f,text:w.trim(),sort:_,limit:I}),[f,w,_,I]),z=g.useRef(0),j=g.useCallback(V=>{const Y=w.trim();return{...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...f.assignedAgentId?{assignedAgentId:f.assignedAgentId}:{},...Y?{text:Y}:{},..._?{sort:_}:{},...I?{limit:I}:{},...V?{cursor:V}:{}}},[f,w,_,I]);g.useEffect(()=>{const V=++z.current;A(!0),D(null),a.list(e,j()).then(Y=>{V===z.current&&(C(Y.items),N(Y.nextCursor))}).catch(Y=>{V===z.current&&(D(Iv(Y)),C([]),N(void 0))}).finally(()=>{V===z.current&&A(!1)})},[P,e,a,R]),g.useEffect(()=>{if(!i||!c)return;let V,Y=!1;return c.onDomainEvent(oe=>{(Bp(oe)||QS(oe))&&E(pe=>pe+1)}).then(oe=>{Y?oe():V=oe}),()=>{Y=!0,V?.()}},[i,c]);const se=g.useCallback(()=>{if(L||!S)return;const V=++z.current;A(!0),D(null),a.list(e,j(S)).then(Y=>{V===z.current&&(C(oe=>[...oe,...Y.items]),N(Y.nextCursor))}).catch(Y=>{V===z.current&&D(Iv(Y))}).finally(()=>{V===z.current&&A(!1)})},[L,S,a,e,j]),q=g.useCallback(V=>{p(Y=>{const oe=Y.statuses??[],pe=oe.includes(V)?oe.filter(Pe=>Pe!==V):[...oe,V];return{...Y,statuses:pe.length>0?pe:void 0}})},[]),T=g.useCallback(V=>{p(Y=>{const oe=Y.priorities??[],pe=oe.includes(V)?oe.filter(Pe=>Pe!==V):[...oe,V];return{...Y,priorities:pe.length>0?pe:void 0}})},[]),re=g.useCallback(()=>{p(V=>({...V,statuses:void 0,priorities:void 0}))},[]),ee=g.useCallback(async V=>{const Y=await a.read(e,V);return{ref:Y.ref,id:Y.id,number:Y.number,title:Y.title,status:Y.status,priority:Y.priority}},[a,e]);return{rows:g.useMemo(()=>G.size===0?b:b.filter(V=>!G.has(V.ref)),[b,G]),busy:L,error:k,text:m,setText:x,statuses:f.statuses??[],priorities:f.priorities??[],toggleStatus:q,togglePriority:T,clearFacets:re,sort:_,setSort:y,hasMore:S!==void 0,loadMore:se,refresh:O,resolve:ee}}const Ov='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function i0({open:e,projectId:t,title:n="Sélectionner un ticket",confirmLabel:r="Sélectionner",selectionMode:s="single",excludeRefs:i,initialQuery:l,persistFilters:a=!0,onSelect:c,onClose:u}){return e?o.jsx(aB,{projectId:t,title:n,confirmLabel:r,selectionMode:s,excludeRefs:i,initialQuery:l,persistFilters:a,onSelect:c,onClose:u}):null}function aB({projectId:e,title:t,confirmLabel:n,selectionMode:r,excludeRefs:s,initialQuery:i,persistFilters:l,onSelect:a,onClose:c}){const u=Rc(e,{initialQuery:i,excludeRefs:s,persistenceKey:l?QO(e):void 0}),h=g.useRef(null),[d,f]=g.useState(!1),[p,m]=g.useState(null),[x,w]=g.useState(()=>new Set),v=r==="multi";g.useEffect(()=>{const S=document.activeElement,N=h.current;N?.querySelector(Ov)?.focus();function A(k){if(k.key==="Escape"){k.preventDefault(),c();return}if(k.key!=="Tab"||!N)return;const D=Array.from(N.querySelectorAll(Ov)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(D.length===0)return;const R=D[0],E=D[D.length-1],O=document.activeElement;k.shiftKey&&O===R?(k.preventDefault(),E.focus()):!k.shiftKey&&O===E&&(k.preventDefault(),R.focus())}return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A),S?.focus?.()}},[c]);function _(S){return S&&typeof S=="object"&&"message"in S?String(S.message):String(S)}function y(S){w(N=>{const L=new Set(N);return L.has(S)?L.delete(S):L.add(S),L})}async function b(S){if(!d){f(!0),m(null);try{const N=await u.resolve(S);a(N),c()}catch(N){m(_(N)),f(!1)}}}async function C(){if(!(d||x.size===0)){f(!0),m(null);try{const S=await Promise.all(Array.from(x).map(N=>u.resolve(N)));a(S),c()}catch(S){m(_(S)),f(!1)}}}return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindowNested},onMouseDown:S=>{S.target===S.currentTarget&&c()},children:o.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-label":t,className:"flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:t}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close ticket picker",onClick:c,children:"Close"})]}),o.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:o.jsx($p,{text:u.text,onTextChange:u.setText,statuses:u.statuses,priorities:u.priorities,onToggleStatus:u.toggleStatus,onTogglePriority:u.togglePriority,onClearFacets:u.clearFacets,sort:u.sort,onSortChange:u.setSort})}),(u.error||p)&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??u.error}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[u.busy&&u.rows.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading tickets…"})]}):u.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No matching tickets."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.rows.map(S=>{const N=x.has(S.ref);return o.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:o.jsxs("button",{type:"button","aria-label":`select ticket ${S.ref}`,...v?{role:"checkbox","aria-checked":N}:{},disabled:d,onClick:()=>v?y(S.ref):void b(S.ref),className:U("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none","disabled:cursor-not-allowed disabled:opacity-60",v&&N&&"bg-raised"),children:[v&&o.jsx("span",{"aria-hidden":"true",className:U("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",N?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),o.jsx(_i,{ticketRef:S.ref,className:"mt-0.5"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:S.title}),o.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[o.jsx(so,{status:S.status}),o.jsx(io,{priority:S.priority})]})]})},S.ref)})}),u.hasMore&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:u.busy,onClick:()=>u.loadMore(),children:"Load more"})})]}),v&&o.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3",children:[o.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[x.size," sélectionné",x.size>1?"s":""]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel ticket selection",onClick:c,children:"Annuler"}),o.jsx(M,{size:"sm","aria-label":"confirm ticket selection",loading:d,disabled:x.size===0||d,onClick:()=>void C(),children:x.size>0?`${n} (${x.size})`:n})]})]})]})})}function cB({projectId:e,vm:t,onClose:n}){const r=Rc(e,{refreshOnEvents:!0}),s=r.rows,i=[...t.sprints].sort((x,w)=>x.order-w.order),[l,a]=g.useState(""),[c,u]=g.useState({}),[h,d]=g.useState(null),[f,p]=g.useState(null);async function m(x){x.preventDefault();const w=l.trim()||`Sprint ${i.length+1}`;await t.createSprint(w)&&a("")}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"manage sprints",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:"Manage sprints"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"Close"})]}),t.error&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-5 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex-1 overflow-auto p-5",children:[o.jsxs("form",{onSubmit:m,className:"mb-5 flex items-center gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsx(ce,{"aria-label":"new sprint name",placeholder:"Sprint name (optional)",value:l,onChange:x=>a(x.target.value),className:"max-w-xs"}),o.jsx(M,{type:"submit",size:"sm",disabled:t.busy,children:"Create sprint"})]}),o.jsx("div",{className:"mb-5",children:o.jsx($p,{text:r.text,onTextChange:r.setText,statuses:r.statuses,priorities:r.priorities,onToggleStatus:r.toggleStatus,onTogglePriority:r.togglePriority,onClearFacets:r.clearFacets,sort:r.sort,onSortChange:r.setSort})}),r.error&&o.jsx("p",{role:"alert",className:"mb-4 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),i.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No sprints yet."}):o.jsx("ul",{className:"flex flex-col gap-4",children:i.map((x,w)=>{const v=s.filter(y=>y.sprintId===x.id),_=c[x.id]??x.name;return o.jsxs("li",{"aria-label":`sprint row ${x.name}`,className:"rounded-md border border-border p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",x.order]}),o.jsx(ce,{"aria-label":`rename sprint ${x.name}`,value:_,disabled:t.busy,onChange:y=>u(b=>({...b,[x.id]:y.target.value})),className:"max-w-xs"}),o.jsx(M,{size:"sm","aria-label":`save sprint ${x.name}`,disabled:t.busy||_.trim()===""||_.trim()===x.name,onClick:async()=>{await t.renameSprint(x.id,_.trim())&&u(b=>{const{[x.id]:C,...S}=b;return S})},children:"Save"}),o.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} up`,disabled:t.busy||w===0,onClick:()=>void t.moveSprint(x.id,"up"),children:"↑"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} down`,disabled:t.busy||w===i.length-1,onClick:()=>void t.moveSprint(x.id,"down"),children:"↓"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete sprint ${x.name}`,disabled:t.busy,className:"text-danger hover:text-danger",onClick:()=>d({id:x.id,name:x.name}),children:"Delete"})]})]}),o.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[v.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No tickets in this sprint."}):o.jsx("ul",{className:"flex flex-col gap-1",children:v.map(y=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx(_i,{ticketRef:y.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:y.title}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(so,{status:y.status}),o.jsx(io,{priority:y.priority})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`remove ${y.ref} from sprint`,disabled:t.busy,onClick:()=>void t.assignSprint(y.ref,null),children:"Remove"})]},y.ref))}),o.jsx("div",{className:"mt-1",children:o.jsx(M,{size:"sm",variant:"ghost","aria-label":`add ticket to sprint ${x.name}`,disabled:t.busy,onClick:()=>p({id:x.id,name:x.name}),children:"Ajouter des tickets"})})]})]},x.id)})}),r.hasMore&&o.jsx("div",{className:"mt-4 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:r.busy,onClick:()=>r.loadMore(),children:"Load more tickets"})})]}),h&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"delete sprint confirmation",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Supprimer le sprint « ",h.name," » ?"]}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Les tickets de ce sprint ne seront pas supprimés : ils seront simplement désassignés et retourneront au backlog « Sans sprint »."}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete sprint",disabled:t.busy,onClick:()=>d(null),children:"Annuler"}),o.jsx(M,{size:"sm","aria-label":"confirm delete sprint",className:"text-danger hover:text-danger",disabled:t.busy,onClick:async()=>{await t.deleteSprint(h.id),d(null)},children:"Supprimer"})]})]})}),o.jsx(i0,{open:f!==null,projectId:e,title:f?`Ajouter des tickets au sprint « ${f.name} »`:"Ajouter des tickets",confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:s.filter(x=>x.sprintId===f?.id).map(x=>x.ref),onSelect:x=>{const w=Array.isArray(x)?x:[x];if(f)for(const v of w)t.assignSprint(v.ref,f.id)},onClose:()=>p(null)})]})}const Bv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function uB({open:e,projectId:t,selectedSprintId:n,title:r="Sélectionner un sprint",onSelect:s,onClose:i}){return e?o.jsx(hB,{projectId:t,selectedSprintId:n??null,title:r,onSelect:s,onClose:i}):null}function dB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function hB({projectId:e,selectedSprintId:t,title:n,onSelect:r,onClose:s}){const{ticket:i}=fe(),l=g.useRef(null),[a,c]=g.useState(null),[u,h]=g.useState(null);g.useEffect(()=>{let p=!1;return h(null),i.listSprints(e).then(m=>{p||c(m)}).catch(m=>{p||(h(dB(m)),c([]))}),()=>{p=!0}},[i,e]),g.useEffect(()=>{const p=document.activeElement,m=l.current;m?.querySelector(Bv)?.focus();function w(v){if(v.key==="Escape"){v.preventDefault(),s();return}if(v.key!=="Tab"||!m)return;const _=Array.from(m.querySelectorAll(Bv)).filter(S=>S.offsetParent!==null||S===document.activeElement);if(_.length===0)return;const y=_[0],b=_[_.length-1],C=document.activeElement;v.shiftKey&&C===y?(v.preventDefault(),b.focus()):!v.shiftKey&&C===b&&(v.preventDefault(),y.focus())}return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w),p?.focus?.()}},[s]);const d=a?[...a].sort((p,m)=>p.order-m.order):[];function f(p){r(p),s()}return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindowNested},onMouseDown:p=>{p.target===p.currentTarget&&s()},children:o.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":n,className:"flex max-h-[80vh] w-full max-w-sm flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:n}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close sprint picker",onClick:s,children:"Close"})]}),u&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:u}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[o.jsxs("ul",{className:"flex flex-col divide-y divide-border",children:[o.jsx("li",{className:"py-1.5 first:pt-0",children:o.jsx(zv,{label:"Sans sprint",ariaLabel:"select no sprint",selected:t===null,onClick:()=>f(null)})}),a===null?o.jsxs("li",{className:"flex items-center gap-2 py-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading sprints…"})]}):d.map(p=>o.jsx("li",{className:"py-1.5 last:pb-0",children:o.jsx(zv,{label:p.name,ariaLabel:`select sprint ${p.name}`,count:p.ticketCount,selected:t===p.id,onClick:()=>f(p)})},p.id))]}),a!==null&&d.length===0&&!u&&o.jsx("p",{className:"mt-2 text-sm text-muted",children:"No sprints yet."})]})]})})}function zv({label:e,ariaLabel:t,count:n,selected:r,onClick:s}){return o.jsxs("button",{type:"button",role:"option","aria-selected":r,"aria-label":t,onClick:s,className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none",r&&"bg-raised"),children:[o.jsx("span",{"aria-hidden":"true",className:U("flex h-4 w-4 shrink-0 items-center justify-center text-[10px] font-bold",r?"text-primary":"text-transparent"),children:"✓"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e}),n!==void 0&&o.jsx("span",{className:"shrink-0 rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:n})]})}const tf=U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function fB({projectId:e,onOpen:t}){const n=zp(e),{agents:r,nameOf:s,loaded:i}=t0(e);g.useEffect(()=>{if(!i)return;const N=n.query.assignedAgentId;if(N&&!r.some(L=>L.id===N)){const{assignedAgentId:L,...A}=n.query;n.setQuery(A)}},[i,r,n.query,n.setQuery]);const[l,a]=g.useState(!1),[c,u]=g.useState(!1),[h,d]=g.useState(""),[f,p]=g.useState("medium"),[m,x]=g.useState(null),[w,v]=g.useState(!1),_=n.list?.items??[],y=new Set(n.sprints.map(N=>N.id)),b=n.sprints.map(N=>({sprint:N,tickets:_.filter(L=>L.sprintId===N.id)})).filter(N=>N.tickets.length>0),C=_.filter(N=>!N.sprintId||!y.has(N.sprintId));async function S(N){if(N.preventDefault(),!h.trim())return;const L=await n.create({title:h.trim(),priority:f});L&&(m&&await n.assignSprint(L.ref,m.id),d(""),p("medium"),x(null),a(!1),t(L.ref))}return o.jsxs(ke,{title:"Tickets",actions:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>a(N=>!N),children:l?"Cancel":"New"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"manage sprints",onClick:()=>u(!0),children:"Sprints"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"})]}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),l&&o.jsxs("form",{onSubmit:S,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsx(ce,{"aria-label":"new ticket title",placeholder:"Ticket title",value:h,onChange:N=>d(N.target.value)}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("select",{"aria-label":"new ticket priority",className:tf,value:f,onChange:N=>p(N.target.value),children:Ni.map(N=>o.jsx("option",{value:N,children:Dc(N)},N))}),o.jsx(M,{type:"submit",size:"sm",disabled:!h.trim()||n.busy,children:"Create"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs text-muted",children:"Sprint"}),o.jsx(M,{type:"button",size:"sm",variant:"ghost","aria-label":"choose sprint for new ticket",disabled:n.busy,onClick:()=>v(!0),className:"border border-border",children:m?m.name:"Sans sprint"})]})]}),o.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[o.jsx($p,{text:n.query.text??"",onTextChange:N=>n.setQuery({...n.query,text:N||void 0}),statuses:n.query.statuses??[],priorities:n.query.priorities??[],onToggleStatus:n.toggleStatus,onTogglePriority:n.togglePriority,onClearFacets:n.clearFacets,sort:n.query.sort,onSortChange:N=>{const{sort:L,...A}=n.query;n.setQuery(N?{...A,sort:N}:A)}}),o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:o.jsxs("select",{"aria-label":"filter by assignee",className:tf,value:n.query.assignedAgentId??"",onChange:N=>n.setQuery({...n.query,assignedAgentId:N.target.value||void 0}),children:[o.jsx("option",{value:"",children:"All assignees"}),r.map(N=>o.jsx("option",{value:N.id,children:N.name},N.id))]})})]}),n.busy&&n.list===null?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading tickets…"})]}):_.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No tickets."}):o.jsxs("div",{className:"flex flex-col gap-4",children:[b.map(N=>o.jsx(Fv,{heading:N.sprint.name,count:N.tickets.length,tickets:N.tickets,sprints:n.sprints,onOpen:t,nameOf:s,onAssignSprint:n.assignSprint},N.sprint.id)),C.length>0&&o.jsx(Fv,{heading:"Sans sprint",count:C.length,tickets:C,sprints:n.sprints,onOpen:t,nameOf:s,onAssignSprint:n.assignSprint})]}),n.list?.nextCursor&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Load more"})}),c&&o.jsx(cB,{projectId:e,vm:n,onClose:()=>u(!1)}),o.jsx(uB,{open:w,projectId:e,selectedSprintId:m?.id??null,title:"Sprint du nouveau ticket",onSelect:N=>x(N),onClose:()=>v(!1)})]})}function Fv({heading:e,count:t,tickets:n,sprints:r,onOpen:s,nameOf:i,onAssignSprint:l}){return o.jsxs("section",{"aria-label":`sprint section ${e}`,children:[o.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t})]}),o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.map(a=>o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(_i,{ticketRef:a.ref,onOpen:s,className:"mt-0.5"}),o.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>s(a.ref),children:[o.jsx("span",{className:"block truncate text-sm font-medium text-content hover:underline",children:a.title}),a.assignedAgentIds.length>0&&o.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted",children:a.assignedAgentIds.map(i).join(", ")})]}),o.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[o.jsx(so,{status:a.status}),o.jsx(io,{priority:a.priority})]})]}),o.jsx("div",{className:"mt-1 pl-6",children:o.jsxs("select",{"aria-label":`sprint for ${a.ref}`,className:tf,value:a.sprintId??"",onChange:c=>l(a.ref,c.target.value||null),children:[o.jsx("option",{value:"",children:"— No sprint —"}),r.map(c=>o.jsx("option",{value:c.id,children:c.name},c.id))]})})]},a.ref))})]})}function qo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function pB(e){return!!e&&typeof e=="object"&&typeof e.message=="string"&&e.message.includes("version conflict")}function l0(e,t){const{ticket:n,system:r}=fe(),[s,i]=g.useState(null),[l,a]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(0),w=g.useCallback(async()=>{p(!0),a(null);try{i(await n.read(e,t,!0)),u(!1),x(A=>A+1)}catch(A){a(qo(A))}finally{p(!1)}},[e,t,n]);g.useEffect(()=>{w()},[w]),g.useEffect(()=>{if(!r)return;let A,k=!1;return r.onDomainEvent(D=>{if(D.type==="issueDeleted"&&D.issueRef===t){d(!0);return}Bp(D)&&D.issueRef===t&&w()}).then(D=>{k?D():A=D}),()=>{k=!0,A?.()}},[w,r,t]);const v=g.useCallback(async(A,k)=>{if(!s)return!1;p(!0),a(null);try{const D=await A(s.version);return i({...D,carnet:k!==void 0?k:s.carnet}),u(!1),!0}catch(D){if(pB(D)){a("This ticket was modified elsewhere. It has been reloaded — re-apply your change.");try{i(await n.read(e,t,!0))}catch(R){a(qo(R))}u(!0),x(R=>R+1)}else a(qo(D));return!1}finally{p(!1)}},[s,n,e,t]),_=g.useCallback(A=>v(k=>n.update(e,t,{...A,expectedVersion:k})),[v,n,e,t]),y=g.useCallback(A=>v(k=>n.updateCarnet(e,t,A,k),A),[v,n,e,t]),b=g.useCallback((A,k)=>v(D=>n.link(e,t,A,k,D)),[v,n,e,t]),C=g.useCallback((A,k)=>v(D=>n.unlink(e,t,A,D,k)),[v,n,e,t]),S=g.useCallback((A,k)=>v(D=>n.assign(e,t,A,k,D)),[v,n,e,t]),N=g.useCallback(A=>v(k=>n.setTicketSprint(e,t,A,k)),[v,n,e,t]),L=g.useCallback(async()=>{p(!0),a(null);try{return await n.delete(e,t),!0}catch(A){return a(qo(A)),!1}finally{p(!1)}},[n,e,t]);return{ticket:s,error:l,conflict:c,deleted:h,busy:f,reloadCount:m,refresh:w,updateFields:_,saveCarnet:y,link:b,unlink:C,assign:S,setSprint:N,remove:L}}function Vo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function mB(e,t){const{ticket:n,profile:r}=fe(),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState([]),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef(null);w.current=l,g.useEffect(()=>{let b=!1;return(async()=>{try{const C=await r?.listProfiles()??[];b||i(C)}catch(C){b||x(Vo(C))}})(),()=>{b=!0}},[r]);const v=g.useCallback(async b=>{if(b){d(!0),x(null);try{const C=await n.openTicketChat(e,t,b);a(C.sessionId),u([])}catch(C){x(Vo(C))}finally{d(!1)}}},[n,e,t]),_=g.useCallback(async()=>{if(w.current){a(null),u([]);try{await n.closeTicketChat(e,t)}catch(b){x(Vo(b))}}},[n,e,t]),y=g.useCallback(async b=>{const C=b.trim();if(!l||!C||f)return;x(null),p(!0),u(N=>[...N,{role:"user",text:C},{role:"assistant",text:"",pending:!0}]);const S=N=>{u(L=>{const A=[...L],k=A.length-1;return k<0||A[k].role!=="assistant"?L:(N.kind==="textDelta"?A[k]={...A[k],text:A[k].text+N.text}:N.kind==="toolActivity"?A[k]={...A[k],text:`${A[k].text} -· ${N.label}`}:N.kind==="error"?A[k]={role:"assistant",text:`⚠️ ${N.message}`,pending:!1}:A[k]={role:"assistant",text:N.content,pending:!1},A)}),(N.kind==="final"||N.kind==="error")&&p(!1)};try{await n.sendTicketChat(l,C,S)}catch(N){x(Vo(N)),u(L=>{const A=[...L],k=A.length-1;return k>=0&&A[k].role==="assistant"&&A[k].pending&&(A[k]={...A[k],pending:!1}),A}),p(!1)}},[n,l,f]);return g.useEffect(()=>()=>{w.current&&n.closeTicketChat(e,t).catch(()=>{})},[n,e,t]),{profiles:s,sessionId:l,turns:c,opening:h,busy:f,error:m,open:v,close:_,send:y}}const gB=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function xB({projectId:e,ticketRef:t}){const n=mB(e,t),[r,s]=g.useState(""),[i,l]=g.useState(""),a=g.useRef(null);g.useEffect(()=>{const h=a.current;h&&(h.scrollTop=h.scrollHeight)},[n.turns]);const c=n.sessionId!==null;function u(){const h=i.trim();!h||n.busy||(n.send(h),l(""))}return o.jsxs("div",{className:"flex flex-col gap-3",children:[c?o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-xs text-muted",children:"Conversation ouverte — l'assistant peut lire le projet et éditer ce ticket."}),o.jsx(M,{size:"sm",variant:"ghost",disabled:n.busy,onClick:()=>void n.close(),children:"Fermer la conversation"})]}),o.jsx("div",{ref:a,className:"flex max-h-96 min-h-32 flex-col gap-2 overflow-auto rounded-md border border-border bg-raised/40 p-3",children:n.turns.length===0?o.jsx("p",{className:"m-auto text-xs text-muted",children:"Démarrez la conversation en décrivant ce que l'assistant doit faire sur ce ticket."}):n.turns.map((h,d)=>o.jsx("div",{className:U("flex",h.role==="user"?"justify-end":"justify-start"),children:o.jsxs("div",{className:U("max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm",h.role==="user"?"bg-primary/15 text-content":"bg-surface text-content"),children:[h.text,h.pending&&o.jsx("span",{className:"ml-1 inline-flex items-center align-middle text-muted",children:o.jsx(Me,{size:12})})]})},d))}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("textarea",{"aria-label":"message à l'assistant",className:U("min-h-10 flex-1 resize-none rounded-md bg-raised p-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),rows:2,placeholder:"Votre message…",value:i,disabled:n.busy,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),u())}}),o.jsx(M,{size:"sm",disabled:!i.trim()||n.busy,loading:n.busy,onClick:u,children:"Envoyer"})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("select",{"aria-label":"profil de l'assistant",className:gB,value:r,disabled:n.opening||n.profiles.length===0,onChange:h=>s(h.target.value),children:[o.jsx("option",{value:"",children:n.profiles.length===0?"Aucun profil disponible":"Choisir un profil IA…"}),n.profiles.map(h=>o.jsx("option",{value:h.id,children:h.name},h.id))]}),o.jsx(M,{size:"sm",disabled:!r||n.opening,loading:n.opening,onClick:()=>void n.open(r),children:"Ouvrir la conversation"})]}),n.error&&o.jsx("p",{role:"alert",className:"text-xs text-danger",children:n.error})]})}const Ko=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),$v=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");async function vB(e){return typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):!1}function Zi({title:e,hint:t,children:n}){return o.jsxs("section",{className:"flex flex-col gap-2 border-b border-border px-5 py-4",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:e}),t&&o.jsx("p",{className:"mt-0.5 text-xs text-muted",children:t})]}),n]})}function _B({projectId:e,ticketRef:t,onClose:n,onOpenRef:r}){const s=l0(e,t),{agents:i,nameOf:l}=t0(e),a=s.ticket,[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState("relatesTo"),[w,v]=g.useState(""),[_,y]=g.useState(!1),[b,C]=g.useState(!1),[S,N]=g.useState(!1),[L,A]=g.useState(!1),[k,D]=g.useState(!1);g.useEffect(()=>{s.deleted&&n()},[s.deleted,n]);const R=s.reloadCount,E=g.useRef(-1),O=g.useRef(null);g.useEffect(()=>{if(!a||E.current===R)return;E.current=R;const q=a.carnet??"",T=O.current;T===null||s.conflict?(u(a.title),d(a.description),p(q)):(u(ee=>ee===T.title?a.title:ee),d(ee=>ee===T.description?a.description:ee),p(ee=>ee===T.carnet?q:ee)),O.current={title:a.title,description:a.description,carnet:q}},[a,R,s.conflict]);const I=!!a&&(c!==a.title||h!==a.description),W=!!a&&f!==(a.carnet??""),G=I||W,P=i.filter(q=>!a?.assignedAgentIds.includes(q.id));function z(){G?C(!0):n()}async function j(){let q=!0;I&&(q=await s.updateFields({title:c,description:h})&&q),q&&W&&(q=await s.saveCarnet(f)&&q),C(!1),q&&n()}async function se(){if(!a)return;await vB(`Travaille sur le ticket ${a.ref} : ${a.title}`)&&(y(!0),window.setTimeout(()=>y(!1),1200))}return o.jsxs(Fh,{open:!0,title:`ticket ${t}`,size:"xl",onClose:z,children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(_i,{ticketRef:t}),a&&o.jsx(so,{status:a.status}),a&&o.jsx(io,{priority:a.priority}),o.jsx("span",{className:"truncate text-sm font-medium text-content",children:a?.title??t})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:!a,onClick:()=>void se(),title:"Copy a delegation prompt to hand this ticket to an agent",children:_?"Copied":"Delegation context"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!a||s.busy,onClick:()=>N(!0),className:"text-danger hover:text-danger",title:"Supprimer définitivement ce ticket",children:"Supprimer"})]})]}),s.conflict&&o.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-1 py-2 text-sm text-warning",children:"This ticket was modified elsewhere and reloaded. Re-apply your change."}),s.error&&!s.conflict&&o.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-1 py-2 text-sm text-danger",children:s.error}),s.busy&&!a?o.jsxs("div",{className:"flex items-center gap-2 py-5 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Loading ticket…"})]}):a?o.jsxs("div",{className:"-mx-4",children:[o.jsxs(Zi,{title:"Details",children:[o.jsx("label",{className:"text-xs font-medium text-muted",htmlFor:"td-title",children:"Title"}),o.jsx(ce,{id:"td-title",value:c,onChange:q=>u(q.target.value),disabled:s.busy}),o.jsx("label",{className:"mt-2 text-xs font-medium text-muted",htmlFor:"td-desc",children:"Description"}),o.jsx("textarea",{id:"td-desc",className:U($v,"min-h-24"),value:h,onChange:q=>d(q.target.value),disabled:s.busy}),h.trim()&&o.jsx("p",{className:"whitespace-pre-wrap break-words rounded-md bg-raised/40 px-3 py-2 text-xs text-muted",children:iB(h,r)}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsx(M,{size:"sm",disabled:!I||s.busy,loading:s.busy&&I,onClick:()=>void s.updateFields({title:c,description:h}),children:"Save changes"}),I&&o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>{u(a.title),d(a.description)},children:"Reset"})]})]}),o.jsx(Zi,{title:"Status & priority",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Status",o.jsx("select",{"aria-label":"ticket status",className:Ko,value:a.status,disabled:s.busy,onChange:q=>void s.updateFields({status:q.target.value}),children:Lc.map(q=>o.jsx("option",{value:q,children:Fp(q)},q))})]}),o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Priority",o.jsx("select",{"aria-label":"ticket priority",className:Ko,value:a.priority,disabled:s.busy,onChange:q=>void s.updateFields({priority:q.target.value}),children:Ni.map(q=>o.jsx("option",{value:q,children:Dc(q)},q))})]})]})}),o.jsxs(Zi,{title:"Carnet",hint:"Markdown notebook scoped to this ticket only — separate from project memory. Saving replaces the whole carnet.",children:[o.jsx("textarea",{"aria-label":"ticket carnet",className:U($v,"min-h-40 font-mono"),value:f,onChange:q=>p(q.target.value),disabled:s.busy}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(M,{size:"sm",disabled:!W||s.busy,loading:s.busy&&W,onClick:()=>void s.saveCarnet(f),children:"Save carnet"}),W&&o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>p(a.carnet??""),children:"Reset"})]})]}),o.jsxs(Zi,{title:"Linked tickets",children:[a.links.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No linked tickets."}):o.jsx("ul",{className:"flex flex-col gap-1",children:a.links.map(q=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"text-xs text-muted",children:Mv(q.kind)}),o.jsx(_i,{ticketRef:q.targetRef,onOpen:r}),o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>void s.unlink(q.targetRef,q.kind),children:"Remove"})]},`${q.kind}-${q.targetRef}`))}),o.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[o.jsx("select",{"aria-label":"link kind",className:Ko,value:m,disabled:s.busy,onChange:q=>x(q.target.value),children:n0.map(q=>o.jsx("option",{value:q,children:Mv(q)},q))}),o.jsx(M,{size:"sm","aria-label":"add link",disabled:s.busy,onClick:()=>A(!0),children:"Add link"})]})]}),o.jsxs(Zi,{title:"Assigned agents",hint:"Only agents known to this project can be assigned.",children:[a.assignedAgentIds.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No agents assigned."}):o.jsx("ul",{className:"flex flex-wrap gap-2",children:a.assignedAgentIds.map(q=>o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[l(q),o.jsx("button",{type:"button","aria-label":`unassign ${l(q)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:s.busy,onClick:()=>void s.assign(q,!1),children:"×"})]},q))}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsxs("select",{"aria-label":"assign agent",className:Ko,value:w,disabled:s.busy||P.length===0,onChange:q=>v(q.target.value),children:[o.jsx("option",{value:"",children:P.length===0?"No more agents":"Select an agent…"}),P.map(q=>o.jsx("option",{value:q.id,children:q.name},q.id))]}),o.jsx(M,{size:"sm",disabled:!w||s.busy,onClick:async()=>{await s.assign(w,!0)&&v("")},children:"Assign"})]})]}),o.jsx(i0,{open:L,projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...a.links.map(q=>q.targetRef)],onSelect:q=>{const T=Array.isArray(q)?q[0]:q;T&&s.link(T.ref,m),A(!1)},onClose:()=>A(!1)})]}):o.jsx("div",{className:"flex items-center justify-center py-10 text-sm text-muted",children:"Ticket not found."}),a&&o.jsx("div",{className:"pointer-events-none sticky bottom-0 z-10 -mx-4 -mb-4 flex justify-end px-4 pb-4 pt-2",children:o.jsx(M,{"aria-label":"ouvrir l'assistant IA",className:"pointer-events-auto shadow-lg",onClick:()=>D(!0),children:"🤖 Assistant IA"})}),o.jsx(Fh,{open:k,title:`Assistant IA — ${t}`,size:"lg",onClose:()=>D(!1),children:o.jsx(xB,{projectId:e,ticketRef:t})}),b&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"unsaved changes",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Modifications non sauvegardées"}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Vous avez des modifications non sauvegardées. Voulez-vous les sauvegarder avant de fermer ?"}),o.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel close",disabled:s.busy,onClick:()=>C(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close without saving",disabled:s.busy,onClick:n,className:"text-danger hover:text-danger",children:"Fermer sans sauvegarder"}),o.jsx(M,{size:"sm","aria-label":"save and close",loading:s.busy,disabled:s.busy,onClick:()=>void j(),children:"Sauvegarder"})]})]})}),S&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"confirmer la suppression",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Supprimer le ticket"}),o.jsxs("p",{className:"mt-2 text-sm text-muted",children:["Supprimer définitivement le ticket ",t," ? Cette action est irréversible."]}),o.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete",disabled:s.busy,onClick:()=>N(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger","aria-label":"confirm delete",loading:s.busy,disabled:s.busy,onClick:async()=>{await s.remove()&&N(!1)},children:"Supprimer"})]})]})})]})}function yB({projectId:e}){const[t,n]=g.useState(null);return o.jsxs(o.Fragment,{children:[o.jsx(fB,{projectId:e,onOpen:n}),t&&o.jsx(_B,{projectId:e,ticketRef:t,onClose:()=>n(null),onOpenRef:n},`${e}-${t}`)]})}function Wv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function o0({projectId:e}){const{project:t}=fe(),[n,r]=g.useState(""),[s,i]=g.useState(""),[l,a]=g.useState(!1),[c,u]=g.useState(null);g.useEffect(()=>{let f=!1;return a(!0),u(null),t.readProjectContext(e).then(p=>{f||(r(p),i(p))}).catch(p=>{f||u(Wv(p))}).finally(()=>{f||a(!1)}),()=>{f=!0}},[t,e]);async function h(){a(!0),u(null);try{await t.updateProjectContext(e,n),i(n)}catch(f){u(Wv(f))}finally{a(!1)}}const d=n!==s;return o.jsxs(ke,{title:"Project Context",className:"flex flex-col gap-0",children:[c&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:c}),o.jsx("div",{className:"border-b border-border px-4 py-2",children:o.jsx("code",{className:"text-xs text-muted",children:".ideai/CONTEXT.md"})}),o.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[o.jsx("textarea",{"aria-label":"project context",value:n,onChange:f=>r(f.target.value),rows:18,className:U("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:l}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l&&o.jsx(Me,{size:14}),o.jsx(M,{variant:"primary",disabled:l||!d,onClick:()=>void h(),children:"Save"})]})]})]})}function a0({panel:e,projectId:t,projectRoot:n,onOpenConversation:r}){switch(e){case"context":return o.jsx(o0,{projectId:t});case"work":return o.jsx(iT,{projectId:t,onOpenConversation:r});case"tickets":return o.jsx(yB,{projectId:t});case"agents":return o.jsx(_w,{projectId:t,projectRoot:n});case"templates":return o.jsx($S,{projectId:t});case"skills":return o.jsx(WS,{projectId:t});case"permissions":return o.jsx(XS,{projectId:t});case"memory":return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(KS,{projectId:t}),o.jsx(VS,{})]});case"git":return o.jsx(Dw,{projectId:t})}}const Hn={projects:"Projects",context:"Project context",work:"Work state",tickets:"Tickets",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Memory",git:"Git"};function Ar(e,t){return e[t]??"closed"}function ls(e,t){return typeof e=="object"&&e.dock===t}function Hv(e,t){return Object.keys(Hn).filter(n=>ls(Ar(e,n),t))}function bB(e){return Object.keys(Hn).filter(t=>Ar(e,t)==="floating")}function rd(e){return e==="detached"}function wB(e){return e!=="projects"&&e in Hn}function SB(e,t){let n=!1;const r={...e};for(const s of t){if(!s.visible||!wB(s.panel))continue;const i=s.panel;Ar(e,i)==="closed"&&(r[i]="detached",n=!0)}return n?r:e}const kB={projects:"md",context:"lg",work:"lg",tickets:"lg",agents:"lg",templates:"lg",skills:"lg",permissions:"md",memory:"lg",git:"lg"};function CB(e){return e.type==="backgroundTaskChanged"&&(e.state==="completed"||e.state==="failed"||e.state==="cancelled"||e.state==="delivered")}function jB(){const e=NL(),{system:t,window:n,focusedProject:r,git:s}=fe(),[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState({}),[d,f]=g.useState(340),[p,m]=g.useState(340),[x,w]=g.useState(null),[v,_]=g.useState(null),[y,b]=g.useState(null),[C,S]=g.useState([]),N=e.openTabs.find(B=>B.id===e.activeTabId)??null,[L,A]=g.useState(!1);g.useEffect(()=>{if(!N){A(!1);return}let B=!1;return s.branches(N.id).then(()=>{B||A(!0)}).catch(()=>{B||A(!1)}),()=>{B=!0}},[s,N?.id]);const{registry:k}=gp(),R=gA(k,{projectOpen:N!==null,gitRepository:L,agentSelected:!1,terminalFocused:!1,layoutCellFocused:!1});g.useEffect(()=>{_(null),b(null)},[N?.id]),g.useEffect(()=>{r?.setFocusedProject(N?{id:N.id,name:N.name,root:N.root}:null)},[r,N?.id,N?.name,N?.root]),g.useEffect(()=>{let B,he=!1;return t.onDomainEvent(ue=>{if(!CB(ue))return;const Ee={id:`${ue.taskId}-${ue.state}-${Date.now()}`,projectId:ue.projectId,agentId:ue.agentId,taskId:ue.taskId,state:ue.state};S(dt=>[...dt.slice(-2),Ee]),window.setTimeout(()=>{S(dt=>dt.filter(Rn=>Rn.id!==Ee.id))},7e3)}).then(ue=>{he?ue():B=ue}),()=>{he=!0,B?.()}},[t]);const E=v?.kind??"terminal",O=i.trim().length>0&&a.trim().length>0&&!e.busy;async function I(B){B.preventDefault(),O&&(await e.createProject(i.trim(),a.trim()),l(""),c(""))}async function W(){const B=await t.pickFolder();B!==null&&c(B)}function G(B,he){h(ue=>{const Ee={...ue};if(he==="floating")for(const dt of Object.keys(Ee))dt!==B&&Ee[dt]==="floating"&&delete Ee[dt];return Ee[B]=he,Ee})}function P(B){h(he=>{if(!(B in he))return he;const ue={...he};return delete ue[B],ue})}function z(){h(B=>{let he=!1;const ue={...B};for(const Ee of Object.keys(ue))ue[Ee]==="floating"&&(delete ue[Ee],he=!0);return he?ue:B})}function j(B){N&&n.openViewWindow(B).then(()=>G(B,"detached")).catch(()=>{})}g.useEffect(()=>{let B,he=!1;return n.onViewWindowClosed(({panel:ue})=>{h(Ee=>Ee[ue]==="detached"?(()=>{const dt={...Ee};return delete dt[ue],dt})():Ee)}).then(ue=>{he?ue():B=ue}),()=>{he=!0,B?.()}},[n]),g.useEffect(()=>{let B=!1;return n.listOpenViewWindows().then(he=>{B||h(ue=>SB(ue,he))}).catch(()=>{}),()=>{B=!0}},[n]);function se(B){b(B),z()}const q=["context","work","tickets","agents","templates","skills","permissions","memory","git","projects"];function T(B){const he=Ar(u,B),ue=[{id:"closed",label:"Fermé",active:he==="closed",onSelect:()=>P(B)},{id:"floating",label:"Flottant",active:he==="floating",onSelect:()=>G(B,"floating")},{id:"dock-left",label:"Ancré à gauche",active:ls(he,"left"),onSelect:()=>G(B,{dock:"left"})},{id:"dock-right",label:"Ancré à droite",active:ls(he,"right"),onSelect:()=>G(B,{dock:"right"})}];return B!=="projects"&&ue.push({id:"detached",label:"Fenêtre détachée",active:rd(he),disabled:!N,onSelect:()=>j(B)}),ue}const re=[{id:"panels",label:"Panneaux",items:[...q.map(B=>({id:B,label:Hn[B],active:Ar(u,B)!=="closed",onSelect:()=>{},submenu:T(B)})),...R.itemsFor("panels")]},...R.topLevelMenus,{id:"settings",label:"Paramètres",items:[...Tw.map(B=>({id:B,label:Aw[B],active:x===B,onSelect:()=>{w(B),z()}})),...R.itemsFor("settings")]}],ee=o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("form",{onSubmit:I,className:"flex flex-col gap-2",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"New project"}),o.jsx(ce,{"aria-label":"project name",placeholder:"Project name",value:i,onChange:B=>l(B.target.value)}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ce,{"aria-label":"project root",placeholder:"/absolute/project/root",value:a,onChange:B=>c(B.target.value),className:"flex-1"}),o.jsx(M,{type:"button","aria-label":"browse project folder",onClick:()=>void W(),disabled:e.busy,children:"Browse…"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{type:"submit",variant:"primary",disabled:!O,className:"flex-1",children:"Create project"}),o.jsx(M,{type:"button",onClick:()=>void e.refresh(),disabled:e.busy,children:"Refresh"})]})]}),o.jsx(ke,{title:"Known projects",children:e.projects.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No projects yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:e.projects.map(B=>o.jsxs("li",{className:"flex items-center justify-between gap-2 py-2 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"font-medium text-content",children:B.name}),o.jsx("code",{className:"truncate text-xs text-muted",children:B.root})]}),o.jsx(M,{size:"sm",onClick:()=>void e.openProject(B.id),children:"Open"})]},B.id))})})]});function Q(B){return B==="projects"?ee:N?o.jsx(a0,{panel:B,projectId:N.id,projectRoot:N.root,onOpenConversation:se}):o.jsx("p",{className:"text-sm text-muted",children:"Open a project to use this panel."})}const V=!N&&Ar(u,"projects")==="closed",Y=Hv(u,"left"),oe=Hv(u,"right"),pe=bB(u);function Pe({panel:B}){const he=Ar(u,B),ue=Hn[B],Ee="bg-raised text-content ring-1 ring-border-strong";return o.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(sr,{size:"sm",title:"Ancré à gauche","aria-label":`Ancré à gauche — ${ue}`,"aria-pressed":ls(he,"left"),className:U(ls(he,"left")&&Ee),onClick:()=>G(B,{dock:"left"}),children:"⇤"}),o.jsx(sr,{size:"sm",title:"Ancré à droite","aria-label":`Ancré à droite — ${ue}`,"aria-pressed":ls(he,"right"),className:U(ls(he,"right")&&Ee),onClick:()=>G(B,{dock:"right"}),children:"⇥"}),o.jsx(sr,{size:"sm",title:"Flottant","aria-label":`Flottant — ${ue}`,"aria-pressed":he==="floating",className:U(he==="floating"&&Ee),onClick:()=>G(B,"floating"),children:"□"}),B!=="projects"&&o.jsx(sr,{size:"sm",title:"Fenêtre détachée","aria-label":`Fenêtre détachée — ${ue}`,"aria-pressed":rd(he),disabled:!N,className:U(rd(he)&&Ee),onClick:()=>j(B),children:"↗"}),o.jsx(sr,{size:"sm",title:"Fermé","aria-label":`Fermé — ${ue}`,onClick:()=>P(B),children:"×"})]})}function $(B){return o.jsxs("section",{"aria-label":`${Hn[B]} panel`,className:"flex min-h-0 flex-1 flex-col border-b border-border last:border-b-0",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:Hn[B]}),o.jsx(Pe,{panel:B})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3",children:Q(B)})]},B)}return o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),o.jsx(EL,{items:e.openTabs.map(B=>({id:B.id,label:B.name})),activeTabId:e.activeTabId,onSelect:B=>e.activateTab(B),onClose:B=>void e.closeTab(B),projectsPanelOpen:Ar(u,"projects")!=="closed",onOpenProjectsPanel:()=>{w(null),G("projects","floating")}}),o.jsx(VP,{menus:re}),o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[Y.length>0&&o.jsx(dx,{side:"left",width:d,onResize:f,"aria-label":"left dock",children:Y.map($)}),o.jsx("main",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:x?o.jsx(gL,{section:x,onSectionChange:w,onClose:()=>w(null)}):N&&y?o.jsx(uT,{projectId:N.id,conversationId:y,onClose:()=>b(null)},`${N.id}-${y}`):N?o.jsxs(o.Fragment,{children:[o.jsx(HA,{projectId:N.id,onActiveLayoutChange:_}),E==="gitGraph"?o.jsx(jL,{projectId:N.id},`${N.id}-${v?.id??"default"}-graph`):o.jsx(IA,{projectId:N.id,cwd:N.root,layoutId:v?.id,onOpenConversation:se,onOpenPluginsSettings:()=>{w("plugins"),z()}},`${N.id}-${v?.id??"default"}`)]}):o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-xl",children:V?ee:o.jsx("p",{className:"text-sm text-muted",children:"Select or create a project to get started."})})})}),oe.length>0&&o.jsx(dx,{side:"right",width:p,onResize:m,"aria-label":"right dock",children:oe.map($)})]}),pe.map(B=>o.jsxs(Fh,{open:!0,title:Hn[B],size:kB[B],onClose:()=>P(B),children:[o.jsx("div",{className:"mb-3 flex justify-end border-b border-border pb-3",children:o.jsx(Pe,{panel:B})}),Q(B)]},B)),C.length>0&&o.jsx("div",{className:"fixed bottom-4 right-4 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",style:{zIndex:Sn.toast},children:C.map(B=>o.jsxs("button",{type:"button",className:"rounded-md border border-border bg-surface px-3 py-2 text-left shadow-lg hover:border-border-strong",onClick:()=>{e.openTabs.some(ue=>ue.id===B.projectId)&&e.activateTab(B.projectId),w(null),b(null),G("work","floating"),S(ue=>ue.filter(Ee=>Ee.id!==B.id))},children:[o.jsxs("span",{className:"block text-sm font-medium text-content",children:["Background task ",B.state]}),o.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted",children:[B.agentId.slice(0,8)," · ",B.taskId.slice(0,8)]})]},B.id))})]})}const NB=5;function EB(e){if(e.totalWorkCount===1)return"1 travail actif sera interrompu si vous quittez IdeA maintenant.";const t=[];return e.busyAgentCount>0&&t.push(e.busyAgentCount===1?"1 agent travaille encore":`${e.busyAgentCount} agents travaillent encore`),e.activeBackgroundTaskCount>0&&t.push(e.activeBackgroundTaskCount===1?"1 tâche de fond est encore active":`${e.activeBackgroundTaskCount} tâches de fond sont encore actives`),`${t.join(" et ")}. Ces travaux seront interrompus si vous quittez IdeA maintenant.`}function PB(e){return e.kind==="busyAgent"?`Agent ${e.agentName} — ${e.projectName}`:`Tâche de fond ${e.taskId.slice(0,8)} — ${e.projectName}`}function AB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Uv="app-exit-confirm-title",qv="app-exit-confirm-desc";function TB(){const{system:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{let p=!1,m;return e.onAppExitWorkGuard(x=>{n(x)}).then(x=>{p?x():m=x}).catch(()=>{}),()=>{p=!0,m?.()}},[e]),g.useEffect(()=>{t&&a.current?.focus()},[t!=null]);function u(){r||(n(null),l(null))}async function h(){s(!0),l(null);try{await e.confirmAppExit()}catch(p){l(AB(p))}finally{s(!1)}}if(g.useEffect(()=>{if(!t)return;function p(m){if(m.key==="Escape"){m.preventDefault(),u();return}if(m.key!=="Tab")return;const x=c.current?.querySelectorAll('button:not(:disabled), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(!x||x.length===0)return;const w=x[0],v=x[x.length-1];m.shiftKey&&document.activeElement===w?(m.preventDefault(),v.focus()):!m.shiftKey&&document.activeElement===v&&(m.preventDefault(),w.focus())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t!=null,r]),!t)return null;const d=t.details.slice(0,NB),f=t.details.length-d.length;return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.toast},children:o.jsxs("div",{ref:c,role:"alertdialog","aria-modal":"true","aria-labelledby":Uv,"aria-describedby":qv,onClick:p=>p.stopPropagation(),className:"flex w-full max-w-[520px] min-w-[440px] flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{id:Uv,className:"text-sm font-semibold text-content",children:"Du travail est encore en cours"}),o.jsx("p",{id:qv,className:"text-sm text-content",children:EB(t)}),o.jsx("p",{className:"text-sm text-muted",children:"Annulez la fermeture pour laisser les agents et les tâches se terminer."}),d.length>0&&o.jsxs("ul",{className:"flex flex-col gap-1 rounded-md bg-canvas p-2 text-xs text-muted",children:[d.map((p,m)=>o.jsx("li",{children:`• ${PB(p)}`},m)),f>0&&o.jsxs("li",{children:["+ ",f," autre",f>1?"s":""]})]}),i&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"IdeA n'a pas pu quitter correctement. Réessayez ou consultez les logs."}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",disabled:r,onClick:u,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger",disabled:r,loading:r,onClick:()=>void h(),children:r?"Fermeture…":"Quitter quand même"})]})]})})}function LB(){const{system:e,profile:t}=fe(),[n,r]=g.useState(null),[s,i]=g.useState(null),[l,a]=g.useState([]),[c,u]=g.useState(null);return g.useEffect(()=>{let h,d=!1;return e.onDomainEvent(f=>a(p=>[...p,f])).then(f=>{d?f():h=f}).catch(()=>{}),e.health("ui-boot").then(f=>r(f)).catch(f=>i(DB(f))),()=>{d=!0,h?.()}},[e]),g.useEffect(()=>{let h=!1;return t.firstRunState().then(d=>{h||u(d.isFirstRun)}).catch(()=>{h||u(!1)}),()=>{h=!0}},[t]),o.jsx(RP,{children:o.jsxs(cA,{children:[o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between border-b border-border px-6 py-3",children:[o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"IdeA"}),o.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"tauri"})]}),o.jsx(gw,{justify:"end",children:o.jsx("span",{className:"text-xs text-faint",children:n?o.jsxs(o.Fragment,{children:["backend ",o.jsx("span",{className:"text-success",children:"●"})," v",n.version," ·"," ",l.length," events"]}):s?o.jsx("span",{className:"text-danger",children:"backend unavailable"}):o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx(Me,{size:12})," checking…"]})})})]}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[s&&o.jsx(ke,{className:"mx-4 mt-4 border-danger/40",children:o.jsxs("p",{className:"text-sm text-danger",children:["Error: ",s]})}),c?o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-xl",children:o.jsx(Cw,{onDone:()=>u(!1)})})}):o.jsx(jB,{})]})]}),o.jsx(TB,{})]})})}function DB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const RB=new Set(Object.keys(Hn).filter(e=>e!=="projects"));function MB(e){const n=new URLSearchParams(e).get("panel");return!n||!RB.has(n)?null:{panel:n}}function IB({panel:e}){const{focusedProject:t}=fe(),[n,r]=g.useState(void 0);return g.useEffect(()=>{let s=!1,i;return t.getFocusedProject().then(l=>{s||r(l)}).catch(()=>{s||r(null)}),t.onFocusedProjectChanged(l=>{s||r(l)}).then(l=>{s?l():i=l}),()=>{s=!0,i?.()}},[t]),o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5",children:[o.jsx("h1",{className:"text-sm font-semibold text-content",children:Hn[e]}),n&&o.jsxs("span",{className:"truncate text-xs text-muted",children:["· ",n.name]})]}),o.jsx("main",{className:"min-h-0 flex-1 overflow-auto p-4",children:n?o.jsx(a0,{panel:e,projectId:n.id,projectRoot:n.root}):o.jsx(ke,{children:o.jsx("p",{className:"text-sm text-muted",children:"Ouvrez un projet dans la fenêtre principale pour afficher ce panneau."})})})]})}function OB(e){if(e&&typeof e=="object"&&"message"in e){const t=e;return{code:String(t.code??"ERROR"),message:String(t.message)}}return{code:"ERROR",message:String(e)}}function BB({session:e,onPaired:t}){const[n,r]=g.useState(""),[s,i]=g.useState(()=>Cx(iL())),[l,a]=g.useState(null),[c,u]=g.useState(!1),h=VO(n),d=s.trim(),f=h.length>0&&d.length>0,p=l?.code==="invalidName"?l.message:null,m=l&&!p?l.message:null;async function x(w){if(w.preventDefault(),!(!f||c)){u(!0),a(null);try{await e.pair(h,Cx(d)),t()}catch(v){a(OB(v))}finally{u(!1)}}}return o.jsx("div",{className:"flex h-full items-center justify-center overflow-y-auto bg-canvas p-4 sm:p-6",children:o.jsx(ke,{className:"w-full max-w-sm",children:o.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Appairer cet appareil"}),o.jsx("p",{className:"text-sm text-muted",children:"Saisissez le code affiché par le serveur IdeA pour connecter ce navigateur."})]}),o.jsx(qt,{label:"Code d'appairage",hint:"8 caractères : chiffres et lettres A-F",children:({id:w,describedBy:v})=>o.jsx(ce,{id:w,"aria-describedby":v,value:n,onChange:_=>r(_.target.value),placeholder:"p. ex. AB12CD34",autoFocus:!0,autoComplete:"one-time-code",inputMode:"text",autoCapitalize:"characters",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!m})}),o.jsx(qt,{label:"Nom de cet appareil",hint:"Pour le reconnaître dans la liste des appareils.",error:p??void 0,children:({id:w,describedBy:v})=>o.jsx(ce,{id:w,"aria-describedby":v,value:s,onChange:_=>i(_.target.value),maxLength:vp,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!p})}),m&&o.jsx("p",{role:"alert","data-testid":"pairing-error",className:"text-sm text-danger",children:m}),o.jsx(M,{type:"submit",disabled:c||!f,children:c?"Appairage…":"Appairer"})]})})})}const zB=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Ctrl-C",aria:"Ctrl-C (interrompre)",data:""},{label:"Ctrl-D",aria:"Ctrl-D (fin de saisie)",data:""},{label:"↑",aria:"Flèche haut",data:"\x1B[A"},{label:"↓",aria:"Flèche bas",data:"\x1B[B"},{label:"←",aria:"Flèche gauche",data:"\x1B[D"},{label:"→",aria:"Flèche droite",data:"\x1B[C"}];function FB({api:e,className:t}){return o.jsx("div",{role:"toolbar","aria-label":"Touches du terminal","data-testid":"terminal-key-bar",className:U("flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-raised/40 px-2 py-1.5",t),children:zB.map(n=>o.jsx(M,{size:"sm",variant:"secondary","aria-label":n.aria??n.label,disabled:!e,onPointerDown:r=>r.preventDefault(),onClick:()=>{e?.send(n.data),e?.focus()},className:"min-h-11 shrink-0 font-mono",children:n.label},n.label))})}function $B({projectId:e,agentId:t,cwd:n,nodeId:r,refitSignal:s}){const{agent:i}=fe(),[l,a]=g.useState(null),[c,u]=g.useState(null),h=g.useCallback((f,p)=>i.launchAgent(e,t,r?{...f,nodeId:r}:f,p),[i,e,t,r]),d=g.useCallback((f,p)=>i.reattach(f,p),[i]);return o.jsxs("div",{"data-testid":"web-agent-cell",className:"flex h-[60dvh] min-h-64 w-full flex-col overflow-hidden rounded-md border border-border sm:h-80",children:[o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(hp,{cwd:n,agentMode:!0,open:h,reattach:d,sessionId:l,onSessionId:a,onReady:u,refitSignal:s})}),o.jsx(FB,{api:c})]})}function WB(e){g.useEffect(()=>{const t=Bh();if(!t)return;let n=t.getConnectionState();return t.onConnectionStateChange(r=>{r==="connected"&&n==="reconnecting"&&e(),n=r})},[e])}function HB(){const[e,t]=g.useState(()=>Bh()?.getConnectionState()??null);return g.useEffect(()=>{const n=Bh();if(n)return t(n.getConnectionState()),n.onConnectionStateChange(t)},[]),e}function Mc(e){switch(e){case"open":return"Ouvert";case"inProgress":return"En cours";case"QA":return"QA";case"closed":return"Fermé"}}function lo(e){switch(e){case"low":return"Faible";case"medium":return"Moyenne";case"high":return"Haute";case"critical":return"Critique"}}function Vv(e){switch(e){case"relatesTo":return"en relation avec";case"blocks":return"bloque";case"blockedBy":return"bloqué par";case"duplicates":return"duplique";case"dependsOn":return"dépend de"}}function UB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function qB(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function c0(e){return U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function Wp({status:e}){return o.jsx("span",{className:c0(UB(e)),children:Mc(e)})}function Hp({priority:e}){return o.jsx("span",{className:c0(qB(e)),children:lo(e)})}const Kv=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),VB=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function KB({sprints:e,busy:t,error:n,onCancel:r,onCreate:s}){const[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState("medium"),[d,f]=g.useState("");async function p(m){m.preventDefault();const x=i.trim();x&&await s({title:x,priority:u,...a.trim()?{description:a.trim()}:{}},d||null)}return o.jsxs(ke,{title:"Nouveau ticket",actions:o.jsx(M,{size:"sm",variant:"ghost",onClick:r,children:"Annuler"}),children:[n&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n}),o.jsxs("form",{onSubmit:p,className:"flex flex-col gap-3",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),o.jsx(ce,{"aria-label":"Titre",value:i,onChange:m=>l(m.target.value),disabled:t,autoFocus:!0})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Priorité"}),o.jsx("select",{"aria-label":"Priorité",className:Kv,value:u,disabled:t,onChange:m=>h(m.target.value),children:Ni.map(m=>o.jsx("option",{value:m,children:lo(m)},m))})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Sprint"}),o.jsxs("select",{"aria-label":"Sprint",className:Kv,value:d,disabled:t,onChange:m=>f(m.target.value),children:[o.jsx("option",{value:"",children:"Sans sprint"}),e.map(m=>o.jsx("option",{value:m.id,children:m.name},m.id))]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),o.jsx("textarea",{"aria-label":"Description",className:U(VB,"min-h-20"),value:a,onChange:m=>c(m.target.value),disabled:t})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx(M,{type:"button",variant:"ghost",size:"sm",disabled:t,onClick:r,children:"Annuler"}),o.jsx(M,{type:"submit",size:"sm",disabled:!i.trim()||t,loading:t,children:"Créer"})]})]})]})}function u0({title:e,body:t,confirmLabel:n,busy:r=!1,onConfirm:s,onCancel:i}){const l=g.useRef(null);return g.useEffect(()=>{l.current?.focus()},[]),g.useEffect(()=>{function a(c){c.key==="Escape"&&i()}return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[i]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.toast},children:o.jsxs("div",{role:"alertdialog","aria-modal":"true","aria-label":e,onClick:a=>a.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:l,size:"sm",variant:"ghost",disabled:r,onClick:i,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger",loading:r,disabled:r,onClick:()=>void s(),children:n})]})]})})}function d0({projectId:e,title:t,confirmLabel:n="Ajouter",selectionMode:r,excludeRefs:s,onSelect:i,onClose:l}){const a=Rc(e,{excludeRefs:s}),c=r==="multi",[u,h]=g.useState(()=>new Set),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useRef(null);g.useEffect(()=>{x.current?.focus()},[]),g.useEffect(()=>{function b(C){C.key==="Escape"&&l()}return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[l]);function w(b){return b&&typeof b=="object"&&"message"in b?String(b.message):String(b)}function v(b){h(C=>{const S=new Set(C);return S.has(b)?S.delete(b):S.add(b),S})}async function _(b){if(!d){f(!0),m(null);try{i(await a.resolve(b)),l()}catch(C){m(w(C)),f(!1)}}}async function y(){if(!(d||u.size===0)){f(!0),m(null);try{const b=await Promise.all(Array.from(u).map(C=>a.resolve(C)));i(b),l()}catch(b){m(w(b)),f(!1)}}}return o.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":t,style:{zIndex:Sn.floatingWindowNested},children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[o.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:t}),o.jsx(M,{ref:x,size:"sm",variant:"ghost",onClick:l,children:"Fermer"})]}),o.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:o.jsx(ce,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:a.text,onChange:b=>a.setText(b.target.value),autoFocus:!0})}),(a.error||p)&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??a.error}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[a.busy&&a.rows.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Chargement des tickets…"})]}):a.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:a.rows.map(b=>{const C=u.has(b.ref);return o.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:o.jsxs("button",{type:"button","aria-label":`${b.ref}, ${b.title}`,...c?{role:"checkbox","aria-checked":C}:{},disabled:d,onClick:()=>c?v(b.ref):void _(b.ref),className:U("flex min-h-[40px] w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-60",c&&C&&"bg-raised"),children:[c&&o.jsx("span",{"aria-hidden":"true",className:U("flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",C?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:b.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:b.title}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(Wp,{status:b.status}),o.jsx(Hp,{priority:b.priority})]})]})},b.ref)})}),a.hasMore&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:a.busy,onClick:()=>a.loadMore(),children:"Charger plus"})})]}),c&&o.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]",children:[o.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[u.size," sélectionné",u.size>1?"s":""]}),o.jsxs(M,{size:"sm",loading:d,disabled:u.size===0||d,onClick:()=>void y(),children:[n," ",u.size>0?`(${u.size})`:""]})]})]})}const Fs=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Gv=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function $s({title:e,defaultOpen:t,children:n}){const[r,s]=g.useState(t);return o.jsxs("section",{className:"border-b border-border py-2 last:border-b-0",children:[o.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>s(i=>!i),className:"flex min-h-[32px] w-full items-center justify-between text-left text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{"aria-hidden":"true",children:r?"▾":"▸"})]}),r&&o.jsx("div",{className:"mt-2 flex flex-col gap-2",children:n})]})}function GB({projectId:e,ticketRef:t,nameOf:n,assignableAgents:r,sprints:s,onBack:i,onOpenRef:l}){const a=l0(e,t),c=a.ticket,[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState("relatesTo"),[v,_]=g.useState(""),[y,b]=g.useState(!1),[C,S]=g.useState(!1),[N,L]=g.useState(!1);g.useEffect(()=>{a.deleted&&i()},[a.deleted,i]);const A=a.reloadCount,k=g.useRef(-1),D=g.useRef(null);g.useEffect(()=>{if(!c||k.current===A)return;k.current=A;const P=c.carnet??"",z=D.current;z===null||a.conflict?(h(c.title),f(c.description),m(P)):(h(se=>se===z.title?c.title:se),f(se=>se===z.description?c.description:se),m(se=>se===z.carnet?P:se)),D.current={title:c.title,description:c.description,carnet:P}},[c,A,a.conflict]);const R=!!c&&(u!==c.title||d!==c.description),E=!!c&&p!==(c.carnet??""),O=R||E,I=r.filter(P=>!c?.assignedAgentIds.includes(P.id));function W(){O?S(!0):i()}async function G(){let P=!0;R&&(P=await a.updateFields({title:u,description:d})&&P),P&&E&&(P=await a.saveCarnet(p)&&P),S(!1),P&&i()}return o.jsxs(ke,{className:"flex flex-col",flush:!0,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:W,children:"← Tickets"}),o.jsx("code",{className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:t})]}),a.conflict&&o.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-4 py-2 text-sm text-warning",children:"Ce ticket a été modifié ailleurs et rechargé. Réappliquez votre modification."}),a.error&&!a.conflict&&o.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:a.error}),a.busy&&!c?o.jsxs("div",{className:"flex items-center gap-2 px-4 py-5 text-sm text-muted",children:[o.jsx(Me,{size:14}),o.jsx("span",{children:"Chargement du ticket…"})]}):c?o.jsxs("div",{className:"flex flex-col px-4 py-2",children:[o.jsxs("div",{className:"flex flex-col gap-1 border-b border-border pb-3",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),o.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[o.jsx(Wp,{status:c.status}),o.jsx(Hp,{priority:c.priority}),c.sprintId&&o.jsxs("span",{children:["· ",s.find(P=>P.id===c.sprintId)?.name??"Sprint"]})]})]}),o.jsxs($s,{title:"Résumé",defaultOpen:!0,children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),o.jsx("input",{"aria-label":"Titre",className:U(Fs,"w-full"),value:u,onChange:P=>h(P.target.value),disabled:a.busy})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),o.jsx("textarea",{"aria-label":"Description",className:U(Gv,"min-h-24"),value:d,onChange:P=>f(P.target.value),disabled:a.busy})]}),o.jsx("div",{children:o.jsx(M,{size:"sm",disabled:!R||a.busy,loading:a.busy&&R,onClick:()=>void a.updateFields({title:u,description:d}),children:"Enregistrer"})})]}),o.jsxs($s,{title:"Statut et priorité",defaultOpen:!0,children:[o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Statut"}),o.jsx("select",{"aria-label":"Statut",className:Fs,value:c.status,disabled:a.busy,onChange:P=>void a.updateFields({status:P.target.value}),children:Lc.map(P=>o.jsx("option",{value:P,children:Mc(P)},P))})]}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Priorité"}),o.jsx("select",{"aria-label":"Priorité",className:Fs,value:c.priority,disabled:a.busy,onChange:P=>void a.updateFields({priority:P.target.value}),children:Ni.map(P=>o.jsx("option",{value:P,children:lo(P)},P))})]}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Sprint"}),o.jsxs("select",{"aria-label":"Sprint",className:Fs,value:c.sprintId??"",disabled:a.busy,onChange:P=>void a.setSprint(P.target.value||null),children:[o.jsx("option",{value:"",children:"Sans sprint"}),s.map(P=>o.jsx("option",{value:P.id,children:P.name},P.id))]})]}),a.busy&&o.jsx(Me,{size:12})]}),o.jsxs($s,{title:"Carnet",defaultOpen:!0,children:[o.jsx("textarea",{"aria-label":"Carnet",className:U(Gv,"min-h-32 font-mono"),value:p,onChange:P=>m(P.target.value),disabled:a.busy}),o.jsx("div",{children:o.jsx(M,{size:"sm",disabled:!E||a.busy,loading:a.busy&&E,onClick:()=>void a.saveCarnet(p),children:"Enregistrer le carnet"})})]}),o.jsxs($s,{title:"Agents assignés",defaultOpen:!1,children:[c.assignedAgentIds.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun agent assigné."}):o.jsx("ul",{className:"flex flex-wrap gap-2",children:c.assignedAgentIds.map(P=>o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[n(P),o.jsx("button",{type:"button","aria-label":`Désassigner ${n(P)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:a.busy,onClick:()=>void a.assign(P,!1),children:"×"})]},P))}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("select",{"aria-label":"Assigner un agent",className:Fs,value:v,disabled:a.busy||I.length===0,onChange:P=>_(P.target.value),children:[o.jsx("option",{value:"",children:I.length===0?"Aucun autre agent":"Choisir un agent…"}),I.map(P=>o.jsx("option",{value:P.id,children:P.name},P.id))]}),o.jsx(M,{size:"sm",disabled:!v||a.busy,onClick:async()=>{await a.assign(v,!0)&&_("")},children:"Assigner"})]})]}),o.jsxs($s,{title:"Liens",defaultOpen:!1,children:[c.links.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun ticket lié."}):o.jsx("ul",{className:"flex flex-col gap-1",children:c.links.map(P=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"text-xs text-muted",children:Vv(P.kind)}),o.jsx("button",{type:"button",className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content hover:text-primary",onClick:()=>l(P.targetRef),children:P.targetRef}),o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:()=>void a.unlink(P.targetRef,P.kind),children:"Retirer"})]},`${P.kind}-${P.targetRef}`))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("select",{"aria-label":"Type de lien",className:Fs,value:x,disabled:a.busy,onChange:P=>w(P.target.value),children:n0.map(P=>o.jsx("option",{value:P,children:Vv(P)},P))}),o.jsx(M,{size:"sm",disabled:a.busy,onClick:()=>L(!0),children:"+ Lier"})]})]}),o.jsxs($s,{title:"Zone dangereuse",defaultOpen:!1,children:[o.jsxs("p",{className:"text-xs text-muted",children:["Le ticket ",t," sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés."]}),o.jsx("div",{children:o.jsx(M,{size:"sm",variant:"danger",disabled:a.busy,onClick:()=>b(!0),children:"Supprimer"})})]})]}):o.jsx("p",{className:"px-4 py-5 text-sm text-muted",children:"Ticket introuvable."}),N&&c&&o.jsx(d0,{projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...c.links.map(P=>P.targetRef)],onSelect:P=>{const z=Array.isArray(P)?P[0]:P;z&&a.link(z.ref,x)},onClose:()=>L(!1)}),y&&o.jsx(u0,{title:"Supprimer ce ticket ?",body:`Le ticket ${t} sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés.`,confirmLabel:"Supprimer",busy:a.busy,onCancel:()=>b(!1),onConfirm:async()=>{await a.remove()&&b(!1)}}),C&&o.jsx("div",{role:"alertdialog","aria-modal":"true","aria-label":"Modifications non enregistrées",className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",children:o.jsxs("div",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:"Des modifications ne sont pas enregistrées."}),o.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:()=>S(!1),children:"Continuer l'édition"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:i,children:"Ignorer"}),o.jsx(M,{size:"sm",loading:a.busy,disabled:a.busy,onClick:()=>void G(),children:"Enregistrer et quitter"})]})]})})]})}function YB(e){const t=eo(e),n=g.useMemo(()=>(t.state?.agents??[]).map(i=>({id:i.agentId,name:i.name})),[t.state]),r=g.useMemo(()=>new Map(n.map(i=>[i.id,i.name])),[n]);return{agents:n,nameOf:i=>r.get(i)??`${i.slice(0,8)}…`,loaded:t.state!==null}}const Go=U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Yv={number:"Numéro",priority:"Priorité",status:"Statut",title:"Titre"};function XB({projectId:e,focusSprintId:t=null}){const n=zp(e),r=YB(e),[s,i]=g.useState({type:"list"}),[l,a]=g.useState(t);if(s.type==="detail")return o.jsx(GB,{projectId:e,ticketRef:s.ref,nameOf:r.nameOf,assignableAgents:r.agents,sprints:n.sprints,onBack:()=>i({type:"list"}),onOpenRef:x=>i({type:"detail",ref:x})},s.ref);if(s.type==="create")return o.jsx(KB,{sprints:n.sprints,busy:n.busy,error:n.error,onCancel:()=>i({type:"list"}),onCreate:async(x,w)=>{const v=await n.create(x);v&&(w&&await n.assignSprint(v.ref,w),i({type:"detail",ref:v.ref}))}});const c=n.list?.items??[],u=!!n.query.text||(n.query.statuses?.length??0)>0||(n.query.priorities?.length??0)>0||!!n.query.assignedAgentId||!!l,h=new Set(n.sprints.map(x=>x.id)),f=(l?n.sprints.filter(x=>x.id===l):n.sprints).map(x=>({sprint:x,tickets:c.filter(w=>w.sprintId===x.id)})).filter(x=>x.tickets.length>0),p=l?[]:c.filter(x=>!x.sprintId||!h.has(x.sprintId));function m(){n.setQuery({}),a(null)}return o.jsxs(ke,{className:"flex flex-col",title:"Tickets",actions:o.jsx(M,{size:"sm",onClick:()=>i({type:"create"}),children:"+ Ticket"}),children:[n.error&&o.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[o.jsx("span",{children:n.error}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),children:"Réessayer"})]}),l&&o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 rounded-md border border-border bg-raised/50 px-3 py-2 text-xs text-muted",children:[o.jsxs("span",{children:["Filtré sur le sprint « ",n.sprints.find(x=>x.id===l)?.name??l," »"]}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>a(null),children:"Voir tous les tickets"})]}),o.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:n.query.text??"",onChange:x=>n.setQuery({...n.query,text:x.target.value||void 0})}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("select",{"aria-label":"Filtrer par statut",className:Go,value:n.query.statuses?.[0]??"",onChange:x=>n.setQuery({...n.query,statuses:x.target.value?[x.target.value]:void 0}),children:[o.jsx("option",{value:"",children:"Tous les statuts"}),Lc.map(x=>o.jsx("option",{value:x,children:Mc(x)},x))]}),o.jsxs("select",{"aria-label":"Filtrer par priorité",className:Go,value:n.query.priorities?.[0]??"",onChange:x=>n.setQuery({...n.query,priorities:x.target.value?[x.target.value]:void 0}),children:[o.jsx("option",{value:"",children:"Toutes les priorités"}),Ni.map(x=>o.jsx("option",{value:x,children:lo(x)},x))]}),o.jsxs("select",{"aria-label":"Filtrer par agent assigné",className:Go,value:n.query.assignedAgentId??"",onChange:x=>n.setQuery({...n.query,assignedAgentId:x.target.value||void 0}),children:[o.jsx("option",{value:"",children:"Tous les agents"}),r.agents.map(x=>o.jsx("option",{value:x.id,children:x.name},x.id))]}),o.jsxs("select",{"aria-label":"Trier les tickets",className:Go,value:n.query.sort?.field??"",onChange:x=>{const w=x.target.value,{sort:v,..._}=n.query;n.setQuery(w?{..._,sort:{field:w,direction:"asc"}}:_)},children:[o.jsx("option",{value:"",children:"Tri par défaut"}),Object.keys(Yv).map(x=>o.jsx("option",{value:x,children:Yv[x]},x))]})]})]}),n.busy&&n.list===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des tickets…"]}):c.length===0&&!u?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket dans ce projet."}),o.jsx(M,{size:"sm",onClick:()=>i({type:"create"}),children:"Créer un ticket"})]}):c.length===0?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond aux filtres."}),o.jsx(M,{size:"sm",variant:"ghost",onClick:m,children:"Réinitialiser les filtres"})]}):o.jsxs("div",{className:"flex flex-col gap-4","data-testid":"web-ticket-list",children:[f.map(x=>o.jsx(Xv,{heading:x.sprint.name,tickets:x.tickets,sprints:n.sprints,nameOf:r.nameOf,onOpen:w=>i({type:"detail",ref:w})},x.sprint.id)),p.length>0&&o.jsx(Xv,{heading:"Sans sprint",tickets:p,sprints:n.sprints,nameOf:r.nameOf,onOpen:x=>i({type:"detail",ref:x})})]}),n.list?.nextCursor&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Charger plus"})})]})}function Xv({heading:e,tickets:t,sprints:n,nameOf:r,onOpen:s}){const i=l=>l?n.find(a=>a.id===l)?.name:void 0;return o.jsxs("section",{"aria-label":`Tickets — ${e}`,children:[o.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t.length})]}),o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(l=>{const a=i(l.sprintId),c=l.assignedAgentIds.map(r).join(", ");return o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>s(l.ref),"aria-label":`${l.ref}, ${l.title}, statut ${Mc(l.status)}, priorité ${lo(l.priority)}`,className:"flex w-full min-w-0 flex-col items-start gap-0.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-raised",children:[o.jsxs("span",{className:"flex w-full min-w-0 items-baseline gap-2",children:[o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:l.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:l.title})]}),o.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[o.jsx(Wp,{status:l.status}),o.jsx(Hp,{priority:l.priority}),a&&o.jsxs("span",{children:["· ",a]}),c&&o.jsxs("span",{children:["· ",c]})]})]})},l.ref)})})]})}function QB({projectId:e,onViewSprintTickets:t}){const n=zp(e),r=Rc(e,{refreshOnEvents:!0}),[s,i]=g.useState(!1),[l,a]=g.useState(""),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState(null),[m,x]=g.useState(null),w=[...n.sprints].sort((_,y)=>_.order-y.order);async function v(_){_.preventDefault();const y=l.trim();if(!y)return;await n.createSprint(y)&&(a(""),i(!1))}return o.jsxs(ke,{title:"Sprints",actions:o.jsx(M,{size:"sm",onClick:()=>i(_=>!_),children:"+ Sprint"}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),s&&o.jsxs("form",{onSubmit:v,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Nom du sprint"}),o.jsx(ce,{"aria-label":"Nom du sprint",value:l,onChange:_=>a(_.target.value),autoFocus:!0})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(!1),children:"Annuler"}),o.jsx(M,{type:"submit",size:"sm",disabled:!l.trim()||n.busy,children:"Créer"})]})]}),n.busy&&n.sprints.length===0?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des sprints…"]}):w.length===0?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun sprint."}),o.jsx(M,{size:"sm",onClick:()=>i(!0),children:"Créer un sprint"})]}):o.jsx("ul",{className:"flex flex-col gap-3",children:w.map((_,y)=>o.jsx(JB,{sprint:_,index:y,lastIndex:w.length-1,tickets:r.rows.filter(b=>b.sprintId===_.id),vm:n,renaming:c===_.id,renameDraft:h,onStartRename:()=>{u(_.id),d(_.name)},onRenameDraftChange:d,onCancelRename:()=>u(null),onSaveRename:async()=>{await n.renameSprint(_.id,h.trim())&&u(null)},onViewTickets:()=>t(_.id),onAddTickets:()=>x({id:_.id,name:_.name}),onRequestDelete:()=>p({id:_.id,name:_.name})},_.id))}),f&&o.jsx(u0,{title:`Supprimer le sprint « ${f.name} » ?`,body:"Les tickets de ce sprint seront conservés et passeront en « Sans sprint ».",confirmLabel:"Supprimer",busy:n.busy,onCancel:()=>p(null),onConfirm:async()=>{await n.deleteSprint(f.id),p(null)}}),m&&o.jsx(d0,{projectId:e,title:`Ajouter des tickets au sprint « ${m.name} »`,confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:r.rows.filter(_=>_.sprintId===m.id).map(_=>_.ref),onSelect:_=>{const y=Array.isArray(_)?_:[_];for(const b of y)n.assignSprint(b.ref,m.id)},onClose:()=>x(null)})]})}function JB({sprint:e,index:t,lastIndex:n,tickets:r,vm:s,renaming:i,renameDraft:l,onStartRename:a,onRenameDraftChange:c,onCancelRename:u,onSaveRename:h,onViewTickets:d,onAddTickets:f,onRequestDelete:p}){return o.jsxs("li",{className:"rounded-md border border-border p-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",e.order]}),!i&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e.name})]}),i?o.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":`Renommer le sprint ${e.name}`,value:l,onChange:m=>c(m.target.value),disabled:s.busy}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:u,children:"Annuler"}),o.jsx(M,{size:"sm",disabled:s.busy||!l.trim()||l.trim()===e.name,onClick:()=>void h(),children:"Enregistrer"})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"mt-1 text-xs text-muted",children:[e.ticketCount," ticket",e.ticketCount>1?"s":""]}),r.length>0&&o.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:r.map(m=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:m.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:m.title}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Retirer ${m.ref} du sprint ${e.name}`,disabled:s.busy,onClick:()=>void s.assignSprint(m.ref,null),children:"Retirer du sprint"})]},m.ref))}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:d,children:"Voir tickets"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:f,children:"Ajouter tickets"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Renommer ${e.name}`,disabled:s.busy,onClick:a,children:"Renommer"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Monter ${e.name}`,disabled:s.busy||t===0,onClick:()=>void s.moveSprint(e.id,"up"),children:"Monter"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Descendre ${e.name}`,disabled:s.busy||t===n,onClick:()=>void s.moveSprint(e.id,"down"),children:"Descendre"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Supprimer ${e.name}`,disabled:s.busy,className:"text-danger hover:text-danger",onClick:p,children:"Supprimer"})]})]})]})}function ZB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function e4({projects:e,openId:t,onOpen:n,onCreate:r,onRefresh:s}){const[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState(!1),[d,f]=g.useState(null),p=i.trim().length>0&&a.trim().length>0&&!u;async function m(x){if(x.preventDefault(),!!p){h(!0),f(null);try{const w=await r(i.trim(),a.trim());l(""),c(""),n(w.id)}catch(w){f(ZB(w))}finally{h(!1)}}}return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Projets"}),o.jsx(M,{variant:"ghost",size:"sm",onClick:s,children:"Rafraîchir"})]}),o.jsx(ke,{title:"Nouveau projet",children:o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-col gap-2",children:[o.jsx(ce,{"aria-label":"Nom du projet",placeholder:"Nom du projet",value:i,onChange:x=>l(x.target.value)}),o.jsx(ce,{"aria-label":"Chemin du projet",placeholder:"/chemin/absolu/du/projet",value:a,onChange:x=>c(x.target.value)}),o.jsx("p",{className:"text-xs text-muted",children:"Saisir un chemin absolu accessible depuis le serveur IdeA."}),d&&o.jsx("p",{role:"alert",className:"text-xs text-danger",children:d}),o.jsx(M,{type:"submit",variant:"primary",disabled:!p,loading:u,children:"Créer le projet"})]})}),e===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Me,{size:12})," Chargement des projets…"]}):e.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun projet."}):o.jsx("ul",{className:"flex flex-col gap-2","data-testid":"web-project-list",children:e.map(x=>o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>n(x.id),"aria-pressed":t===x.id,className:"flex w-full flex-col items-start rounded-md border border-border bg-raised px-3 py-2 text-left transition-colors hover:border-primary aria-pressed:border-primary",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:x.name}),o.jsx("span",{className:"text-xs text-faint",children:x.root})]})},x.id))})]})}function h0({title:e,entries:t,note:n,onClose:r}){const s=g.useRef(null);return g.useEffect(()=>{s.current?.focus()},[]),g.useEffect(()=>{function i(l){l.key==="Escape"&&r()}return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[r]),o.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":e,style:{zIndex:Sn.floatingWindowNested},children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[o.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:e}),o.jsx(M,{ref:s,size:"sm",variant:"ghost",onClick:r,children:"Fermer"})]}),n&&o.jsx("p",{className:"shrink-0 border-b border-border px-4 py-2 text-xs text-muted",children:n}),o.jsx("ul",{className:"min-h-0 flex-1 overflow-auto px-2 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:t.map(i=>o.jsx("li",{children:o.jsxs("button",{type:"button",disabled:i.disabled,title:i.hint,"aria-current":i.active?"true":void 0,onClick:()=>{i.disabled||i.onSelect()},className:U("flex min-h-[44px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-50 disabled:hover:bg-transparent",i.active&&"bg-raised font-medium text-content"),children:[o.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-primary",children:i.active?"●":""}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:i.label}),i.secondaryLabel&&o.jsx("span",{className:"shrink-0 text-xs text-muted",children:i.secondaryLabel})]})},i.id))})]})}function va(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const t4=["context","work","tickets","sprints","agents","templates","skills","permissions","memory","git","projects"],Qv={context:"Contexte projet",work:"Travail",tickets:"Tickets",sprints:"Sprints",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Mémoire",git:"Git",projects:"Projets"};function n4(){const{project:e}=fe(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState("projects"),[u,h]=g.useState(null),d=t?.find(x=>x.id===i)?.root??null,f=g.useCallback(async()=>{s(null);try{n(await e.listProjects())}catch(x){s(va(x))}},[e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async x=>{s(null),l(null);try{await e.openProject(x),l(x),c("work")}catch(w){s(va(w))}},[e]),m=g.useCallback(async(x,w)=>{s(null);try{const v=await e.createProject(x,w);return await f(),v}catch(v){throw s(va(v)),v}},[e,f]);return o.jsxs("div",{"data-testid":"web-workspace",className:"flex h-full flex-col gap-4 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:[o.jsx(i4,{}),o.jsx(r4,{activePanel:a,hasProject:!!i,onSelect:c}),r&&o.jsx(ke,{className:"border-danger/40",children:o.jsx("p",{className:"text-sm text-danger",children:r})}),a==="projects"?o.jsx(e4,{projects:t,openId:i,onOpen:x=>void p(x),onCreate:m,onRefresh:()=>void f()}):i?o.jsx(s4,{panel:a,projectId:i,root:d,focusSprintId:u,onViewSprintTickets:x=>{h(x),c("tickets")}}):o.jsx("p",{className:"text-sm text-muted",children:"Ouvrir un projet pour utiliser ce panneau."})]})}function r4({activePanel:e,hasProject:t,onSelect:n}){const[r,s]=g.useState(!1);return o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>s(!0),children:["Panneaux : ",Qv[e]]}),r&&o.jsx(h0,{title:"Panneaux",note:t?void 0:"Ouvrir un projet pour utiliser ce panneau.",onClose:()=>s(!1),entries:t4.map(i=>{const l=i!=="projects"&&!t;return{id:i,label:Qv[i],active:i===e,disabled:l,hint:l?"Ouvrir un projet pour utiliser ce panneau.":void 0,onSelect:()=>{n(i),s(!1)}}})})]})}function s4({panel:e,projectId:t,root:n,focusSprintId:r,onViewSprintTickets:s}){switch(e){case"context":return o.jsx(o0,{projectId:t});case"work":return o.jsx(l4,{projectId:t,root:n});case"tickets":return o.jsx(XB,{projectId:t,focusSprintId:r});case"sprints":return o.jsx(QB,{projectId:t,onViewSprintTickets:s});case"agents":return o.jsx(_w,{projectId:t,projectRoot:n??""});case"templates":return o.jsx($S,{projectId:t});case"skills":return o.jsx(WS,{projectId:t});case"permissions":return o.jsx(XS,{projectId:t});case"memory":return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(KS,{projectId:t}),o.jsx(VS,{})]});case"git":return o.jsx(Dw,{projectId:t})}}function i4(){return HB()!=="reconnecting"?null:o.jsxs("div",{role:"status","data-testid":"web-reconnect-banner",className:"flex items-center gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:[o.jsx(Me,{size:12}),"Connexion perdue — reconnexion en cours…"]})}function l4({projectId:e,root:t}){const n=eo(e);WB(n.refresh);const[r,s]=g.useState(null),[i,l]=g.useState(0),a=g.useCallback(()=>l(f=>f+1),[]),c=n.state?.agents??[],[u,h]=g.useState(new Set);g.useEffect(()=>{const f=new Set(c.filter(p=>(p.backgroundTasks??[]).length>0).map(p=>p.agentId));h(p=>{const m=new Set([...p].filter(x=>f.has(x)));return m.size===p.size?p:m})},[c]);const d=g.useCallback(f=>{h(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return o.jsxs(ke,{className:"mt-2",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[o.jsxs("h3",{className:"text-sm font-semibold",children:["État live",o.jsx("span",{className:"ml-2 rounded bg-canvas px-1.5 py-0.5 text-[0.6rem] uppercase text-muted",children:"read-only"})]}),o.jsx(M,{variant:"ghost",size:"sm",loading:n.busy,onClick:()=>void n.refresh(),children:"Rafraîchir"})]}),n.error&&o.jsx("p",{role:"alert",className:"mb-2 text-xs text-danger",children:n.error}),n.busy&&n.state===null?o.jsx("p",{className:"text-xs text-muted",children:"Chargement de l'état…"}):c.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun agent actif."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"web-workstate",children:c.map(f=>o.jsx(o4,{agent:f,open:r===f.agentId,onToggleOpen:()=>{s(p=>p===f.agentId?null:f.agentId),a()},onRefresh:n.refresh,bgExpanded:u.has(f.agentId),onToggleBgExpanded:()=>d(f.agentId)},f.agentId))}),t&&r&&o.jsxs("div",{className:"mt-3",children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-muted",children:"Agent"}),o.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{s(null),a()},children:"Fermer"})]}),o.jsx($B,{projectId:e,agentId:r,cwd:t,refitSignal:i},r)]})]})}function o4({agent:e,open:t,onToggleOpen:n,onRefresh:r,bgExpanded:s,onToggleBgExpanded:i}){const l=e.live!==void 0,a=e.busy?.state==="busy",c=[...e.inbox??[]].sort((h,d)=>h.createdAtMs-d.createdAtMs),u=[...e.backgroundTasks??[]].sort((h,d)=>d.updatedAtMs-h.updatedAtMs||h.taskId.localeCompare(d.taskId));return o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between sm:gap-2",children:[o.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:e.name}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-xs",children:[o.jsx("span",{className:U("rounded-full px-2 py-0.5 font-medium",l?"bg-success/15 text-success":"bg-raised text-muted"),children:l?"Live":"Offline"}),o.jsx("span",{className:U("rounded-full px-2 py-0.5 font-medium",a?"bg-warning/15 text-warning":"bg-raised text-muted"),children:a?"Busy":"Idle"}),o.jsx(M,{variant:"ghost",size:"sm","aria-pressed":t,onClick:n,children:t?"Fermer":"Ouvrir"})]})]}),c.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),o.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:c.map(h=>o.jsxs("li",{className:"flex min-w-0 items-start gap-2 text-xs text-muted",children:[o.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium",children:h.kind}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:h.body})]},h.id))})]}),u.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsxs("button",{type:"button","aria-expanded":s,"aria-controls":`web-bg-tasks-${e.agentId}`,"aria-label":s?`Masquer les background tasks de ${e.name}`:`Afficher les background tasks de ${e.name}`,onClick:i,className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-faint hover:text-muted",children:[o.jsx("span",{"aria-hidden":"true",children:s?"▾":"▸"}),"Background tasks",o.jsx("span",{className:"rounded-full bg-raised px-1.5 py-0.5 font-medium normal-case tracking-normal text-muted",children:u.length})]}),s&&o.jsx("ul",{id:`web-bg-tasks-${e.agentId}`,"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:u.map(h=>o.jsx(u4,{task:h,onRefresh:r},h.taskId))})]})]})}const a4={running:"Running",completed:"Completed",failed:"Failed",cancelled:"Cancelled",pending:"Pending",delivered:"Delivered"};function c4(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function u4({task:e,onRefresh:t}){const{workState:n}=fe(),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=e.status==="running"||e.status==="pending",c=e.status==="failed"||e.status==="cancelled";async function u(h){s(!0),l(null);try{await h(e.taskId),await t()}catch(d){l(va(d))}finally{s(!1)}}return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:U("shrink-0 rounded-full px-1.5 py-0.5 font-medium",c4(e.status)),children:a4[e.status]}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:e.kind})]}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:!a||r,loading:r,onClick:()=>void u(h=>n.cancelBackgroundTask(h)),children:"Cancel"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!c||r,loading:r,onClick:()=>void u(h=>n.retryBackgroundTask(h)),children:"Retry"})]})]}),i&&o.jsx("p",{role:"alert",className:"mt-1 text-danger",children:i})]})}const Yo={aiProfiles:"Profils IA",devices:"Appareils"};function d4({session:e}={}){const t=e??uw(),[n,r]=g.useState(()=>t.isPaired()),[s,i]=g.useState(!1),[l,a]=g.useState(null),[c,u]=g.useState(!1);g.useEffect(()=>t.onUnauthorized(()=>{a(null),u(!1),r(!1)}),[t]);async function h(){if(!s){i(!0);try{await t.logout()}finally{ox(),i(!1),a(null),u(!1),r(!1)}}}const d=g.useCallback(()=>{t.forget(),ox(),a(null),u(!1),r(!1)},[t]);return o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{"data-testid":"web-header",className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:px-6",children:[o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("h1",{className:"text-base font-semibold tracking-tight sm:text-lg",children:"IdeA"}),o.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"web"})]}),n&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(M,{variant:"ghost",size:"sm","aria-pressed":c,onClick:()=>u(!0),children:"Paramètres"}),o.jsx(M,{variant:"ghost",size:"sm",loading:s,onClick:()=>void h(),children:"Se déconnecter"})]})]}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:n?l==="aiProfiles"?o.jsx(Jv,{title:Yo.aiProfiles,onBack:()=>a(null),children:o.jsx(jw,{})}):l==="devices"?o.jsx(Jv,{title:Yo.devices,onBack:()=>a(null),children:o.jsx(Pw,{onSessionEnded:d})}):o.jsx(n4,{}):o.jsx(BB,{session:t,onPaired:()=>r(!0)})}),c&&o.jsx(h0,{title:"Paramètres",onClose:()=>u(!1),entries:[{id:"aiProfiles",label:Yo.aiProfiles,active:l==="aiProfiles",onSelect:()=>{a("aiProfiles"),u(!1)}},{id:"devices",label:Yo.devices,active:l==="devices",onSelect:()=>{a("devices"),u(!1)}},{id:"deployment",label:"Déploiement",active:!1,disabled:!0,secondaryLabel:"Desktop uniquement",hint:"Desktop uniquement",onSelect:()=>{}}]})]})}function Jv({title:e,onBack:t,children:n}){return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2 pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))]",children:[o.jsx(M,{variant:"ghost",size:"sm",onClick:t,children:"← Retour"}),o.jsx("span",{className:"text-sm font-medium text-content",children:e})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:o.jsx("div",{className:"mx-auto w-full max-w-xl",children:n})})]})}const f0=document.getElementById("root");if(!f0)throw new Error("missing #root element");const Zv=MB(window.location.search);window.__IDEA_TRANSPORT__="http";const h4=hw()==="http";sd.createRoot(f0).render(o.jsx(T0.StrictMode,{children:o.jsx(hP,{children:h4?o.jsx(d4,{}):Zv?o.jsx(IB,{panel:Zv.panel}):o.jsx(LB,{})})})); diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-C_fuYLKS.js b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-C_fuYLKS.js deleted file mode 100644 index e7789a8..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-C_fuYLKS.js +++ /dev/null @@ -1,128 +0,0 @@ -var m0=Object.defineProperty;var g0=(e,t,n)=>t in e?m0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var X=(e,t,n)=>g0(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var _a=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ty={exports:{}},ac={},ny={exports:{}},Se={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ql=Symbol.for("react.element"),x0=Symbol.for("react.portal"),v0=Symbol.for("react.fragment"),y0=Symbol.for("react.strict_mode"),_0=Symbol.for("react.profiler"),b0=Symbol.for("react.provider"),w0=Symbol.for("react.context"),S0=Symbol.for("react.forward_ref"),k0=Symbol.for("react.suspense"),C0=Symbol.for("react.memo"),j0=Symbol.for("react.lazy"),Kp=Symbol.iterator;function N0(e){return e===null||typeof e!="object"?null:(e=Kp&&e[Kp]||e["@@iterator"],typeof e=="function"?e:null)}var ry={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},sy=Object.assign,iy={};function _i(e,t,n){this.props=e,this.context=t,this.refs=iy,this.updater=n||ry}_i.prototype.isReactComponent={};_i.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};_i.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ly(){}ly.prototype=_i.prototype;function lf(e,t,n){this.props=e,this.context=t,this.refs=iy,this.updater=n||ry}var of=lf.prototype=new ly;of.constructor=lf;sy(of,_i.prototype);of.isPureReactComponent=!0;var Vp=Array.isArray,oy=Object.prototype.hasOwnProperty,af={current:null},ay={key:!0,ref:!0,__self:!0,__source:!0};function cy(e,t,n){var r,s={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)oy.call(t,r)&&!ay.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,q=P[Q];if(0>>1;Qs(te,C))Js(K,te)?(P[Q]=K,P[J]=C,Q=J):(P[Q]=te,P[se]=C,Q=se);else if(Js(K,C))P[Q]=K,P[J]=C,Q=J;else break e}}return z}function s(P,z){var C=P.sortIndex-z.sortIndex;return C!==0?C:P.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,a=l.now();e.unstable_now=function(){return l.now()-a}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,x=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function _(P){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=P)r(u),z.sortIndex=z.expirationTime,t(c,z);else break;z=n(u)}}function b(P){if(x=!1,_(P),!m)if(n(c)!==null)m=!0,W(j);else{var z=n(u);z!==null&&G(b,z.startTime-P)}}function j(P,z){m=!1,x&&(x=!1,v(D),D=-1),p=!0;var C=f;try{for(_(z),d=n(c);d!==null&&(!(d.expirationTime>z)||P&&!R());){var Q=d.callback;if(typeof Q=="function"){d.callback=null,f=d.priorityLevel;var q=Q(d.expirationTime<=z);z=e.unstable_now(),typeof q=="function"?d.callback=q:d===n(c)&&r(c),_(z)}else r(c);d=n(c)}if(d!==null)var L=!0;else{var se=n(u);se!==null&&G(b,se.startTime-z),L=!1}return L}finally{d=null,f=C,p=!1}}var S=!1,N=null,D=-1,A=5,k=-1;function R(){return!(e.unstable_now()-kP||125Q?(P.sortIndex=C,t(u,P),n(c)===null&&P===n(u)&&(x?(v(D),D=-1):x=!0,G(b,C-Q))):(P.sortIndex=q,t(c,P),m||p||(m=!0,W(j))),P},e.unstable_shouldYield=R,e.unstable_wrapCallback=function(P){var z=f;return function(){var C=f;f=z;try{return P.apply(this,arguments)}finally{f=C}}}})(py);fy.exports=py;var z0=fy.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var F0=g,an=z0;function Z(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),od=Object.prototype.hasOwnProperty,$0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Yp={},Xp={};function W0(e){return od.call(Xp,e)?!0:od.call(Yp,e)?!1:$0.test(e)?Xp[e]=!0:(Yp[e]=!0,!1)}function H0(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function U0(e,t,n,r){if(t===null||typeof t>"u"||H0(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function zt(e,t,n,r,s,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var wt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wt[e]=new zt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wt[t]=new zt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wt[e]=new zt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wt[e]=new zt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){wt[e]=new zt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wt[e]=new zt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wt[e]=new zt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wt[e]=new zt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wt[e]=new zt(e,5,!1,e.toLowerCase(),null,!1,!1)});var uf=/[\-:]([a-z])/g;function df(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(uf,df);wt[t]=new zt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(uf,df);wt[t]=new zt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(uf,df);wt[t]=new zt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wt[e]=new zt(e,1,!1,e.toLowerCase(),null,!1,!1)});wt.xlinkHref=new zt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wt[e]=new zt(e,1,!1,e.toLowerCase(),null,!0,!0)});function hf(e,t,n,r){var s=wt.hasOwnProperty(t)?wt[t]:null;(s!==null?s.type!==0:r||!(2a||s[l]!==i[a]){var c=` -`+s[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=a);break}}}finally{Fc=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?el(e):""}function q0(e){switch(e.tag){case 5:return el(e.type);case 16:return el("Lazy");case 13:return el("Suspense");case 19:return el("SuspenseList");case 0:case 2:case 15:return e=$c(e.type,!1),e;case 11:return e=$c(e.type.render,!1),e;case 1:return e=$c(e.type,!0),e;default:return""}}function dd(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case qs:return"Fragment";case Us:return"Portal";case ad:return"Profiler";case ff:return"StrictMode";case cd:return"Suspense";case ud:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case xy:return(e.displayName||"Context")+".Consumer";case gy:return(e._context.displayName||"Context")+".Provider";case pf:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case mf:return t=e.displayName||null,t!==null?t:dd(e.type)||"Memo";case kr:t=e._payload,e=e._init;try{return dd(e(t))}catch{}}return null}function K0(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return dd(t);case 8:return t===ff?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Hr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function yy(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function V0(e){var t=yy(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function uo(e){e._valueTracker||(e._valueTracker=V0(e))}function _y(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=yy(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ba(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function hd(e,t){var n=t.checked;return Ve({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Jp(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Hr(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function by(e,t){t=t.checked,t!=null&&hf(e,"checked",t,!1)}function fd(e,t){by(e,t);var n=Hr(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?pd(e,t.type,n):t.hasOwnProperty("defaultValue")&&pd(e,t.type,Hr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Zp(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function pd(e,t,n){(t!=="number"||ba(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var tl=Array.isArray;function ri(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=ho.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sl(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var cl={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},G0=["Webkit","ms","Moz","O"];Object.keys(cl).forEach(function(e){G0.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),cl[t]=cl[e]})});function Cy(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||cl.hasOwnProperty(e)&&cl[e]?(""+t).trim():t+"px"}function jy(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=Cy(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var Y0=Ve({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function xd(e,t){if(t){if(Y0[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Z(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Z(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Z(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Z(62))}}function vd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var yd=null;function gf(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var _d=null,si=null,ii=null;function nm(e){if(e=Gl(e)){if(typeof _d!="function")throw Error(Z(280));var t=e.stateNode;t&&(t=fc(t),_d(e.stateNode,e.type,t))}}function Ny(e){si?ii?ii.push(e):ii=[e]:si=e}function Ey(){if(si){var e=si,t=ii;if(ii=si=null,nm(e),t)for(e=0;e>>=0,e===0?32:31-(lk(e)/ok|0)|0}var fo=64,po=4194304;function nl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Ca(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,l=n&268435455;if(l!==0){var a=l&~s;a!==0?r=nl(a):(i&=l,i!==0&&(r=nl(i)))}else l=n&~s,l!==0?r=nl(l):i!==0&&(r=nl(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Kl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Pn(t),e[t]=n}function dk(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=dl),dm=" ",hm=!1;function Gy(e,t){switch(e){case"keyup":return zk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Yy(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ks=!1;function $k(e,t){switch(e){case"compositionend":return Yy(t);case"keypress":return t.which!==32?null:(hm=!0,dm);case"textInput":return e=t.data,e===dm&&hm?null:e;default:return null}}function Wk(e,t){if(Ks)return e==="compositionend"||!kf&&Gy(e,t)?(e=Ky(),ea=bf=Tr=null,Ks=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=gm(n)}}function Zy(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Zy(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function e_(){for(var e=window,t=ba();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ba(e.document)}return t}function Cf(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Qk(e){var t=e_(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Zy(n.ownerDocument.documentElement,n)){if(r!==null&&Cf(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=xm(n,i);var l=xm(n,r);s&&l&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Vs=null,jd=null,fl=null,Nd=!1;function vm(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Nd||Vs==null||Vs!==ba(r)||(r=Vs,"selectionStart"in r&&Cf(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),fl&&Pl(fl,r)||(fl=r,r=Ea(jd,"onSelect"),0Xs||(e.current=Dd[Xs],Dd[Xs]=null,Xs--)}function Oe(e,t){Xs++,Dd[Xs]=e.current,e.current=t}var Ur={},Tt=Kr(Ur),Gt=Kr(!1),xs=Ur;function di(e,t){var n=e.type.contextTypes;if(!n)return Ur;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Yt(e){return e=e.childContextTypes,e!=null}function Aa(){Fe(Gt),Fe(Tt)}function Cm(e,t,n){if(Tt.current!==Ur)throw Error(Z(168));Oe(Tt,t),Oe(Gt,n)}function c_(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(Z(108,K0(e)||"Unknown",s));return Ve({},n,r)}function Ta(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ur,xs=Tt.current,Oe(Tt,e),Oe(Gt,Gt.current),!0}function jm(e,t,n){var r=e.stateNode;if(!r)throw Error(Z(169));n?(e=c_(e,t,xs),r.__reactInternalMemoizedMergedChildContext=e,Fe(Gt),Fe(Tt),Oe(Tt,e)):Fe(Gt),Oe(Gt,n)}var sr=null,pc=!1,tu=!1;function u_(e){sr===null?sr=[e]:sr.push(e)}function c1(e){pc=!0,u_(e)}function Vr(){if(!tu&&sr!==null){tu=!0;var e=0,t=Te;try{var n=sr;for(Te=1;e>=l,s-=l,ir=1<<32-Pn(t)+s|n<D?(A=N,N=null):A=N.sibling;var k=f(v,N,_[D],b);if(k===null){N===null&&(N=A);break}e&&N&&k.alternate===null&&t(v,N),y=i(k,y,D),S===null?j=k:S.sibling=k,S=k,N=A}if(D===_.length)return n(v,N),$e&&ns(v,D),j;if(N===null){for(;D<_.length;D++)N=d(v,_[D],b),N!==null&&(y=i(N,y,D),S===null?j=N:S.sibling=N,S=N);return $e&&ns(v,D),j}for(N=r(v,N);D<_.length;D++)A=p(N,v,D,_[D],b),A!==null&&(e&&A.alternate!==null&&N.delete(A.key===null?D:A.key),y=i(A,y,D),S===null?j=A:S.sibling=A,S=A);return e&&N.forEach(function(R){return t(v,R)}),$e&&ns(v,D),j}function x(v,y,_,b){var j=Ai(_);if(typeof j!="function")throw Error(Z(150));if(_=j.call(_),_==null)throw Error(Z(151));for(var S=j=null,N=y,D=y=0,A=null,k=_.next();N!==null&&!k.done;D++,k=_.next()){N.index>D?(A=N,N=null):A=N.sibling;var R=f(v,N,k.value,b);if(R===null){N===null&&(N=A);break}e&&N&&R.alternate===null&&t(v,N),y=i(R,y,D),S===null?j=R:S.sibling=R,S=R,N=A}if(k.done)return n(v,N),$e&&ns(v,D),j;if(N===null){for(;!k.done;D++,k=_.next())k=d(v,k.value,b),k!==null&&(y=i(k,y,D),S===null?j=k:S.sibling=k,S=k);return $e&&ns(v,D),j}for(N=r(v,N);!k.done;D++,k=_.next())k=p(N,v,D,k.value,b),k!==null&&(e&&k.alternate!==null&&N.delete(k.key===null?D:k.key),y=i(k,y,D),S===null?j=k:S.sibling=k,S=k);return e&&N.forEach(function(T){return t(v,T)}),$e&&ns(v,D),j}function w(v,y,_,b){if(typeof _=="object"&&_!==null&&_.type===qs&&_.key===null&&(_=_.props.children),typeof _=="object"&&_!==null){switch(_.$$typeof){case co:e:{for(var j=_.key,S=y;S!==null;){if(S.key===j){if(j=_.type,j===qs){if(S.tag===7){n(v,S.sibling),y=s(S,_.props.children),y.return=v,v=y;break e}}else if(S.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===kr&&Pm(j)===S.type){n(v,S.sibling),y=s(S,_.props),y.ref=Mi(v,S,_),y.return=v,v=y;break e}n(v,S);break}else t(v,S);S=S.sibling}_.type===qs?(y=fs(_.props.children,v.mode,b,_.key),y.return=v,v=y):(b=aa(_.type,_.key,_.props,null,v.mode,b),b.ref=Mi(v,y,_),b.return=v,v=b)}return l(v);case Us:e:{for(S=_.key;y!==null;){if(y.key===S)if(y.tag===4&&y.stateNode.containerInfo===_.containerInfo&&y.stateNode.implementation===_.implementation){n(v,y.sibling),y=s(y,_.children||[]),y.return=v,v=y;break e}else{n(v,y);break}else t(v,y);y=y.sibling}y=cu(_,v.mode,b),y.return=v,v=y}return l(v);case kr:return S=_._init,w(v,y,S(_._payload),b)}if(tl(_))return m(v,y,_,b);if(Ai(_))return x(v,y,_,b);bo(v,_)}return typeof _=="string"&&_!==""||typeof _=="number"?(_=""+_,y!==null&&y.tag===6?(n(v,y.sibling),y=s(y,_),y.return=v,v=y):(n(v,y),y=au(_,v.mode,b),y.return=v,v=y),l(v)):n(v,y)}return w}var fi=p_(!0),m_=p_(!1),Ra=Kr(null),Ma=null,Zs=null,Pf=null;function Af(){Pf=Zs=Ma=null}function Tf(e){var t=Ra.current;Fe(Ra),e._currentValue=t}function Id(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function oi(e,t){Ma=e,Pf=Zs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Vt=!0),e.firstContext=null)}function bn(e){var t=e._currentValue;if(Pf!==e)if(e={context:e,memoizedValue:t,next:null},Zs===null){if(Ma===null)throw Error(Z(308));Zs=e,Ma.dependencies={lanes:0,firstContext:e}}else Zs=Zs.next=e;return t}var cs=null;function Lf(e){cs===null?cs=[e]:cs.push(e)}function g_(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Lf(t)):(n.next=s.next,s.next=n),t.interleaved=n,hr(e,r)}function hr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Cr=!1;function Df(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function x_(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ar(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Br(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ne&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,hr(e,n)}return s=r.interleaved,s===null?(t.next=t,Lf(r)):(t.next=s.next,s.next=t),r.interleaved=t,hr(e,n)}function na(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vf(e,n)}}function Am(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ia(e,t,n,r){var s=e.updateQueue;Cr=!1;var i=s.firstBaseUpdate,l=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var c=a,u=c.next;c.next=null,l===null?i=u:l.next=u,l=c;var h=e.alternate;h!==null&&(h=h.updateQueue,a=h.lastBaseUpdate,a!==l&&(a===null?h.firstBaseUpdate=u:a.next=u,h.lastBaseUpdate=c))}if(i!==null){var d=s.baseState;l=0,h=u=c=null,a=i;do{var f=a.lane,p=a.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=e,x=a;switch(f=t,p=n,x.tag){case 1:if(m=x.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=x.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Ve({},d,f);break e;case 2:Cr=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},h===null?(u=h=p,c=d):h=h.next=p,l|=f;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;f=a,a=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(h===null&&(c=d),s.baseState=c,s.firstBaseUpdate=u,s.lastBaseUpdate=h,t=s.shared.interleaved,t!==null){s=t;do l|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);_s|=l,e.lanes=l,e.memoizedState=d}}function Tm(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=ru.transition;ru.transition={};try{e(!1),t()}finally{Te=n,ru.transition=r}}function R_(){return wn().memoizedState}function f1(e,t,n){var r=Fr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},M_(e))I_(t,n);else if(n=g_(e,t,n,r),n!==null){var s=Ot();An(n,e,r,s),O_(n,t,r)}}function p1(e,t,n){var r=Fr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(M_(e))I_(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,a=i(l,n);if(s.hasEagerState=!0,s.eagerState=a,Dn(a,l)){var c=t.interleaved;c===null?(s.next=s,Lf(t)):(s.next=c.next,c.next=s),t.interleaved=s;return}}catch{}finally{}n=g_(e,t,s,r),n!==null&&(s=Ot(),An(n,e,r,s),O_(n,t,r))}}function M_(e){var t=e.alternate;return e===Ke||t!==null&&t===Ke}function I_(e,t){pl=Ba=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function O_(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vf(e,n)}}var za={readContext:bn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},m1={readContext:bn,useCallback:function(e,t){return Fn().memoizedState=[e,t===void 0?null:t],e},useContext:bn,useEffect:Dm,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,sa(4194308,4,P_.bind(null,t,e),n)},useLayoutEffect:function(e,t){return sa(4194308,4,e,t)},useInsertionEffect:function(e,t){return sa(4,2,e,t)},useMemo:function(e,t){var n=Fn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=f1.bind(null,Ke,e),[r.memoizedState,e]},useRef:function(e){var t=Fn();return e={current:e},t.memoizedState=e},useState:Lm,useDebugValue:$f,useDeferredValue:function(e){return Fn().memoizedState=e},useTransition:function(){var e=Lm(!1),t=e[0];return e=h1.bind(null,e[1]),Fn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ke,s=Fn();if($e){if(n===void 0)throw Error(Z(407));n=n()}else{if(n=t(),xt===null)throw Error(Z(349));ys&30||b_(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Dm(S_.bind(null,r,i,e),[e]),r.flags|=2048,Ol(9,w_.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Fn(),t=xt.identifierPrefix;if($e){var n=lr,r=ir;n=(r&~(1<<32-Pn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ml++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[Wn]=t,e[Ll]=r,V_(e,t,!1,!1),t.stateNode=e;e:{switch(l=vd(n,r),n){case"dialog":Be("cancel",e),Be("close",e),s=r;break;case"iframe":case"object":case"embed":Be("load",e),s=r;break;case"video":case"audio":for(s=0;sgi&&(t.flags|=128,r=!0,Ii(i,!1),t.lanes=4194304)}else{if(!r)if(e=Oa(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ii(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!$e)return Ct(t),null}else 2*et()-i.renderingStartTime>gi&&n!==1073741824&&(t.flags|=128,r=!0,Ii(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=et(),t.sibling=null,n=qe.current,Oe(qe,r?n&1|2:n&1),t):(Ct(t),null);case 22:case 23:return Vf(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?rn&1073741824&&(Ct(t),t.subtreeFlags&6&&(t.flags|=8192)):Ct(t),null;case 24:return null;case 25:return null}throw Error(Z(156,t.tag))}function S1(e,t){switch(Nf(t),t.tag){case 1:return Yt(t.type)&&Aa(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return pi(),Fe(Gt),Fe(Tt),If(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Mf(t),null;case 13:if(Fe(qe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Z(340));hi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Fe(qe),null;case 4:return pi(),null;case 10:return Tf(t.type._context),null;case 22:case 23:return Vf(),null;case 24:return null;default:return null}}var So=!1,Pt=!1,k1=typeof WeakSet=="function"?WeakSet:Set,ce=null;function ei(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ye(e,t,r)}else n.current=null}function qd(e,t,n){try{n()}catch(r){Ye(e,t,r)}}var Um=!1;function C1(e,t){if(Ed=ja,e=e_(),Cf(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,a=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||s!==0&&d.nodeType!==3||(a=l+s),d!==i||r!==0&&d.nodeType!==3||(c=l+r),d.nodeType===3&&(l+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===s&&(a=l),f===i&&++h===r&&(c=l),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=a===-1||c===-1?null:{start:a,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Pd={focusedElem:e,selectionRange:n},ja=!1,ce=t;ce!==null;)if(t=ce,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ce=e;else for(;ce!==null;){t=ce;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var x=m.memoizedProps,w=m.memoizedState,v=t.stateNode,y=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:jn(t.type,x),w);v.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var _=t.stateNode.containerInfo;_.nodeType===1?_.textContent="":_.nodeType===9&&_.documentElement&&_.removeChild(_.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Z(163))}}catch(b){Ye(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,ce=e;break}ce=t.return}return m=Um,Um=!1,m}function ml(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&qd(t,n,i)}s=s.next}while(s!==r)}}function xc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Kd(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function X_(e){var t=e.alternate;t!==null&&(e.alternate=null,X_(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Wn],delete t[Ll],delete t[Ld],delete t[o1],delete t[a1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Q_(e){return e.tag===5||e.tag===3||e.tag===4}function qm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Q_(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Vd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Pa));else if(r!==4&&(e=e.child,e!==null))for(Vd(e,t,n),e=e.sibling;e!==null;)Vd(e,t,n),e=e.sibling}function Gd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Gd(e,t,n),e=e.sibling;e!==null;)Gd(e,t,n),e=e.sibling}var yt=null,Nn=!1;function vr(e,t,n){for(n=n.child;n!==null;)J_(e,t,n),n=n.sibling}function J_(e,t,n){if(Kn&&typeof Kn.onCommitFiberUnmount=="function")try{Kn.onCommitFiberUnmount(cc,n)}catch{}switch(n.tag){case 5:Pt||ei(n,t);case 6:var r=yt,s=Nn;yt=null,vr(e,t,n),yt=r,Nn=s,yt!==null&&(Nn?(e=yt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):yt.removeChild(n.stateNode));break;case 18:yt!==null&&(Nn?(e=yt,n=n.stateNode,e.nodeType===8?eu(e.parentNode,n):e.nodeType===1&&eu(e,n),Nl(e)):eu(yt,n.stateNode));break;case 4:r=yt,s=Nn,yt=n.stateNode.containerInfo,Nn=!0,vr(e,t,n),yt=r,Nn=s;break;case 0:case 11:case 14:case 15:if(!Pt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&qd(n,t,l),s=s.next}while(s!==r)}vr(e,t,n);break;case 1:if(!Pt&&(ei(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Ye(n,t,a)}vr(e,t,n);break;case 21:vr(e,t,n);break;case 22:n.mode&1?(Pt=(r=Pt)||n.memoizedState!==null,vr(e,t,n),Pt=r):vr(e,t,n);break;default:vr(e,t,n)}}function Km(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new k1),t.forEach(function(r){var s=R1.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Cn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=l),r&=~i}if(r=s,r=et()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*N1(r/1960))-r,10e?16:e,Lr===null)var r=!1;else{if(e=Lr,Lr=null,Wa=0,Ne&6)throw Error(Z(331));var s=Ne;for(Ne|=4,ce=e.current;ce!==null;){var i=ce,l=i.child;if(ce.flags&16){var a=i.deletions;if(a!==null){for(var c=0;cet()-qf?hs(e,0):Uf|=n),Xt(e,t)}function lb(e,t){t===0&&(e.mode&1?(t=po,po<<=1,!(po&130023424)&&(po=4194304)):t=1);var n=Ot();e=hr(e,t),e!==null&&(Kl(e,t,n),Xt(e,n))}function D1(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),lb(e,n)}function R1(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Z(314))}r!==null&&r.delete(t),lb(e,n)}var ob;ob=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Gt.current)Vt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Vt=!1,b1(e,t,n);Vt=!!(e.flags&131072)}else Vt=!1,$e&&t.flags&1048576&&d_(t,Da,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ia(e,t),e=t.pendingProps;var s=di(t,Tt.current);oi(t,n),s=Bf(null,t,r,e,s,n);var i=zf();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Yt(r)?(i=!0,Ta(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Df(t),s.updater=gc,t.stateNode=s,s._reactInternals=t,Bd(t,r,e,n),t=$d(null,t,r,!0,i,n)):(t.tag=0,$e&&i&&jf(t),Mt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ia(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=I1(r),e=jn(r,e),s){case 0:t=Fd(null,t,r,e,n);break e;case 1:t=$m(null,t,r,e,n);break e;case 11:t=zm(null,t,r,e,n);break e;case 14:t=Fm(null,t,r,jn(r.type,e),n);break e}throw Error(Z(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),Fd(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),$m(e,t,r,s,n);case 3:e:{if(U_(t),e===null)throw Error(Z(387));r=t.pendingProps,i=t.memoizedState,s=i.element,x_(e,t),Ia(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=mi(Error(Z(423)),t),t=Wm(e,t,r,n,s);break e}else if(r!==s){s=mi(Error(Z(424)),t),t=Wm(e,t,r,n,s);break e}else for(sn=Or(t.stateNode.containerInfo.firstChild),ln=t,$e=!0,En=null,n=m_(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(hi(),r===s){t=fr(e,t,n);break e}Mt(e,t,r,n)}t=t.child}return t;case 5:return v_(t),e===null&&Md(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,l=s.children,Ad(r,s)?l=null:i!==null&&Ad(r,i)&&(t.flags|=32),H_(e,t),Mt(e,t,l,n),t.child;case 6:return e===null&&Md(t),null;case 13:return q_(e,t,n);case 4:return Rf(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=fi(t,null,r,n):Mt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),zm(e,t,r,s,n);case 7:return Mt(e,t,t.pendingProps,n),t.child;case 8:return Mt(e,t,t.pendingProps.children,n),t.child;case 12:return Mt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,l=s.value,Oe(Ra,r._currentValue),r._currentValue=l,i!==null)if(Dn(i.value,l)){if(i.children===s.children&&!Gt.current){t=fr(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){l=i.child;for(var c=a.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=ar(-1,n&-n),c.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Id(i.return,n,t),a.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(Z(341));l.lanes|=n,a=l.alternate,a!==null&&(a.lanes|=n),Id(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Mt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,oi(t,n),s=bn(s),r=r(s),t.flags|=1,Mt(e,t,r,n),t.child;case 14:return r=t.type,s=jn(r,t.pendingProps),s=jn(r.type,s),Fm(e,t,r,s,n);case 15:return $_(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:jn(r,s),ia(e,t),t.tag=1,Yt(r)?(e=!0,Ta(t)):e=!1,oi(t,n),B_(t,r,s),Bd(t,r,s,n),$d(null,t,r,!0,e,n);case 19:return K_(e,t,n);case 22:return W_(e,t,n)}throw Error(Z(156,t.tag))};function ab(e,t){return My(e,t)}function M1(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vn(e,t,n,r){return new M1(e,t,n,r)}function Yf(e){return e=e.prototype,!(!e||!e.isReactComponent)}function I1(e){if(typeof e=="function")return Yf(e)?1:0;if(e!=null){if(e=e.$$typeof,e===pf)return 11;if(e===mf)return 14}return 2}function $r(e,t){var n=e.alternate;return n===null?(n=vn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function aa(e,t,n,r,s,i){var l=2;if(r=e,typeof e=="function")Yf(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case qs:return fs(n.children,s,i,t);case ff:l=8,s|=8;break;case ad:return e=vn(12,n,t,s|2),e.elementType=ad,e.lanes=i,e;case cd:return e=vn(13,n,t,s),e.elementType=cd,e.lanes=i,e;case ud:return e=vn(19,n,t,s),e.elementType=ud,e.lanes=i,e;case vy:return yc(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case gy:l=10;break e;case xy:l=9;break e;case pf:l=11;break e;case mf:l=14;break e;case kr:l=16,r=null;break e}throw Error(Z(130,e==null?e:typeof e,""))}return t=vn(l,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function fs(e,t,n,r){return e=vn(7,e,r,t),e.lanes=n,e}function yc(e,t,n,r){return e=vn(22,e,r,t),e.elementType=vy,e.lanes=n,e.stateNode={isHidden:!1},e}function au(e,t,n){return e=vn(6,e,null,t),e.lanes=n,e}function cu(e,t,n){return t=vn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function O1(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Hc(0),this.expirationTimes=Hc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Hc(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Xf(e,t,n,r,s,i,l,a,c){return e=new O1(e,t,n,a,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=vn(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Df(i),e}function B1(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(hb)}catch(e){console.error(e)}}hb(),hy.exports=cn;var H1=hy.exports,eg=H1;ld.createRoot=eg.createRoot,ld.hydrateRoot=eg.hydrateRoot;/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var fb=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,q1=(e,t)=>{for(var n in t)fb(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,r)=>{for(var s=r>1?void 0:r?U1(t,n):t,i=e.length-1,l;i>=0;i--)(l=e[i])&&(s=(r?l(t,n,s):l(s))||s);return r&&s&&fb(t,n,s),s},le=(e,t)=>(n,r)=>t(n,r,e),tg="Terminal input",Zd={get:()=>tg,set:e=>tg=e},ng="Too much output to announce, navigate to rows manually to read",eh={get:()=>ng,set:e=>ng=e};function K1(e){return e.replace(/\r?\n/g,"\r")}function V1(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function G1(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Y1(e,t,n,r){if(e.stopPropagation(),e.clipboardData){let s=e.clipboardData.getData("text/plain");pb(s,t,n,r)}}function pb(e,t,n,r){e=K1(e),e=V1(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function mb(e,t,n){let r=n.getBoundingClientRect(),s=e.clientX-r.left-10,i=e.clientY-r.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${s}px`,t.style.top=`${i}px`,t.style.zIndex="1000",t.focus()}function rg(e,t,n,r,s){mb(e,t,n),s&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function jr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function kc(e,t=0,n=e.length){let r="";for(let s=t;s65535?(i-=65536,r+=String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):r+=String.fromCharCode(i)}return r}var X1=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,s=0;if(this._interim){let i=e.charCodeAt(s++);56320<=i&&i<=57343?t[r++]=(this._interim-55296)*1024+i-56320+65536:(t[r++]=this._interim,t[r++]=i),this._interim=0}for(let i=s;i=n)return this._interim=l,r;let a=e.charCodeAt(i);56320<=a&&a<=57343?t[r++]=(l-55296)*1024+a-56320+65536:(t[r++]=l,t[r++]=a);continue}l!==65279&&(t[r++]=l)}return r}},Q1=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,s,i,l,a,c=0,u=0;if(this.interim[0]){let f=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,x;for(;(x=this.interim[++m]&63)&&m<4;)p<<=6,p|=x;let w=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,v=w-m;for(;u=n)return 0;if(x=e[u++],(x&192)!==128){u--,f=!0;break}else this.interim[m++]=x,p<<=6,p|=x&63}f||(w===2?p<128?u--:t[r++]=p:w===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let h=n-4,d=u;for(;d=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(c=(s&31)<<6|i&63,c<128){d--;continue}t[r++]=c}else if((s&240)===224){if(d>=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,r;if(l=e[d++],(l&192)!==128){d--;continue}if(c=(s&15)<<12|(i&63)<<6|l&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((s&248)===240){if(d>=n)return this.interim[0]=s,r;if(i=e[d++],(i&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,r;if(l=e[d++],(l&192)!==128){d--;continue}if(d>=n)return this.interim[0]=s,this.interim[1]=i,this.interim[2]=l,r;if(a=e[d++],(a&192)!==128){d--;continue}if(c=(s&7)<<18|(i&63)<<12|(l&63)<<6|a&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},gb="",Dr=" ",Xl=class xb{constructor(){this.fg=0,this.bg=0,this.extended=new qa}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new xb;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},qa=class vb{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new vb(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},_n=class yb extends Xl{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new qa,this.combinedData=""}static fromCharData(t){let n=new yb;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?jr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let s=t[1].charCodeAt(1);56320<=s&&s<=57343?this.content=(r-55296)*1024+s-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},sg="di$target",th="di$dependencies",uu=new Map;function J1(e){return e[th]||[]}function vt(e){if(uu.has(e))return uu.get(e);let t=function(n,r,s){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Z1(t,n,s)};return t._id=e,uu.set(e,t),t}function Z1(e,t,n){t[sg]===t?t[th].push({id:e,index:n}):(t[th]=[{id:e,index:n}],t[sg]=t)}var Ft=vt("BufferService"),_b=vt("CoreMouseService"),Ns=vt("CoreService"),eC=vt("CharsetService"),ep=vt("InstantiationService"),bb=vt("LogService"),$t=vt("OptionsService"),wb=vt("OscLinkService"),tC=vt("UnicodeService"),Ql=vt("DecorationService"),nh=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],s=this._optionsService.rawOptions.linkHandler,i=new _n,l=n.getTrimmedLength(),a=-1,c=-1,u=!1;for(let h=0;hs?s.activate(m,x,f):nC(m,x),hover:(m,x)=>s?.hover?.(m,x,f),leave:(m,x)=>s?.leave?.(m,x,f)})}u=!1,i.hasExtendedAttrs()&&i.extended.urlId?(c=h,a=i.extended.urlId):(c=-1,a=-1)}}t(r)}};nh=Qe([le(0,Ft),le(1,$t),le(2,wb)],nh);function nC(e,t){if(confirm(`Do you want to navigate to ${t}? - -WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Cc=vt("CharSizeService"),mr=vt("CoreBrowserService"),tp=vt("MouseService"),gr=vt("RenderService"),rC=vt("SelectionService"),Sb=vt("CharacterJoinerService"),Si=vt("ThemeService"),kb=vt("LinkProviderService"),sC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?ig.isErrorNoTelemetry(e)?new ig(e.message+` - -`+e.stack):new Error(e.message+` - -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},iC=new sC;function ca(e){lC(e)||iC.onUnexpectedError(e)}var rh="Canceled";function lC(e){return e instanceof oC?!0:e instanceof Error&&e.name===rh&&e.message===rh}var oC=class extends Error{constructor(){super(rh),this.name=this.message}};function aC(e){return new Error(`Illegal argument: ${e}`)}var ig=class sh extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof sh)return t;let n=new sh;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},ih=class Cb extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Cb.prototype)}};function Zt(e,t=0){return e[e.length-(1+t)]}var cC;(e=>{function t(i){return i<0}e.isLessThan=t;function n(i){return i<=0}e.isLessThanOrEqual=n;function r(i){return i>0}e.isGreaterThan=r;function s(i){return i===0}e.isNeitherLessOrGreaterThan=s,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(cC||={});function uC(e,t){let n=this,r=!1,s;return function(){return r||(r=!0,t||(s=e.apply(n,arguments))),s}}var jb;(e=>{function t(b){return b&&typeof b=="object"&&typeof b[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*s(b){yield b}e.single=s;function i(b){return t(b)?b:s(b)}e.wrap=i;function l(b){return b||n}e.from=l;function*a(b){for(let j=b.length-1;j>=0;j--)yield b[j]}e.reverse=a;function c(b){return!b||b[Symbol.iterator]().next().done===!0}e.isEmpty=c;function u(b){return b[Symbol.iterator]().next().value}e.first=u;function h(b,j){let S=0;for(let N of b)if(j(N,S++))return!0;return!1}e.some=h;function d(b,j){for(let S of b)if(j(S))return S}e.find=d;function*f(b,j){for(let S of b)j(S)&&(yield S)}e.filter=f;function*p(b,j){let S=0;for(let N of b)yield j(N,S++)}e.map=p;function*m(b,j){let S=0;for(let N of b)yield*j(N,S++)}e.flatMap=m;function*x(...b){for(let j of b)yield*j}e.concat=x;function w(b,j,S){let N=S;for(let D of b)N=j(N,D);return N}e.reduce=w;function*v(b,j,S=b.length){for(j<0&&(j+=b.length),S<0?S+=b.length:S>b.length&&(S=b.length);j1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function dC(...e){return We(()=>ws(e))}function We(e){return{dispose:uC(()=>{e()})}}var Nb=class Eb{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ws(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Eb.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Nb.DISABLE_DISPOSED_WARNING=!1;var Wr=Nb,be=class{constructor(){this._store=new Wr,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};be.None=Object.freeze({dispose(){}});var xi=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},or=typeof window=="object"?window:globalThis,lh=class oh{constructor(t){this.element=t,this.next=oh.Undefined,this.prev=oh.Undefined}};lh.Undefined=new lh(void 0);var He=lh,lg=class{constructor(){this._first=He.Undefined,this._last=He.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===He.Undefined}clear(){let e=this._first;for(;e!==He.Undefined;){let t=e.next;e.prev=He.Undefined,e.next=He.Undefined,e=t}this._first=He.Undefined,this._last=He.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new He(e);if(this._first===He.Undefined)this._first=n,this._last=n;else if(t){let s=this._last;this._last=n,n.prev=s,s.next=n}else{let s=this._first;this._first=n,n.next=s,s.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==He.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==He.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==He.Undefined&&e.next!==He.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===He.Undefined&&e.next===He.Undefined?(this._first=He.Undefined,this._last=He.Undefined):e.next===He.Undefined?(this._last=this._last.prev,this._last.next=He.Undefined):e.prev===He.Undefined&&(this._first=this._first.next,this._first.prev=He.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==He.Undefined;)yield e.element,e=e.next}},hC=globalThis.performance&&typeof globalThis.performance.now=="function",fC=class Pb{static create(t){return new Pb(t)}constructor(t){this._now=hC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},_t;(e=>{e.None=()=>be.None;function t(T,E){return d(T,()=>{},0,void 0,!0,void 0,E)}e.defer=t;function n(T){return(E,O=null,I)=>{let W=!1,G;return G=T(P=>{if(!W)return G?G.dispose():W=!0,E.call(O,P)},null,I),W&&G.dispose(),G}}e.once=n;function r(T,E,O){return u((I,W=null,G)=>T(P=>I.call(W,E(P)),null,G),O)}e.map=r;function s(T,E,O){return u((I,W=null,G)=>T(P=>{E(P),I.call(W,P)},null,G),O)}e.forEach=s;function i(T,E,O){return u((I,W=null,G)=>T(P=>E(P)&&I.call(W,P),null,G),O)}e.filter=i;function l(T){return T}e.signal=l;function a(...T){return(E,O=null,I)=>{let W=dC(...T.map(G=>G(P=>E.call(O,P))));return h(W,I)}}e.any=a;function c(T,E,O,I){let W=O;return r(T,G=>(W=E(W,G),W),I)}e.reduce=c;function u(T,E){let O,I={onWillAddFirstListener(){O=T(W.fire,W)},onDidRemoveLastListener(){O?.dispose()}},W=new re(I);return E?.add(W),W.event}function h(T,E){return E instanceof Array?E.push(T):E&&E.add(T),T}function d(T,E,O=100,I=!1,W=!1,G,P){let z,C,Q,q=0,L,se={leakWarningThreshold:G,onWillAddFirstListener(){z=T(J=>{q++,C=E(C,J),I&&!Q&&(te.fire(C),C=void 0),L=()=>{let K=C;C=void 0,Q=void 0,(!I||q>1)&&te.fire(K),q=0},typeof O=="number"?(clearTimeout(Q),Q=setTimeout(L,O)):Q===void 0&&(Q=0,queueMicrotask(L))})},onWillRemoveListener(){W&&q>0&&L?.()},onDidRemoveLastListener(){L=void 0,z.dispose()}},te=new re(se);return P?.add(te),te.event}e.debounce=d;function f(T,E=0,O){return e.debounce(T,(I,W)=>I?(I.push(W),I):[W],E,void 0,!0,void 0,O)}e.accumulate=f;function p(T,E=(I,W)=>I===W,O){let I=!0,W;return i(T,G=>{let P=I||!E(G,W);return I=!1,W=G,P},O)}e.latch=p;function m(T,E,O){return[e.filter(T,E,O),e.filter(T,I=>!E(I),O)]}e.split=m;function x(T,E=!1,O=[],I){let W=O.slice(),G=T(C=>{W?W.push(C):z.fire(C)});I&&I.add(G);let P=()=>{W?.forEach(C=>z.fire(C)),W=null},z=new re({onWillAddFirstListener(){G||(G=T(C=>z.fire(C)),I&&I.add(G))},onDidAddFirstListener(){W&&(E?setTimeout(P):P())},onDidRemoveLastListener(){G&&G.dispose(),G=null}});return I&&I.add(z),z.event}e.buffer=x;function w(T,E){return(O,I,W)=>{let G=E(new y);return T(function(P){let z=G.evaluate(P);z!==v&&O.call(I,z)},void 0,W)}}e.chain=w;let v=Symbol("HaltChainable");class y{constructor(){this.steps=[]}map(E){return this.steps.push(E),this}forEach(E){return this.steps.push(O=>(E(O),O)),this}filter(E){return this.steps.push(O=>E(O)?O:v),this}reduce(E,O){let I=O;return this.steps.push(W=>(I=E(I,W),I)),this}latch(E=(O,I)=>O===I){let O=!0,I;return this.steps.push(W=>{let G=O||!E(W,I);return O=!1,I=W,G?W:v}),this}evaluate(E){for(let O of this.steps)if(E=O(E),E===v)break;return E}}function _(T,E,O=I=>I){let I=(...z)=>P.fire(O(...z)),W=()=>T.on(E,I),G=()=>T.removeListener(E,I),P=new re({onWillAddFirstListener:W,onDidRemoveLastListener:G});return P.event}e.fromNodeEventEmitter=_;function b(T,E,O=I=>I){let I=(...z)=>P.fire(O(...z)),W=()=>T.addEventListener(E,I),G=()=>T.removeEventListener(E,I),P=new re({onWillAddFirstListener:W,onDidRemoveLastListener:G});return P.event}e.fromDOMEventEmitter=b;function j(T){return new Promise(E=>n(T)(E))}e.toPromise=j;function S(T){let E=new re;return T.then(O=>{E.fire(O)},()=>{E.fire(void 0)}).finally(()=>{E.dispose()}),E.event}e.fromPromise=S;function N(T,E){return T(O=>E.fire(O))}e.forward=N;function D(T,E,O){return E(O),T(I=>E(I))}e.runAndSubscribe=D;class A{constructor(E,O){this._observable=E,this._counter=0,this._hasChanged=!1;let I={onWillAddFirstListener:()=>{E.addObserver(this)},onDidRemoveLastListener:()=>{E.removeObserver(this)}};this.emitter=new re(I),O&&O.add(this.emitter)}beginUpdate(E){this._counter++}handlePossibleChange(E){}handleChange(E,O){this._hasChanged=!0}endUpdate(E){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function k(T,E){return new A(T,E).emitter.event}e.fromObservable=k;function R(T){return(E,O,I)=>{let W=0,G=!1,P={beginUpdate(){W++},endUpdate(){W--,W===0&&(T.reportChanges(),G&&(G=!1,E.call(O)))},handlePossibleChange(){},handleChange(){G=!0}};T.addObserver(P),T.reportChanges();let z={dispose(){T.removeObserver(P)}};return I instanceof Wr?I.add(z):Array.isArray(I)&&I.push(z),z}}e.fromObservableLight=R})(_t||={});var ah=class ch{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${ch._idPool++}`,ch.all.add(this)}start(t){this._stopWatch=new fC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};ah.all=new Set,ah._idPool=0;var pC=ah,mC=-1,Ab=class Tb{constructor(t,n,r=(Tb._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,n){let r=this.threshold;if(r<=0||n{let i=this._stacks.get(t.value)||0;this._stacks.set(t.value,i-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[r,s]of this._stacks)(!t||n{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let a=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new yC(`${l}. HINT: Stack shows most frequent listener (${a[1]}-times)`,a[0]);return(this._options?.onListenerError||ca)(c),be.None}if(this._disposed)return be.None;t&&(e=e.bind(t));let r=new du(e),s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=xC.create(),s=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof du?(this._deliveryQueue??=new SC,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let i=We(()=>{s?.(),this._removeListener(r)});return n instanceof Wr?n.add(i):Array.isArray(n)&&n.push(i),i},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*bC<=t.length){let s=0;for(let i=0;i0}},SC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},uh=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new re,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new re,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(r,t),this._onDidChangeZoomLevel.fire(r)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToFullScreen.set(r,t),this._onDidChangeFullscreen.fire(r)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};uh.INSTANCE=new uh;var np=uh;function kC(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}np.INSTANCE.onDidChangeZoomLevel;function CC(e){return np.INSTANCE.getZoomFactor(e)}np.INSTANCE.onDidChangeFullscreen;var ki=typeof navigator=="object"?navigator.userAgent:"",dh=ki.indexOf("Firefox")>=0,jC=ki.indexOf("AppleWebKit")>=0,rp=ki.indexOf("Chrome")>=0,NC=!rp&&ki.indexOf("Safari")>=0;ki.indexOf("Electron/")>=0;ki.indexOf("Android")>=0;var hu=!1;if(typeof or.matchMedia=="function"){let e=or.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=or.matchMedia("(display-mode: fullscreen)");hu=e.matches,kC(or,e,({matches:n})=>{hu&&t.matches||(hu=n)})}var ni="en",hh=!1,fh=!1,ua=!1,Db=!1,jo,da=ni,og=ni,EC,nr,ps=globalThis,nn;typeof ps.vscode<"u"&&typeof ps.vscode.process<"u"?nn=ps.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(nn=process);var PC=typeof nn?.versions?.electron=="string",AC=PC&&nn?.type==="renderer";if(typeof nn=="object"){hh=nn.platform==="win32",fh=nn.platform==="darwin",ua=nn.platform==="linux",ua&&nn.env.SNAP&&nn.env.SNAP_REVISION,nn.env.CI||nn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,jo=ni,da=ni;let e=nn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);jo=t.userLocale,og=t.osLocale,da=t.resolvedLanguage||ni,EC=t.languagePack?.translationsConfigFile}catch{}Db=!0}else typeof navigator=="object"&&!AC?(nr=navigator.userAgent,hh=nr.indexOf("Windows")>=0,fh=nr.indexOf("Macintosh")>=0,(nr.indexOf("Macintosh")>=0||nr.indexOf("iPad")>=0||nr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ua=nr.indexOf("Linux")>=0,nr?.indexOf("Mobi")>=0,da=globalThis._VSCODE_NLS_LANGUAGE||ni,jo=navigator.language.toLowerCase(),og=jo):console.error("Unable to resolve platform.");var Rb=hh,Gn=fh,TC=ua,ag=Db,Yn=nr,yr=da,LC;(e=>{function t(){return yr}e.value=t;function n(){return yr.length===2?yr==="en":yr.length>=3?yr[0]==="e"&&yr[1]==="n"&&yr[2]==="-":!1}e.isDefaultVariant=n;function r(){return yr==="en"}e.isDefault=r})(LC||={});var DC=typeof ps.postMessage=="function"&&!ps.importScripts;(()=>{if(DC){let e=[];ps.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let r=0,s=e.length;r{let r=++t;e.push({id:r,callback:n}),ps.postMessage({vscodeScheduleAsyncWork:r},"*")}}return e=>setTimeout(e)})();var RC=!!(Yn&&Yn.indexOf("Chrome")>=0);Yn&&Yn.indexOf("Firefox")>=0;!RC&&Yn&&Yn.indexOf("Safari")>=0;Yn&&Yn.indexOf("Edg/")>=0;Yn&&Yn.indexOf("Android")>=0;var Ls=typeof navigator=="object"?navigator:{};ag||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ls&&Ls.clipboard&&Ls.clipboard.writeText,ag||Ls&&Ls.clipboard&&Ls.clipboard.readText;var sp=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},fu=new sp,cg=new sp,ug=new sp,MC=new Array(230),Mb;(e=>{function t(a){return fu.keyCodeToStr(a)}e.toString=t;function n(a){return fu.strToKeyCode(a)}e.fromString=n;function r(a){return cg.keyCodeToStr(a)}e.toUserSettingsUS=r;function s(a){return ug.keyCodeToStr(a)}e.toUserSettingsGeneral=s;function i(a){return cg.strToKeyCode(a)||ug.strToKeyCode(a)}e.fromUserSettings=i;function l(a){if(a>=98&&a<=113)return null;switch(a){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return fu.keyCodeToStr(a)}e.toElectronAccelerator=l})(Mb||={});var IC=class Ib{constructor(t,n,r,s,i){this.ctrlKey=t,this.shiftKey=n,this.altKey=r,this.metaKey=s,this.keyCode=i}equals(t){return t instanceof Ib&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",r=this.altKey?"1":"0",s=this.metaKey?"1":"0";return`K${t}${n}${r}${s}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new OC([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},OC=class{constructor(e){if(e.length===0)throw aC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t{function t(n){return n===e.None||n===e.Cancelled||n instanceof KC?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:_t.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Ob})})(qC||={});var KC=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Ob:(this._emitter||(this._emitter=new re),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},ip=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new ih("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new ih("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},VC=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new ih("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=We(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},GC;(e=>{async function t(r){let s,i=await Promise.all(r.map(l=>l.then(a=>a,a=>{s||(s=a)})));if(typeof s<"u")throw s;return i}e.settled=t;function n(r){return new Promise(async(s,i)=>{try{await r(s,i)}catch(l){i(l)}})}e.withAsyncBody=n})(GC||={});var pg=class fn{static fromArray(t){return new fn(n=>{n.emitMany(t)})}static fromPromise(t){return new fn(async n=>{n.emitMany(await t)})}static fromPromises(t){return new fn(async n=>{await Promise.all(t.map(async r=>n.emitOne(await r)))})}static merge(t){return new fn(async n=>{await Promise.all(t.map(async r=>{for await(let s of r)n.emitOne(s)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new re,queueMicrotask(async()=>{let r={emitOne:s=>this.emitOne(s),emitMany:s=>this.emitMany(s),reject:s=>this.reject(s)};try{await Promise.resolve(t(r)),this.resolve()}catch(s){this.reject(s)}finally{r.emitOne=void 0,r.emitMany=void 0,r.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new fn(async r=>{for await(let s of t)r.emitOne(n(s))})}map(t){return fn.map(this,t)}static filter(t,n){return new fn(async r=>{for await(let s of t)n(s)&&r.emitOne(s)})}filter(t){return fn.filter(this,t)}static coalesce(t){return fn.filter(t,n=>!!n)}coalesce(){return fn.coalesce(this)}static async toPromise(t){let n=[];for await(let r of t)n.push(r);return n}toPromise(){return fn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};pg.EMPTY=pg.fromArray([]);var{getWindow:qn,getWindowId:YC,onDidRegisterWindow:XC}=function(){let e=new Map,t={window:or,disposables:new Wr};e.set(or.vscodeWindowId,t);let n=new re,r=new re,s=new re;function i(l,a){return(typeof l=="number"?e.get(l):void 0)??(a?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:s.event,onDidUnregisterWindow:r.event,registerWindow(l){if(e.has(l.vscodeWindowId))return be.None;let a=new Wr,c={window:l,disposables:a.add(new Wr)};return e.set(l.vscodeWindowId,c),a.add(We(()=>{e.delete(l.vscodeWindowId),r.fire(l)})),a.add(me(l,ht.BEFORE_UNLOAD,()=>{s.fire(l)})),n.fire(c),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(l){return l.vscodeWindowId},hasWindow(l){return e.has(l)},getWindowById:i,getWindow(l){let a=l;if(a?.ownerDocument?.defaultView)return a.ownerDocument.defaultView.window;let c=l;return c?.view?c.view.window:or},getDocument(l){return qn(l).document}}}(),QC=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function me(e,t,n,r){return new QC(e,t,n,r)}var mg=function(e,t,n,r){return me(e,t,n,r)},lp,JC=class extends VC{constructor(e){super(),this.defaultTarget=e&&qn(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},gg=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){ca(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,s=i=>{n.set(i,!1);let l=e.get(i)??[];for(t.set(i,l),e.set(i,[]),r.set(i,!0);l.length>0;)l.sort(gg.sort),l.shift().execute();r.set(i,!1)};lp=(i,l,a=0)=>{let c=YC(i),u=new gg(l,a),h=e.get(c);return h||(h=[],e.set(c,h)),h.push(u),n.get(c)||(n.set(c,!0),i.requestAnimationFrame(()=>s(c))),u}})();function ZC(e){let t=e.getBoundingClientRect(),n=qn(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var ht={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},ej=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Wt(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Wt(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Wt(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Wt(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Wt(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Wt(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Wt(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Wt(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Wt(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Wt(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Wt(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Wt(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Wt(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Wt(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Wt(e){return typeof e=="number"?`${e}px`:e}function vl(e){return new ej(e)}var Bb=class{constructor(){this._hooks=new Wr,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=s;let i=e;try{e.setPointerCapture(t),this._hooks.add(We(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{i=qn(e)}this._hooks.add(me(i,ht.POINTER_MOVE,l=>{if(l.buttons!==n){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(me(i,ht.POINTER_UP,l=>this.stopMonitoring(!0)))}};function tj(e,t,n){let r=null,s=null;if(typeof n.value=="function"?(r="value",s=n.value,s.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(r="get",s=n.get),!s)throw new Error("not supported");let i=`$memoize$${t}`;n[r]=function(...l){return this.hasOwnProperty(i)||Object.defineProperty(this,i,{configurable:!1,enumerable:!1,writable:!1,value:s.apply(this,l)}),this[i]}}var zn;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(zn||={});var sl=class Nt extends be{constructor(){super(),this.dispatched=!1,this.targets=new lg,this.ignoreTargets=new lg,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(_t.runAndSubscribe(XC,({window:t,disposables:n})=>{n.add(me(t.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),n.add(me(t.document,"touchend",r=>this.onTouchEnd(t,r))),n.add(me(t.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:or,disposables:this._store}))}static addTarget(t){if(!Nt.isTouchDevice())return be.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.targets.push(t);return We(n)}static ignoreTarget(t){if(!Nt.isTouchDevice())return be.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.ignoreTargets.push(t);return We(n)}static isTouchDevice(){return"ontouchstart"in or||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,s=t.targetTouches.length;r=Nt.HOLD_DELAY&&Math.abs(c.initialPageX-Zt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Zt(c.rollingPageY))<30){let h=this.newGestureEvent(zn.Contextmenu,c.initialTarget);h.pageX=Zt(c.rollingPageX),h.pageY=Zt(c.rollingPageY),this.dispatchEvent(h)}else if(s===1){let h=Zt(c.rollingPageX),d=Zt(c.rollingPageY),f=Zt(c.rollingTimestamps)-c.rollingTimestamps[0],p=h-c.rollingPageX[0],m=d-c.rollingPageY[0],x=[...this.targets].filter(w=>c.initialTarget instanceof Node&&w.contains(c.initialTarget));this.inertia(t,x,r,Math.abs(p)/f,p>0?1:-1,h,Math.abs(m)/f,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(zn.End,c.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let r=document.createEvent("CustomEvent");return r.initEvent(t,!1,!0),r.initialTarget=n,r.tapCount=0,r}dispatchEvent(t){if(t.type===zn.Tap){let n=new Date().getTime(),r=0;n-this._lastSetTapCountTime>Nt.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===zn.Change||t.type===zn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(t.initialTarget))return;let n=[];for(let r of this.targets)if(r.contains(t.initialTarget)){let s=0,i=t.initialTarget;for(;i&&i!==r;)s++,i=i.parentElement;n.push([s,r])}n.sort((r,s)=>r[0]-s[0]);for(let[r,s]of n)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,s,i,l,a,c,u){this.handle=lp(t,()=>{let h=Date.now(),d=h-r,f=0,p=0,m=!0;s+=Nt.SCROLL_FRICTION*d,a+=Nt.SCROLL_FRICTION*d,s>0&&(m=!1,f=i*s*d),a>0&&(m=!1,p=c*a*d);let x=this.newGestureEvent(zn.Change);x.translationX=f,x.translationY=p,n.forEach(w=>w.dispatchEvent(x)),m||this.inertia(t,n,h,s,i,l+f,a,c,u+p)})}onTouchMove(t){let n=Date.now();for(let r=0,s=t.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(i.pageX),l.rollingPageY.push(i.pageY),l.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};sl.SCROLL_FRICTION=-.005,sl.HOLD_DELAY=700,sl.CLEAR_TAP_COUNT_TIME=400,Qe([tj],sl,"isTouchDevice",1);var nj=sl,op=class extends be{onclick(e,t){this._register(me(e,ht.CLICK,n=>t(new No(qn(e),n))))}onmousedown(e,t){this._register(me(e,ht.MOUSE_DOWN,n=>t(new No(qn(e),n))))}onmouseover(e,t){this._register(me(e,ht.MOUSE_OVER,n=>t(new No(qn(e),n))))}onmouseleave(e,t){this._register(me(e,ht.MOUSE_LEAVE,n=>t(new No(qn(e),n))))}onkeydown(e,t){this._register(me(e,ht.KEY_DOWN,n=>t(new dg(n))))}onkeyup(e,t){this._register(me(e,ht.KEY_UP,n=>t(new dg(n))))}oninput(e,t){this._register(me(e,ht.INPUT,t))}onblur(e,t){this._register(me(e,ht.BLUR,t))}onfocus(e,t){this._register(me(e,ht.FOCUS,t))}onchange(e,t){this._register(me(e,ht.CHANGE,t))}ignoreGesture(e){return nj.ignoreTarget(e)}},xg=11,rj=class extends op{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=xg+"px",this.domNode.style.height=xg+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Bb),this._register(mg(this.bgDomNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(mg(this.domNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new JC),this._pointerdownScheduleRepeatTimer=this._register(new ip)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,qn(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},sj=class ph{constructor(t,n,r,s,i,l,a){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,r=r|0,s=s|0,i=i|0,l=l|0,a=a|0),this.rawScrollLeft=s,this.rawScrollTop=a,n<0&&(n=0),s+n>r&&(s=r-n),s<0&&(s=0),i<0&&(i=0),a+i>l&&(a=l-i),a<0&&(a=0),this.width=n,this.scrollWidth=r,this.scrollLeft=s,this.height=i,this.scrollHeight=l,this.scrollTop=a}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new ph(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new ph(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let r=this.width!==t.width,s=this.scrollWidth!==t.scrollWidth,i=this.scrollLeft!==t.scrollLeft,l=this.height!==t.height,a=this.scrollHeight!==t.scrollHeight,c=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:r,scrollWidthChanged:s,scrollLeftChanged:i,heightChanged:l,scrollHeightChanged:a,scrollTopChanged:c}}},ij=class extends be{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new re),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new sj(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;t?r=new yg(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):r=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=yg.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},vg=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function pu(e,t){let n=t-e;return function(r){return e+n*aj(r)}}function lj(e,t,n){return function(r){return r2.5*r){let s,i;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},uj=140,zb=class extends op{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new cj(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Bb),this._shouldRender=!0,this.domNode=vl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(me(this.domNode.domNode,ht.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new rj(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=vl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof n=="number"&&this.slider.setWidth(n),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(me(this.slider.domNode,ht.POINTER_DOWN,s=>{s.button===0&&(s.preventDefault(),this._sliderPointerDown(s))})),this.onclick(this.slider.domNode,s=>{s.leftButton&&s.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),s=this._sliderPointerPosition(e);n<=s&&s<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,n=e.offsetY;else{let s=ZC(this.domNode.domNode);t=e.pageX-s.left,n=e.pageY-s.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,s=>{let i=this._sliderOrthogonalPointerPosition(s),l=Math.abs(i-n);if(Rb&&l>uj){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let a=this._sliderPointerPosition(s)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Fb=class gh{constructor(t,n,r,s,i,l){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(r),this._arrowSize=Math.round(t),this._visibleSize=s,this._scrollSize=i,this._scrollPosition=l,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new gh(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,r,s,i){let l=Math.max(0,r-t),a=Math.max(0,l-2*n),c=s>0&&s>r;if(!c)return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(r*a/s))),h=(a-u)/(s-r),d=i*h;return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=gh._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,r=this._scrollPosition;return n0&&Math.abs(t.deltaY)>0)return 1;let r=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(r+=.25),n){let s=Math.abs(t.deltaX),i=Math.abs(t.deltaY),l=Math.abs(n.deltaX),a=Math.abs(n.deltaY),c=Math.max(Math.min(s,l),1),u=Math.max(Math.min(i,a),1),h=Math.max(s,l),d=Math.max(i,a);h%c===0&&d%u===0&&(r-=.5)}return Math.min(Math.max(r,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};xh.INSTANCE=new xh;var mj=xh,gj=class extends op{constructor(e,t,n){super(),this._onScroll=this._register(new re),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new re),this.onWillScroll=this._onWillScroll.event,this._options=vj(t),this._scrollable=n,this._register(this._scrollable.onScroll(s=>{this._onWillScroll.fire(s),this._onDidScroll(s),this._onScroll.fire(s)}));let r={onMouseWheel:s=>this._onMouseWheel(s),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new hj(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new dj(this._scrollable,this._options,r)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=vl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=vl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=vl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,s=>this._onMouseOver(s)),this.onmouseleave(this._listenOnDomNode,s=>this._onMouseLeave(s)),this._hideTimeout=this._register(new ip),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ws(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Gn&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new fg(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ws(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new fg(n))};this._mouseWheelToDispose.push(me(this._listenOnDomNode,ht.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=mj.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let s=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+s===0?i=s=0:Math.abs(s)>=Math.abs(i)?i=0:s=0),this._options.flipAxes&&([s,i]=[i,s]);let l=!Gn&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||l)&&!i&&(i=s,s=0),e.browserEvent&&e.browserEvent.altKey&&(i=i*this._options.fastScrollSensitivity,s=s*this._options.fastScrollSensitivity);let a=this._scrollable.getFutureScrollPosition(),c={};if(s){let u=_g*s,h=a.scrollTop-(u<0?Math.floor(u):Math.ceil(u));this._verticalScrollbar.writeScrollPosition(c,h)}if(i){let u=_g*i,h=a.scrollLeft-(u<0?Math.floor(u):Math.ceil(u));this._horizontalScrollbar.writeScrollPosition(c,h)}c=this._scrollable.validateScrollPosition(c),(a.scrollLeft!==c.scrollLeft||a.scrollTop!==c.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(c):this._scrollable.setScrollPositionNow(c),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?" left":"",s=t?" top":"",i=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${s}`),this._topLeftShadowDomNode.setClassName(`shadow${i}${s}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),fj)}},xj=class extends gj{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function vj(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Gn&&(t.className+=" mac"),t}var vh=class extends be{constructor(e,t,n,r,s,i,l,a){super(),this._bufferService=n,this._optionsService=l,this._renderService=a,this._onRequestScrollLines=this._register(new re),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new ij({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:u=>lp(r.window,u)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new xj(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(s.onProtocolChange(u=>{this._scrollableElement.updateOptions({handleMouseWheel:!(u&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(_t.runAndSubscribe(i.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=i.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(We(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(We(()=>this._styleElement.remove())),this._register(_t.runAndSubscribe(i.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${i.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${i.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${i.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(u=>this._handleScroll(u)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};vh=Qe([le(2,Ft),le(3,mr),le(4,_b),le(5,Si),le(6,$t),le(7,gr)],vh);var yh=class extends be{constructor(e,t,n,r,s){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=s,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(i=>this._removeDecoration(i))),this._register(We(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};yh=Qe([le(1,Ft),le(2,mr),le(3,Ql),le(4,gr)],yh);var yj=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||"full"]&&t<=e.endBufferLine+this._linePadding[n||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},In={full:0,left:0,center:0,right:0},_r={full:0,left:0,center:0,right:0},Bi={full:0,left:0,center:0,right:0},Ka=class extends be{constructor(e,t,n,r,s,i,l,a){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=s,this._optionsService=i,this._themeService=l,this._coreBrowserService=a,this._colorZoneStore=new yj,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(We(()=>this._canvas?.remove()));let c=this._canvas.getContext("2d");if(c)this._ctx=c;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);_r.full=this._canvas.width,_r.left=e,_r.center=t,_r.right=e,this._refreshDrawHeightConstants(),Bi.full=1,Bi.left=1,Bi.center=1+_r.left,Bi.right=1+_r.left+_r.center}_refreshDrawHeightConstants(){In.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);In.left=t,In.center=t,In.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Bi[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-In[e.position||"full"]/2),_r[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+In[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Ka=Qe([le(2,Ft),le(3,Ql),le(4,gr),le(5,$t),le(6,Si),le(7,mr)],Ka);var V;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(V||={});var ha;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(ha||={});var $b;(e=>e.ST=`${V.ESC}\\`)($b||={});var _h=class{constructor(e,t,n,r,s,i){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=s,this._renderService=i,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let n;t.start+=this._dataAlreadySent.length,this._isComposing?n=this._textarea.value.substring(t.start,this._compositionPosition.start):n=this._textarea.value.substring(t.start),n.length>0&&this._coreService.triggerDataEvent(n,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,"");this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};_h=Qe([le(2,Ft),le(3,$t),le(4,Ns),le(5,gr)],_h);var pt=0,mt=0,gt=0,Ge=0,bg={css:"#00000000",rgba:0},rt;(e=>{function t(s,i,l,a){return a!==void 0?`#${Qr(s)}${Qr(i)}${Qr(l)}${Qr(a)}`:`#${Qr(s)}${Qr(i)}${Qr(l)}`}e.toCss=t;function n(s,i,l,a=255){return(s<<24|i<<16|l<<8|a)>>>0}e.toRgba=n;function r(s,i,l,a){return{css:e.toCss(s,i,l,a),rgba:e.toRgba(s,i,l,a)}}e.toColor=r})(rt||={});var ze;(e=>{function t(c,u){if(Ge=(u.rgba&255)/255,Ge===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,d=u.rgba>>16&255,f=u.rgba>>8&255,p=c.rgba>>24&255,m=c.rgba>>16&255,x=c.rgba>>8&255;pt=p+Math.round((h-p)*Ge),mt=m+Math.round((d-m)*Ge),gt=x+Math.round((f-x)*Ge);let w=rt.toCss(pt,mt,gt),v=rt.toRgba(pt,mt,gt);return{css:w,rgba:v}}e.blend=t;function n(c){return(c.rgba&255)===255}e.isOpaque=n;function r(c,u,h){let d=fa.ensureContrastRatio(c.rgba,u.rgba,h);if(d)return rt.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=r;function s(c){let u=(c.rgba|255)>>>0;return[pt,mt,gt]=fa.toChannels(u),{css:rt.toCss(pt,mt,gt),rgba:u}}e.opaque=s;function i(c,u){return Ge=Math.round(u*255),[pt,mt,gt]=fa.toChannels(c.rgba),{css:rt.toCss(pt,mt,gt,Ge),rgba:rt.toRgba(pt,mt,gt,Ge)}}e.opacity=i;function l(c,u){return Ge=c.rgba&255,i(c,Ge*u/255)}e.multiplyOpacity=l;function a(c){return[c.rgba>>24&255,c.rgba>>16&255,c.rgba>>8&255]}e.toColorRGB=a})(ze||={});var Ue;(e=>{let t,n;try{let s=document.createElement("canvas");s.width=1,s.height=1;let i=s.getContext("2d",{willReadFrequently:!0});i&&(t=i,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function r(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return pt=parseInt(s.slice(1,2).repeat(2),16),mt=parseInt(s.slice(2,3).repeat(2),16),gt=parseInt(s.slice(3,4).repeat(2),16),rt.toColor(pt,mt,gt);case 5:return pt=parseInt(s.slice(1,2).repeat(2),16),mt=parseInt(s.slice(2,3).repeat(2),16),gt=parseInt(s.slice(3,4).repeat(2),16),Ge=parseInt(s.slice(4,5).repeat(2),16),rt.toColor(pt,mt,gt,Ge);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let i=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(i)return pt=parseInt(i[1]),mt=parseInt(i[2]),gt=parseInt(i[3]),Ge=Math.round((i[5]===void 0?1:parseFloat(i[5]))*255),rt.toColor(pt,mt,gt,Ge);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=s,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[pt,mt,gt,Ge]=t.getImageData(0,0,1,1).data,Ge!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rt.toRgba(pt,mt,gt,Ge),css:s}}e.toColor=r})(Ue||={});var Rt;(e=>{function t(r){return n(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=t;function n(r,s,i){let l=r/255,a=s/255,c=i/255,u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),h=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);return u*.2126+h*.7152+d*.0722}e.relativeLuminance2=n})(Rt||={});var fa;(e=>{function t(l,a){if(Ge=(a&255)/255,Ge===1)return a;let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=l>>24&255,f=l>>16&255,p=l>>8&255;return pt=d+Math.round((c-d)*Ge),mt=f+Math.round((u-f)*Ge),gt=p+Math.round((h-p)*Ge),rt.toRgba(pt,mt,gt)}e.blend=t;function n(l,a,c){let u=Rt.relativeLuminance(l>>8),h=Rt.relativeLuminance(a>>8);if(er(u,h)>8));if(m>8));return m>w?p:x}return p}let d=s(l,a,c),f=er(u,Rt.relativeLuminance(d>>8));if(f>8));return f>m?d:p}return d}}e.ensureContrastRatio=n;function r(l,a,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=a>>24&255,p=a>>16&255,m=a>>8&255,x=er(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x0||p>0||m>0);)f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),m-=Math.max(0,Math.ceil(m*.1)),x=er(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));return(f<<24|p<<16|m<<8|255)>>>0}e.reduceLuminance=r;function s(l,a,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=a>>24&255,p=a>>16&255,m=a>>8&255,x=er(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x>>0}e.increaseLuminance=s;function i(l){return[l>>24&255,l>>16&255,l>>8&255,l&255]}e.toChannels=i})(fa||={});function Qr(e){let t=e.toString(16);return t.length<2?"0"+t:t}function er(e,t){return e1){let h=this._getJoinedRanges(r,l,i,t,s);for(let d=0;d1){let u=this._getJoinedRanges(r,l,i,t,s);for(let h=0;h=k,G=E,P=this._workCell;if(f.length>0&&E===f[0][0]&&W){let B=f.shift(),fe=this._isCellInSelection(B[0],t);for(y=B[0]+1;y=B[1],W?(I=!0,P=new _j(this._workCell,e.translateToString(!0,B[0],B[1]),B[1]-B[0]),G=B[1]-1,O=P.getWidth()):k=B[1]}let z=this._isCellInSelection(E,t),C=n&&E===i,Q=T&&E>=u&&E<=h,q=!1;this._decorationService.forEachDecorationAtCell(E,t,void 0,B=>{q=!0});let L=P.getChars()||Dr;if(L===" "&&(P.isUnderline()||P.isOverline())&&(L=" "),A=O*a-c.get(L,P.isBold(),P.isItalic()),!x)x=this._document.createElement("span");else if(w&&(z&&D||!z&&!D&&P.bg===_)&&(z&&D&&p.selectionForeground||P.fg===b)&&P.extended.ext===j&&Q===S&&A===N&&!C&&!I&&!q&&W){P.isInvisible()?v+=Dr:v+=L,w++;continue}else w&&(x.textContent=v),x=this._document.createElement("span"),w=0,v="";if(_=P.bg,b=P.fg,j=P.extended.ext,S=Q,N=A,D=z,I&&i>=E&&i<=G&&(i=E),!this._coreService.isCursorHidden&&C&&this._coreService.isCursorInitialized){if(R.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&R.push("xterm-cursor-blink"),R.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(s)switch(s){case"outline":R.push("xterm-cursor-outline");break;case"block":R.push("xterm-cursor-block");break;case"bar":R.push("xterm-cursor-bar");break;case"underline":R.push("xterm-cursor-underline");break}}if(P.isBold()&&R.push("xterm-bold"),P.isItalic()&&R.push("xterm-italic"),P.isDim()&&R.push("xterm-dim"),P.isInvisible()?v=Dr:v=P.getChars()||Dr,P.isUnderline()&&(R.push(`xterm-underline-${P.extended.underlineStyle}`),v===" "&&(v=" "),!P.isUnderlineColorDefault()))if(P.isUnderlineColorRGB())x.style.textDecorationColor=`rgb(${Xl.toColorRGB(P.getUnderlineColor()).join(",")})`;else{let B=P.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&P.isBold()&&B<8&&(B+=8),x.style.textDecorationColor=p.ansi[B].css}P.isOverline()&&(R.push("xterm-overline"),v===" "&&(v=" ")),P.isStrikethrough()&&R.push("xterm-strikethrough"),Q&&(x.style.textDecoration="underline");let se=P.getFgColor(),te=P.getFgColorMode(),J=P.getBgColor(),K=P.getBgColorMode(),Y=!!P.isInverse();if(Y){let B=se;se=J,J=B;let fe=te;te=K,K=fe}let ae,pe,Pe=!1;this._decorationService.forEachDecorationAtCell(E,t,void 0,B=>{B.options.layer!=="top"&&Pe||(B.backgroundColorRGB&&(K=50331648,J=B.backgroundColorRGB.rgba>>8&16777215,ae=B.backgroundColorRGB),B.foregroundColorRGB&&(te=50331648,se=B.foregroundColorRGB.rgba>>8&16777215,pe=B.foregroundColorRGB),Pe=B.options.layer==="top")}),!Pe&&z&&(ae=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,J=ae.rgba>>8&16777215,K=50331648,Pe=!0,p.selectionForeground&&(te=50331648,se=p.selectionForeground.rgba>>8&16777215,pe=p.selectionForeground)),Pe&&R.push("xterm-decoration-top");let $;switch(K){case 16777216:case 33554432:$=p.ansi[J],R.push(`xterm-bg-${J}`);break;case 50331648:$=rt.toColor(J>>16,J>>8&255,J&255),this._addStyle(x,`background-color:#${wg((J>>>0).toString(16),"0",6)}`);break;case 0:default:Y?($=p.foreground,R.push("xterm-bg-257")):$=p.background}switch(ae||P.isDim()&&(ae=ze.multiplyOpacity($,.5)),te){case 16777216:case 33554432:P.isBold()&&se<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(se+=8),this._applyMinimumContrast(x,$,p.ansi[se],P,ae,void 0)||R.push(`xterm-fg-${se}`);break;case 50331648:let B=rt.toColor(se>>16&255,se>>8&255,se&255);this._applyMinimumContrast(x,$,B,P,ae,pe)||this._addStyle(x,`color:#${wg(se.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(x,$,p.foreground,P,ae,pe)||Y&&R.push("xterm-fg-257")}R.length&&(x.className=R.join(" "),R.length=0),!C&&!I&&!q&&W?w++:x.textContent=v,A!==this.defaultSpacing&&(x.style.letterSpacing=`${A}px`),d.push(x),E=G}return x&&w&&(x.textContent=v),d}_applyMinimumContrast(e,t,n,r,s,i){if(this._optionsService.rawOptions.minimumContrastRatio===1||Sj(r.getCode()))return!1;let l=this._getContrastCache(r),a;if(!s&&!i&&(a=l.getColor(t.rgba,n.rgba)),a===void 0){let c=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);a=ze.ensureContrastRatio(s||t,i||n,c),l.setColor((s||t).rgba,(i||n).rgba,a??null)}return a?(this._addStyle(e,`color:${a.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};bh=Qe([le(1,Sb),le(2,$t),le(3,mr),le(4,Ns),le(5,Ql),le(6,Si)],bh);function wg(e,t,n){for(;e.length0&&(this._flat[r]=l),l}let s=e;t&&(s+="B"),n&&(s+="I");let i=this._holey.get(s);if(i===void 0){let l=0;t&&(l|=1),n&&(l|=2),i=this._measure(e,l),i>0&&this._holey.set(s,i)}return i}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},jj=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let s=e.buffers.active.ydisp,i=t[1]-s,l=n[1]-s,a=Math.max(i,0),c=Math.min(l,e.rows-1);if(a>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=i,this.viewportEndRow=l,this.viewportCappedStartRow=a,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function Nj(){return new jj}var mu="xterm-dom-renderer-owner-",dn="xterm-rows",Po="xterm-fg-",Sg="xterm-bg-",zi="xterm-focus",Ao="xterm-selection",Ej=1,wh=class extends be{constructor(e,t,n,r,s,i,l,a,c,u,h,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=s,this._helperContainer=i,this._linkifier2=l,this._charSizeService=c,this._optionsService=u,this._bufferService=h,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Ej++,this._rowElements=[],this._selectionRenderModel=Nj(),this.onRequestRedraw=this._register(new re).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(dn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Ao),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=kj(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(m=>this._injectCss(m))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(bh,document),this._element.classList.add(mu+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(m=>this._handleLinkHover(m))),this._register(this._linkifier2.onHideLinkUnderline(m=>this._handleLinkLeave(m))),this._register(We(()=>{this._element.classList.remove(mu+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Cj(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let n of this._rowElements)n.style.width=`${this.dimensions.css.canvas.width}px`,n.style.height=`${this.dimensions.css.cell.height}px`,n.style.lineHeight=`${this.dimensions.css.cell.height}px`,n.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${dn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${dn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${dn} .xterm-dim { color: ${ze.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,s=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${s} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${dn}.${zi} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${dn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Ao} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Ao} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Ao} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[i,l]of e.ansi.entries())t+=`${this._terminalSelector} .${Po}${i} { color: ${l.css}; }${this._terminalSelector} .${Po}${i}.xterm-dim { color: ${ze.multiplyOpacity(l,.5).css}; }${this._terminalSelector} .${Sg}${i} { background-color: ${l.css}; }`;t+=`${this._terminalSelector} .${Po}257 { color: ${ze.opaque(e.background).css}; }${this._terminalSelector} .${Po}257.xterm-dim { color: ${ze.multiplyOpacity(ze.opaque(e.background),.5).css}; }${this._terminalSelector} .${Sg}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let n=this._rowElements.length;n<=t;n++){let r=this._document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(zi),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(zi),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,s=this._selectionRenderModel.viewportEndRow,i=this._selectionRenderModel.viewportCappedStartRow,l=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(n){let c=e[0]>t[0];a.appendChild(this._createSelectionElement(i,c?t[0]:e[0],c?e[0]:t[0],l-i+1))}else{let c=r===i?e[0]:0,u=i===s?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(i,c,u));let h=l-i-1;if(a.appendChild(this._createSelectionElement(i+1,0,this._bufferService.cols,h)),i!==l){let d=s===l?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(l,0,d))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,n,r=1){let s=this._document.createElement("div"),i=t*this.dimensions.css.cell.width,l=this.dimensions.css.cell.width*(n-t);return i+l>this.dimensions.css.canvas.width&&(l=this.dimensions.css.canvas.width-i),s.style.height=`${r*this.dimensions.css.cell.height}px`,s.style.top=`${e*this.dimensions.css.cell.height}px`,s.style.left=`${i}px`,s.style.width=`${l}px`,s}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,s=Math.min(n.x,this._bufferService.cols-1),i=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,l=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let u=c+n.ydisp,h=this._rowElements[c],d=n.lines.get(u);if(!h||!d)break;h.replaceChildren(...this._rowFactory.createRow(d,u,u===r,l,a,s,i,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${mu}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,s,i){n<0&&(e=0),r<0&&(t=0);let l=this._bufferService.rows-1;n=Math.max(Math.min(n,l),0),r=Math.max(Math.min(r,l),0),s=Math.min(s,this._bufferService.cols);let a=this._bufferService.buffer,c=a.ybase+a.y,u=Math.min(a.x,s-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=n;p<=r;++p){let m=p+a.ydisp,x=this._rowElements[p],w=a.lines.get(m);if(!x||!w)break;x.replaceChildren(...this._rowFactory.createRow(w,m,m===c,d,f,u,h,this.dimensions.css.cell.width,this._widthCache,i?p===n?e:0:-1,i?(p===r?t:s)-1:-1))}}};wh=Qe([le(7,ep),le(8,Cc),le(9,$t),le(10,Ft),le(11,Ns),le(12,mr),le(13,Si)],wh);var Sh=class extends be{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new re),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Aj(this._optionsService))}catch{this._measureStrategy=this._register(new Pj(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Sh=Qe([le(2,$t)],Sh);var Wb=class extends be{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},Pj=class extends Wb{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Aj=class extends Wb{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Tj=class extends be{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Lj(this._window)),this._onDprChange=this._register(new re),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new re),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(r=>this._screenDprMonitor.setWindow(r))),this._register(_t.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(me(this._textarea,"focus",()=>this._isFocused=!0)),this._register(me(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Lj=class extends be{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new xi),this._onDprChange=this._register(new re),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(We(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=me(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Dj=class extends be{constructor(){super(),this.linkProviders=[],this._register(We(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function ap(e,t,n){let r=n.getBoundingClientRect(),s=e.getComputedStyle(n),i=parseInt(s.getPropertyValue("padding-left")),l=parseInt(s.getPropertyValue("padding-top"));return[t.clientX-r.left-i,t.clientY-r.top-l]}function Rj(e,t,n,r,s,i,l,a,c){if(!i)return;let u=ap(e,t,n);if(u)return u[0]=Math.ceil((u[0]+(c?l/2:0))/l),u[1]=Math.ceil(u[1]/a),u[0]=Math.min(Math.max(u[0],1),r+(c?1:0)),u[1]=Math.min(Math.max(u[1],1),s),u}var kh=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,s){return Rj(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(e,t){let n=ap(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};kh=Qe([le(0,gr),le(1,Cc)],kh);var Mj=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Hb={};q1(Hb,{getSafariVersion:()=>Oj,isChromeOS:()=>Vb,isFirefox:()=>Ub,isIpad:()=>Bj,isIphone:()=>zj,isLegacyEdge:()=>Ij,isLinux:()=>cp,isMac:()=>Ga,isNode:()=>jc,isSafari:()=>qb,isWindows:()=>Kb});var jc=typeof process<"u"&&"title"in process,Jl=jc?"node":navigator.userAgent,Zl=jc?"node":navigator.platform,Ub=Jl.includes("Firefox"),Ij=Jl.includes("Edge"),qb=/^((?!chrome|android).)*safari/i.test(Jl);function Oj(){if(!qb)return 0;let e=Jl.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Ga=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zl),Bj=Zl==="iPad",zj=Zl==="iPhone",Kb=["Windows","Win16","Win32","WinCE"].includes(Zl),cp=Zl.indexOf("Linux")>=0,Vb=/\bCrOS\b/.test(Jl),Gb=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._is){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=s}this.clear()}},Fj=class extends Gb{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},$j=class extends Gb{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ya=!jc&&"requestIdleCallback"in window?$j:Fj,Wj=class{constructor(){this._queue=new Ya}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Ch=class extends be{constructor(e,t,n,r,s,i,l,a,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=s,this._coreBrowserService=a,this._renderer=this._register(new xi),this._pausedResizeTask=new Wj,this._observerDisposable=this._register(new xi),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new re),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new re),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new re),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new re),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Mj((u,h)=>this._renderRows(u,h),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Hj(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(We(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(l.onResize(()=>this._fullRefresh())),this._register(l.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(i.onDecorationRegistered(()=>this._fullRefresh())),this._register(i.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(l.cols,l.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(l.buffer.y,l.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(u=>this._registerIntersectionObserver(u,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let n=new e.IntersectionObserver(r=>this._handleIntersectionChange(r[r.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=We(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Ch=Qe([le(2,$t),le(3,Cc),le(4,Ns),le(5,Ql),le(6,Ft),le(7,mr),le(8,Si)],Ch);var Hj=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Uj(e,t,n,r){let s=n.buffer.x,i=n.buffer.y;if(!n.buffer.hasScrollback)return Vj(s,i,e,t,n,r)+Nc(i,t,n,r)+Gj(s,i,e,t,n,r);let l;if(i===t)return l=s>e?"D":"C",Fl(Math.abs(s-e),zl(l,r));l=i>t?"D":"C";let a=Math.abs(i-t),c=Kj(i>t?e:s,n)+(a-1)*n.cols+1+qj(i>t?s:e);return Fl(c,zl(l,r))}function qj(e,t){return e-1}function Kj(e,t){return t.cols-e}function Vj(e,t,n,r,s,i){return Nc(t,r,s,i).length===0?"":Fl(Xb(e,t,e,t-Ss(t,s),!1,s).length,zl("D",i))}function Nc(e,t,n,r){let s=e-Ss(e,n),i=t-Ss(t,n),l=Math.abs(s-i)-Yj(e,t,n);return Fl(l,zl(Yb(e,t),r))}function Gj(e,t,n,r,s,i){let l;Nc(t,r,s,i).length>0?l=r-Ss(r,s):l=t;let a=r,c=Xj(e,t,n,r,s,i);return Fl(Xb(e,l,n,a,c==="C",s).length,zl(c,i))}function Yj(e,t,n){let r=0,s=e-Ss(e,n),i=t-Ss(t,n);for(let l=0;l=0&&e0?l=r-Ss(r,s):l=t,e=n&&lt?"A":"B"}function Xb(e,t,n,r,s,i){let l=e,a=t,c="";for(;(l!==n||a!==r)&&a>=0&&ai.cols-1?(c+=i.buffer.translateBufferLineToString(a,!1,e,l),l=0,e=0,a++):!s&&l<0&&(c+=i.buffer.translateBufferLineToString(a,!1,0,e+1),l=i.cols-1,e=l,a--);return c+i.buffer.translateBufferLineToString(a,!1,e,l)}function zl(e,t){let n=t?"O":"[";return V.ESC+n+e}function Fl(e,t){e=Math.floor(e);let n="";for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function kg(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var gu=50,Jj=15,Zj=50,eN=500,tN=" ",nN=new RegExp(tN,"g"),jh=class extends be{constructor(e,t,n,r,s,i,l,a,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=s,this._mouseService=i,this._optionsService=l,this._renderService=a,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new _n,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new re),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new re),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new re),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new re),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=u=>this._handleMouseMove(u),this._mouseUpListener=u=>this._handleMouseUp(u),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(u=>this._handleTrim(u)),this._register(this._bufferService.buffers.onBufferActivate(u=>this._handleBufferActivate(u))),this.enable(),this._model=new Qj(this._bufferService),this._activeSelectionMode=0,this._register(We(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(u=>{u.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let s=e[0]s.replace(nN," ")).join(Kb?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),cp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=kg(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=ap(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-gu),gu),t/=gu,t/Math.abs(t)+Math.round(t*(Jj-1)))}shouldForceSelection(e){return Ga?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Zj)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Ga&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let s=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:s>1&&t!==r&&(n+=s-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let s=this._bufferService.buffer,i=s.lines.get(e[1]);if(!i)return;let l=s.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(i,e[0]),c=a,u=e[0]-a,h=0,d=0,f=0,p=0;if(l.charAt(a)===" "){for(;a>0&&l.charAt(a-1)===" ";)a--;for(;c1&&(p+=y-1,c+=y-1);w>0&&a>0&&!this._isCharWordSeparator(i.loadCell(w-1,this._workCell));){i.loadCell(w-1,this._workCell);let _=this._workCell.getChars().length;this._workCell.getWidth()===0?(h++,w--):_>1&&(f+=_-1,a-=_-1),a--,w--}for(;v1&&(p+=_-1,c+=_-1),c++,v++}}c++;let m=a+u-h+f,x=Math.min(this._bufferService.cols,c-a+h+d-f-p);if(!(!t&&l.slice(a,c).trim()==="")){if(n&&m===0&&i.getCodePoint(0)!==32){let w=s.lines.get(e[1]-1);if(w&&i.isWrapped&&w.getCodePoint(this._bufferService.cols-1)!==32){let v=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(v){let y=this._bufferService.cols-v.start;m-=y,x+=y}}}if(r&&m+x===this._bufferService.cols&&i.getCodePoint(this._bufferService.cols-1)!==32){let w=s.lines.get(e[1]+1);if(w?.isWrapped&&w.getCodePoint(0)!==32){let v=this._getWordAt([0,e[1]+1],!1,!1,!0);v&&(x+=v.length)}}return{start:m,length:x}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=kg(n,this._bufferService.cols)}};jh=Qe([le(3,Ft),le(4,Ns),le(5,tp),le(6,$t),le(7,gr),le(8,mr)],jh);var Cg=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},jg=class{constructor(){this._color=new Cg,this._css=new Cg}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},it=Object.freeze((()=>{let e=[Ue.toColor("#2e3436"),Ue.toColor("#cc0000"),Ue.toColor("#4e9a06"),Ue.toColor("#c4a000"),Ue.toColor("#3465a4"),Ue.toColor("#75507b"),Ue.toColor("#06989a"),Ue.toColor("#d3d7cf"),Ue.toColor("#555753"),Ue.toColor("#ef2929"),Ue.toColor("#8ae234"),Ue.toColor("#fce94f"),Ue.toColor("#729fcf"),Ue.toColor("#ad7fa8"),Ue.toColor("#34e2e2"),Ue.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],s=t[n/6%6|0],i=t[n%6];e.push({css:rt.toCss(r,s,i),rgba:rt.toRgba(r,s,i)})}for(let n=0;n<24;n++){let r=8+n*10;e.push({css:rt.toCss(r,r,r),rgba:rt.toRgba(r,r,r)})}return e})()),ss=Ue.toColor("#ffffff"),il=Ue.toColor("#000000"),Ng=Ue.toColor("#ffffff"),Eg=il,Fi={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},rN=ss,Nh=class extends be{constructor(e){super(),this._optionsService=e,this._contrastCache=new jg,this._halfContrastCache=new jg,this._onChangeColors=this._register(new re),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ss,background:il,cursor:Ng,cursorAccent:Eg,selectionForeground:void 0,selectionBackgroundTransparent:Fi,selectionBackgroundOpaque:ze.blend(il,Fi),selectionInactiveBackgroundTransparent:Fi,selectionInactiveBackgroundOpaque:ze.blend(il,Fi),scrollbarSliderBackground:ze.opacity(ss,.2),scrollbarSliderHoverBackground:ze.opacity(ss,.4),scrollbarSliderActiveBackground:ze.opacity(ss,.5),overviewRulerBorder:ss,ansi:it.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Le(e.foreground,ss),t.background=Le(e.background,il),t.cursor=ze.blend(t.background,Le(e.cursor,Ng)),t.cursorAccent=ze.blend(t.background,Le(e.cursorAccent,Eg)),t.selectionBackgroundTransparent=Le(e.selectionBackground,Fi),t.selectionBackgroundOpaque=ze.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Le(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ze.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Le(e.selectionForeground,bg):void 0,t.selectionForeground===bg&&(t.selectionForeground=void 0),ze.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ze.opacity(t.selectionBackgroundTransparent,.3)),ze.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ze.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Le(e.scrollbarSliderBackground,ze.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Le(e.scrollbarSliderHoverBackground,ze.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Le(e.scrollbarSliderActiveBackground,ze.opacity(t.foreground,.5)),t.overviewRulerBorder=Le(e.overviewRulerBorder,rN),t.ansi=it.slice(),t.ansi[0]=Le(e.black,it[0]),t.ansi[1]=Le(e.red,it[1]),t.ansi[2]=Le(e.green,it[2]),t.ansi[3]=Le(e.yellow,it[3]),t.ansi[4]=Le(e.blue,it[4]),t.ansi[5]=Le(e.magenta,it[5]),t.ansi[6]=Le(e.cyan,it[6]),t.ansi[7]=Le(e.white,it[7]),t.ansi[8]=Le(e.brightBlack,it[8]),t.ansi[9]=Le(e.brightRed,it[9]),t.ansi[10]=Le(e.brightGreen,it[10]),t.ansi[11]=Le(e.brightYellow,it[11]),t.ansi[12]=Le(e.brightBlue,it[12]),t.ansi[13]=Le(e.brightMagenta,it[13]),t.ansi[14]=Le(e.brightCyan,it[14]),t.ansi[15]=Le(e.brightWhite,it[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;ri.index-l.index),r=[];for(let i of n){let l=this._services.get(i.id);if(!l)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${i.id._id}.`);r.push(l)}let s=n.length>0?n[0].index:t.length;if(t.length!==s)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${s+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},lN={trace:0,debug:1,info:2,warn:3,error:4,off:5},oN="xterm.js: ",Eh=class extends be{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=lN[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;r--)this._array[this._getCyclicIndex(r+n.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;rthis._maxLength){let r=this._length+n.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+n<0)throw new Error("Cannot shift elements in list beyond index 0");if(n>0){for(let s=t-1;s>=0;s--)this.set(e+s+n,this.get(e+s));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r]}set(t,n){this._data[t*_e+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*_e+0]=t|2097152|n[2]<<22):this._data[t*_e+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*_e+0]>>22}hasWidth(t){return this._data[t*_e+0]&12582912}getFg(t){return this._data[t*_e+1]}getBg(t){return this._data[t*_e+2]}hasContent(t){return this._data[t*_e+0]&4194303}getCodePoint(t){let n=this._data[t*_e+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*_e+0]&2097152}getString(t){let n=this._data[t*_e+0];return n&2097152?this._combined[t]:n&2097151?jr(n&2097151):""}isProtected(t){return this._data[t*_e+2]&536870912}loadCell(t,n){return To=t*_e,n.content=this._data[To+0],n.fg=this._data[To+1],n.bg=this._data[To+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*_e+0]=n.content,this._data[t*_e+1]=n.fg,this._data[t*_e+2]=n.bg}setCellFromCodepoint(t,n,r,s){s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*_e+0]=n|r<<22,this._data[t*_e+1]=s.fg,this._data[t*_e+2]=s.bg}addCodepointToCell(t,n,r){let s=this._data[t*_e+0];s&2097152?this._combined[t]+=jr(n):s&2097151?(this._combined[t]=jr(s&2097151)+jr(n),s&=-2097152,s|=2097152):s=n|1<<22,r&&(s&=-12582913,s|=r<<22),this._data[t*_e+0]=s}insertCells(t,n,r){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,r),n=0;--i)this.setCell(t+n+i,this.loadCell(t+i,s));for(let i=0;ithis.length){if(this._data.buffer.byteLength>=r*4)this._data=new Uint32Array(this._data.buffer,0,r);else{let s=new Uint32Array(r);s.set(this._data),this._data=s}for(let s=this.length;s=t&&delete this._combined[a]}let i=Object.keys(this._extendedAttrs);for(let l=0;l=t&&delete this._extendedAttrs[a]}}return this.length=t,r*4*xu=0;--t)if(this._data[t*_e+0]&4194303)return t+(this._data[t*_e+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*_e+0]&4194303||this._data[t*_e+2]&50331648)return t+(this._data[t*_e+0]>>22);return 0}copyCellsFrom(t,n,r,s,i){let l=t._data;if(i)for(let c=s-1;c>=0;c--){for(let u=0;u<_e;u++)this._data[(r+c)*_e+u]=l[(n+c)*_e+u];l[(n+c)*_e+2]&268435456&&(this._extendedAttrs[r+c]=t._extendedAttrs[n+c])}else for(let c=0;c=n&&(this._combined[u-n+r]=t._combined[u])}}translateToString(t,n,r,s){n=n??0,r=r??this.length,t&&(r=Math.min(r,this.getTrimmedLength())),s&&(s.length=0);let i="";for(;n>22||1}return s&&s.push(n),i}};function aN(e,t,n,r,s,i){let l=[];for(let a=0;a=a&&r0&&(w>d||h[w].getTrimmedLength()===0);w--)x++;x>0&&(l.push(a+h.length-x),l.push(x)),a+=h.length-1}return l}function cN(e,t){let n=[],r=0,s=t[r],i=0;for(let l=0;l$l(e,u,t)).reduce((c,u)=>c+u),i=0,l=0,a=0;for(;ac&&(i-=c,l++);let u=e[l].getWidth(i-1)===2;u&&i--;let h=u?n-1:n;r.push(h),a+=h}return r}function $l(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,s=e[t+1].getWidth(0)===2;return r&&s?n-1:n}var Jb=class Zb{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Zb._nextId++,this._onDispose=this.register(new re),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ws(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Jb._nextId=1;var hN=Jb,ut={},is=ut.B;ut[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ut.A={"#":"£"};ut.B=void 0;ut[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ut.C=ut[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ut.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ut.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ut.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ut.E=ut[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ut.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ut.H=ut[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Ag=4294967295,Tg=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=nt.clone(),this.savedCharset=is,this.markers=[],this._nullCell=_n.fromCharData([0,gb,1,0]),this._whitespaceCell=_n.fromCharData([0,Dr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ya,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Pg(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new qa),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new qa),this._whitespaceCell}getBlankLine(e,t){return new ll(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eAg?Ag:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=nt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Pg(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(nt),r=0,s=this._getCorrectBufferLength(t);if(s>this.lines.maxLength&&(this.lines.maxLength=s),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+i+1?(this.ybase--,i++,this.ydisp>0&&this.ydisp--):this.lines.push(new ll(e,n)));else for(let l=this._rows;l>t;l--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(s0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=s}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),i&&(this.y+=i),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let i=0;i.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=aN(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(nt),n);if(r.length>0){let s=cN(this.lines,r);uN(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(nt),s=n;for(;s-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let a=this.lines.get(l);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let c=[a];for(;a.isWrapped&&l>0;)a=this.lines.get(--l),c.unshift(a);if(!n){let _=this.ybase+this.y;if(_>=l&&_0&&(s.push({start:l+c.length+i,newLines:p}),i+=p.length),c.push(...p);let m=h.length-1,x=h[m];x===0&&(m--,x=h[m]);let w=c.length-d-1,v=u;for(;w>=0;){let _=Math.min(v,x);if(c[m]===void 0)break;if(c[m].copyCellsFrom(c[w],v-_,x-_,_,!0),x-=_,x===0&&(m--,x=h[m]),v-=_,v===0){w--;let b=Math.max(w,0);v=$l(c,b,this._cols)}}for(let _=0;_0;)this.ybase===0?this.y0){let l=[],a=[];for(let x=0;x=0;x--)if(d&&d.start>u+f){for(let w=d.newLines.length-1;w>=0;w--)this.lines.set(x--,d.newLines[w]);x++,l.push({index:u+1,amount:d.newLines.length}),f+=d.newLines.length,d=s[++h]}else this.lines.set(x,a[u--]);let p=0;for(let x=l.length-1;x>=0;x--)l[x].index+=p,this.lines.onInsertEmitter.fire(l[x]),p+=l[x].amount;let m=Math.max(0,c+i-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(e,t,n=0,r){let s=this.lines.get(e);return s?s.translateToString(t,n,r):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.linen.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},fN=class extends be{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new re),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Tg(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Tg(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},ew=2,tw=1,Ph=class extends be{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new re),this.onResize=this._onResize.event,this._onScroll=this._register(new re),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,ew),this.rows=Math.max(e.rawOptions.rows||0,tw),this.buffers=this._register(new fN(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let s=n.ybase+n.scrollTop,i=n.ybase+n.scrollBottom;if(n.scrollTop===0){let l=n.lines.isFull;i===n.lines.length-1?l?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(i+1,0,r.clone()),l?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let l=i-s+1;n.lines.shiftElements(s+1,l-1,-1),n.lines.set(i,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Ph=Qe([le(0,$t)],Ph);var Ds={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Ga,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},pN=["normal","bold","100","200","300","400","500","600","700","800","900"],mN=class extends be{constructor(e){super(),this._onOptionChange=this._register(new re),this.onOptionChange=this._onOptionChange.event;let t={...Ds};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(r){console.error(r)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(We(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=n=>{if(!(n in Ds))throw new Error(`No option with key "${n}"`);return this.rawOptions[n]},t=(n,r)=>{if(!(n in Ds))throw new Error(`No option with key "${n}"`);r=this._sanitizeAndValidateOption(n,r),this.rawOptions[n]!==r&&(this.rawOptions[n]=r,this._onOptionChange.fire(n))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ds[e]),!gN(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ds[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=pN.includes(t)?t:Ds[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function gN(e){return e==="block"||e==="underline"||e==="bar"}function ol(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&ol(e[r],t-1);return n}var Lg=Object.freeze({insertMode:!1}),Dg=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Ah=class extends be{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new re),this.onData=this._onData.event,this._onUserInput=this._register(new re),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new re),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new re),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=ol(Lg),this.decPrivateModes=ol(Dg)}reset(){this.modes=ol(Lg),this.decPrivateModes=ol(Dg)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(r=>r.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};Ah=Qe([le(0,Ft),le(1,bb),le(2,$t)],Ah);var Rg={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function vu(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var yu=String.fromCharCode,Mg={DEFAULT:e=>{let t=[vu(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${yu(t[0])}${yu(t[1])}${yu(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${vu(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${vu(e,!0)};${e.x};${e.y}${t}`}},Th=class extends be{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new re),this.onProtocolChange=this._onProtocolChange.event;for(let r of Object.keys(Rg))this.addProtocol(r,Rg[r]);for(let r of Object.keys(Mg))this.addEncoding(r,Mg[r]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,s=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(s/=r+0,Math.abs(e.deltaY)<50&&(s*=.3),this._wheelPartialScroll+=s,s=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(s*=this._bufferService.rows),s}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Th=Qe([le(0,Ft),le(1,Ns),le(2,$t)],Th);var _u=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],xN=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],lt;function vN(e,t){let n=0,r=t.length-1,s;if(et[r][1])return!1;for(;r>=n;)if(s=n+r>>1,e>t[s][1])n=s+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let s=ds.extractWidth(t);s===0?r=!1:s>n&&(n=s)}return ds.createPropertyValue(0,n,r)}},ds=class pa{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new re,this.onChange=this._onChange.event;let t=new yN;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,r=!1){return(t&16777215)<<3|(n&3)<<1|(r?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,r=0,s=t.length;for(let i=0;i=s)return n+this.wcwidth(l);let u=t.charCodeAt(i);56320<=u&&u<=57343?l=(l-55296)*1024+u-56320+65536:n+=this.wcwidth(u)}let a=this.charProperties(l,r),c=pa.extractWidth(a);pa.extractShouldJoin(a)&&(c-=pa.extractWidth(r)),n+=c,r=a}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},_N=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ig(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var $i=2147483647,bN=256,nw=class Lh{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>bN)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new Lh;if(!t.length)return n;for(let r=Array.isArray(t[0])?1:0;r>8,s=this._subParamsIdx[n]&255;s-r>0&&t.push(Array.prototype.slice.call(this._subParams,r,s))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>$i?$i:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>$i?$i:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;return r-n>0?this._subParams.subarray(n,r):null}getSubParamsAll(){let t={};for(let n=0;n>8,s=this._subParamsIdx[n]&255;s-r>0&&(t[n]=this._subParams.slice(r,s))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,s=r[n-1];r[n-1]=~s?Math.min(s*10+t,$i):t}},Wi=[],wN=class{constructor(){this._state=0,this._active=Wi,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Wi}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Wi,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Wi,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,"PUT",kc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let n=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Wi,this._id=-1,this._state=0}}},en=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=kc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(n=>(this._data="",this._hitLimit=!1,n));return this._data="",this._hitLimit=!1,t}},Hi=[],SN=class{constructor(){this._handlers=Object.create(null),this._active=Hi,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Hi}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Hi,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Hi,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let n=this._active.length-1;n>=0;n--)this._active[n].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,"PUT",kc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let n=!1,r=this._active.length-1,s=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Hi,this._ident=0}},al=new nw;al.addParam(0);var Og=class{constructor(e){this._handler=e,this._data="",this._params=al,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():al,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=kc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=al,this._data="",this._hitLimit=!1,n));return this._params=al,this._data="",this._hitLimit=!1,t}},kN=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let s=0;sc),n=(a,c)=>t.slice(a,c),r=n(32,127),s=n(0,24);s.push(25),s.push.apply(s,n(28,32));let i=n(0,14),l;e.setDefault(1,0),e.addMany(r,0,2,0);for(l in i)e.addMany([24,26,153,154],l,3,0),e.addMany(n(128,144),l,3,0),e.addMany(n(144,152),l,3,0),e.add(156,l,0,0),e.add(27,l,11,1),e.add(157,l,4,8),e.addMany([152,158,159],l,0,7),e.add(155,l,11,3),e.add(144,l,11,9);return e.addMany(s,0,3,0),e.addMany(s,1,3,1),e.add(127,1,0,1),e.addMany(s,8,0,8),e.addMany(s,3,3,3),e.add(127,3,0,3),e.addMany(s,4,3,4),e.add(127,4,0,4),e.addMany(s,6,3,6),e.addMany(s,5,3,5),e.add(127,5,0,5),e.addMany(s,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(s,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(s,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(s,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(s,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(s,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(s,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(pn,0,2,0),e.add(pn,8,5,8),e.add(pn,6,0,6),e.add(pn,11,0,11),e.add(pn,13,13,13),e}(),jN=class extends be{constructor(e=CN){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new nw,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,n,r)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,n)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(We(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new wN),this._dcsParser=this._register(new SN),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let s=0;si||i>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");n<<=8,n|=i}}if(e.final.length!==1)throw new Error("final must be a single byte");let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,s){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=s}parse(e,t,n){let r=0,s=0,i=0,l;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,i=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let a=this._parseStack.handlers,c=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&c>-1){for(;c>=0&&(l=a[c](this._params),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 4:if(n===!1&&c>-1){for(;c>=0&&(l=a[c](),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],l=this._dcsParser.unhook(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],l=this._oscParser.end(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,i=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=i;a>4){case 2:for(let f=a+1;;++f){if(f>=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=0&&(l=c[u](this._params),l!==!0);u--)if(l instanceof Promise)return this._preserveStack(3,c,u,s,a),l;u<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++a47&&r<60);a--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let h=this._escHandlers[this._collect<<8|r],d=h?h.length-1:-1;for(;d>=0&&(l=h[d](),l!==!0);d--)if(l instanceof Promise)return this._preserveStack(4,h,d,s,a),l;d<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let f=a+1;;++f)if(f>=t||(r=e[f])===24||r===26||r===27||r>127&&r=t||(r=e[f])<32||r>127&&r>4:i>>8}return r}}function bu(e,t){let n=e.toString(16),r=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function PN(e,t=16){let[n,r,s]=e;return`rgb:${bu(n,t)}/${bu(r,t)}/${bu(s,t)}`}var AN={"(":0,")":1,"*":2,"+":3,"-":1,".":2},br=131072,zg=10;function Fg(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var $g=5e3,Wg=0,TN=class extends be{constructor(e,t,n,r,s,i,l,a,c=new jN){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=s,this._oscLinkService=i,this._coreMouseService=l,this._unicodeService=a,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new X1,this._utf8Decoder=new Q1,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone(),this._onRequestBell=this._register(new re),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new re),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new re),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new re),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new re),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new re),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new re),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new re),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new re),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new re),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new re),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new re),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new re),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Dh(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,h)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:h.toArray()})}),this._parser.setEscHandlerFallback(u=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(u)})}),this._parser.setExecuteHandlerFallback(u=>{this._logService.debug("Unknown EXECUTE code: ",{code:u})}),this._parser.setOscHandlerFallback((u,h,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:h,data:d})}),this._parser.setDcsHandlerFallback((u,h,d)=>{h==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:h,payload:d})}),this._parser.setPrintHandler((u,h,d)=>this.print(u,h,d)),this._parser.registerCsiHandler({final:"@"},u=>this.insertChars(u)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},u=>this.scrollLeft(u)),this._parser.registerCsiHandler({final:"A"},u=>this.cursorUp(u)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},u=>this.scrollRight(u)),this._parser.registerCsiHandler({final:"B"},u=>this.cursorDown(u)),this._parser.registerCsiHandler({final:"C"},u=>this.cursorForward(u)),this._parser.registerCsiHandler({final:"D"},u=>this.cursorBackward(u)),this._parser.registerCsiHandler({final:"E"},u=>this.cursorNextLine(u)),this._parser.registerCsiHandler({final:"F"},u=>this.cursorPrecedingLine(u)),this._parser.registerCsiHandler({final:"G"},u=>this.cursorCharAbsolute(u)),this._parser.registerCsiHandler({final:"H"},u=>this.cursorPosition(u)),this._parser.registerCsiHandler({final:"I"},u=>this.cursorForwardTab(u)),this._parser.registerCsiHandler({final:"J"},u=>this.eraseInDisplay(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},u=>this.eraseInDisplay(u,!0)),this._parser.registerCsiHandler({final:"K"},u=>this.eraseInLine(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},u=>this.eraseInLine(u,!0)),this._parser.registerCsiHandler({final:"L"},u=>this.insertLines(u)),this._parser.registerCsiHandler({final:"M"},u=>this.deleteLines(u)),this._parser.registerCsiHandler({final:"P"},u=>this.deleteChars(u)),this._parser.registerCsiHandler({final:"S"},u=>this.scrollUp(u)),this._parser.registerCsiHandler({final:"T"},u=>this.scrollDown(u)),this._parser.registerCsiHandler({final:"X"},u=>this.eraseChars(u)),this._parser.registerCsiHandler({final:"Z"},u=>this.cursorBackwardTab(u)),this._parser.registerCsiHandler({final:"`"},u=>this.charPosAbsolute(u)),this._parser.registerCsiHandler({final:"a"},u=>this.hPositionRelative(u)),this._parser.registerCsiHandler({final:"b"},u=>this.repeatPrecedingCharacter(u)),this._parser.registerCsiHandler({final:"c"},u=>this.sendDeviceAttributesPrimary(u)),this._parser.registerCsiHandler({prefix:">",final:"c"},u=>this.sendDeviceAttributesSecondary(u)),this._parser.registerCsiHandler({final:"d"},u=>this.linePosAbsolute(u)),this._parser.registerCsiHandler({final:"e"},u=>this.vPositionRelative(u)),this._parser.registerCsiHandler({final:"f"},u=>this.hVPosition(u)),this._parser.registerCsiHandler({final:"g"},u=>this.tabClear(u)),this._parser.registerCsiHandler({final:"h"},u=>this.setMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"h"},u=>this.setModePrivate(u)),this._parser.registerCsiHandler({final:"l"},u=>this.resetMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"l"},u=>this.resetModePrivate(u)),this._parser.registerCsiHandler({final:"m"},u=>this.charAttributes(u)),this._parser.registerCsiHandler({final:"n"},u=>this.deviceStatus(u)),this._parser.registerCsiHandler({prefix:"?",final:"n"},u=>this.deviceStatusPrivate(u)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},u=>this.softReset(u)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},u=>this.setCursorStyle(u)),this._parser.registerCsiHandler({final:"r"},u=>this.setScrollRegion(u)),this._parser.registerCsiHandler({final:"s"},u=>this.saveCursor(u)),this._parser.registerCsiHandler({final:"t"},u=>this.windowOptions(u)),this._parser.registerCsiHandler({final:"u"},u=>this.restoreCursor(u)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},u=>this.insertColumns(u)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},u=>this.deleteColumns(u)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},u=>this.selectProtected(u)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},u=>this.requestMode(u,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},u=>this.requestMode(u,!1)),this._parser.setExecuteHandler(V.BEL,()=>this.bell()),this._parser.setExecuteHandler(V.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(V.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(V.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(V.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(V.BS,()=>this.backspace()),this._parser.setExecuteHandler(V.HT,()=>this.tab()),this._parser.setExecuteHandler(V.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(V.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(ha.IND,()=>this.index()),this._parser.setExecuteHandler(ha.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(ha.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new en(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new en(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new en(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new en(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new en(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new en(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new en(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new en(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new en(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new en(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new en(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new en(u=>this.restoreCursorColor(u))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let u in ut)this._parser.registerEscHandler({intermediates:"(",final:u},()=>this.selectCharset("("+u)),this._parser.registerEscHandler({intermediates:")",final:u},()=>this.selectCharset(")"+u)),this._parser.registerEscHandler({intermediates:"*",final:u},()=>this.selectCharset("*"+u)),this._parser.registerEscHandler({intermediates:"+",final:u},()=>this.selectCharset("+"+u)),this._parser.registerEscHandler({intermediates:"-",final:u},()=>this.selectCharset("-"+u)),this._parser.registerEscHandler({intermediates:".",final:u},()=>this.selectCharset("."+u)),this._parser.registerEscHandler({intermediates:"/",final:u},()=>this.selectCharset("/"+u));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(u=>(this._logService.error("Parsing error: ",u),u)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Og((u,h)=>this.requestStatusString(u,h)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),$g))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${$g} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,s=this._activeBuffer.y,i=0,l=this._parseStack.paused;if(l){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,s=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>br&&(i=this._parseStack.position+br)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,u=>String.fromCharCode(u)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(u=>u.charCodeAt(0)):e),this._parseBuffer.lengthbr)for(let u=i;u0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let f=this._parser.precedingJoinState;for(let p=t;pa){if(c){let v=d,y=this._activeBuffer.x-w;for(this._activeBuffer.x=w,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),w>0&&d instanceof ll&&d.copyCellsFrom(v,y,0,w,!1);y=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(u&&(d.insertCells(this._activeBuffer.x,s-w,this._activeBuffer.getNullCell(h)),d.getWidth(a-1)===2&&d.setCellFromCodepoint(a-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,r,s,h),s>0)for(;--s;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>Fg(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Og(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new en(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,s=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),s),r&&(i.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=a;for(let u=1;u0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(V.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(V.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(V.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(V.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(V.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(x[x.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",x[x.SET=1]="SET",x[x.RESET=2]="RESET",x[x.PERMANENTLY_SET=3]="PERMANENTLY_SET",x[x.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:i}=this._coreMouseService,l=this._coreService,{buffers:a,cols:c}=this._bufferService,{active:u,alt:h}=a,d=this._optionsService.rawOptions,f=(x,w)=>(l.triggerDataEvent(`${V.ESC}[${t?"":"?"}${x};${w}$y`),!0),p=x=>x?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(l.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:c===132?1:0:0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(s==="X10")):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!l.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(s==="VT200")):m===1002?f(m,p(s==="DRAG")):m===1003?f(m,p(s==="ANY")):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(i==="SGR")):m===1015?f(m,4):m===1016?f(m,p(i==="SGR_PIXELS")):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(u===h)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,s){return t===2?(e|=50331648,e&=-16777216,e|=Xl.fromColorRGB([n,r,s])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],s=0,i=0;do{if(r[i+s]=e.params[t+i],e.hasSubParams(t+i)){let l=e.getSubParams(t+i),a=0;do r[1]===5&&(s=1),r[i+a+1+s]=l[a];while(++a=2||r[1]===2&&i+s>=5)break;r[1]&&(s=1)}while(++i+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=nt.fg,e.bg=nt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let s=0;s=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777216|n-90|8):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777216|n-100|8):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(s)?e.getSubParams(s)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=nt.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=nt.bg&16777215):n===38||n===48||n===58?s+=this._extractColor(e,s,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=nt.fg&16777215,r.bg&=-67108864,r.bg|=nt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${V.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[?${t};${n}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=nt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Fg(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${V.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>zg&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>zg&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let r=n.shift(),s=n.shift();if(/^\d+$/.exec(r)){let i=parseInt(r);if(Hg(i))if(s==="?")t.push({type:0,index:i});else{let l=Bg(s);l&&t.push({type:1,index:i,color:l})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),r,s=n.findIndex(i=>i.startsWith("id="));return s!==-1&&(r=n[s].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let r=0;r=this._specialColors.length);++r,++t)if(n[r]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let s=Bg(n[r]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let r=0;r=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new _n;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${V.ESC}${l}${V.ESC}\\`),!0),r=this._bufferService.buffer,s=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Dh=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Wg=e,e=t,t=Wg),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Dh=Qe([le(0,Ft)],Dh);function Hg(e){return 0<=e&&e<256}var LN=5e7,Ug=12,DN=50,RN=class extends be{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new re),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>LN)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let r=this._writeBuffer[this._bufferOffset],s=this._action(r,t);if(s){let l=a=>performance.now()-n>=Ug?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(n,a);s.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(l);return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-n>=Ug)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>DN&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Rh=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),c={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(c,a)),this._dataByLinkId.set(c.id,c),c.id}let n=e,r=this._getEntryIdKey(n),s=this._entriesWithId.get(r);if(s)return this.addLineToLink(s.id,t.ybase+t.y),s.id;let i=t.addMarker(t.ybase+t.y),l={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(l,i)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(r=>r.line!==t)){let r=this._bufferService.buffer.addMarker(t);n.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(n,r))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Rh=Qe([le(0,Ft)],Rh);var qg=!1,MN=class extends be{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new xi),this._onBinary=this._register(new re),this.onBinary=this._onBinary.event,this._onData=this._register(new re),this.onData=this._onData.event,this._onLineFeed=this._register(new re),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new re),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new re),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new re),this._instantiationService=new iN,this.optionsService=this._register(new mN(e)),this._instantiationService.setService($t,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Ph)),this._instantiationService.setService(Ft,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Eh)),this._instantiationService.setService(bb,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Ah)),this._instantiationService.setService(Ns,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Th)),this._instantiationService.setService(_b,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(ds)),this._instantiationService.setService(tC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(_N),this._instantiationService.setService(eC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Rh),this._instantiationService.setService(wb,this._oscLinkService),this._inputHandler=this._register(new TN(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(_t.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(_t.forward(this._bufferService.onResize,this._onResize)),this._register(_t.forward(this.coreService.onData,this._onData)),this._register(_t.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new RN((t,n)=>this._inputHandler.parse(t,n))),this._register(_t.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new re),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!qg&&(this._logService.warn("writeSync is unreliable and will be removed soon."),qg=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,ew),t=Math.max(t,tw),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ig.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Ig(this._bufferService),!1))),this._windowsWrappingHeuristics.value=We(()=>{for(let t of e)t.dispose()})}}},IN={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function ON(e,t,n,r){let s={type:0,cancel:!1,key:void 0},i=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?s.key=V.ESC+"OA":s.key=V.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?s.key=V.ESC+"OD":s.key=V.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?s.key=V.ESC+"OC":s.key=V.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?s.key=V.ESC+"OB":s.key=V.ESC+"[B");break;case 8:s.key=e.ctrlKey?"\b":V.DEL,e.altKey&&(s.key=V.ESC+s.key);break;case 9:if(e.shiftKey){s.key=V.ESC+"[Z";break}s.key=V.HT,s.cancel=!0;break;case 13:s.key=e.altKey?V.ESC+V.CR:V.CR,s.cancel=!0;break;case 27:s.key=V.ESC,e.altKey&&(s.key=V.ESC+V.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;i?s.key=V.ESC+"[1;"+(i+1)+"D":t?s.key=V.ESC+"OD":s.key=V.ESC+"[D";break;case 39:if(e.metaKey)break;i?s.key=V.ESC+"[1;"+(i+1)+"C":t?s.key=V.ESC+"OC":s.key=V.ESC+"[C";break;case 38:if(e.metaKey)break;i?s.key=V.ESC+"[1;"+(i+1)+"A":t?s.key=V.ESC+"OA":s.key=V.ESC+"[A";break;case 40:if(e.metaKey)break;i?s.key=V.ESC+"[1;"+(i+1)+"B":t?s.key=V.ESC+"OB":s.key=V.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(s.key=V.ESC+"[2~");break;case 46:i?s.key=V.ESC+"[3;"+(i+1)+"~":s.key=V.ESC+"[3~";break;case 36:i?s.key=V.ESC+"[1;"+(i+1)+"H":t?s.key=V.ESC+"OH":s.key=V.ESC+"[H";break;case 35:i?s.key=V.ESC+"[1;"+(i+1)+"F":t?s.key=V.ESC+"OF":s.key=V.ESC+"[F";break;case 33:e.shiftKey?s.type=2:e.ctrlKey?s.key=V.ESC+"[5;"+(i+1)+"~":s.key=V.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:e.ctrlKey?s.key=V.ESC+"[6;"+(i+1)+"~":s.key=V.ESC+"[6~";break;case 112:i?s.key=V.ESC+"[1;"+(i+1)+"P":s.key=V.ESC+"OP";break;case 113:i?s.key=V.ESC+"[1;"+(i+1)+"Q":s.key=V.ESC+"OQ";break;case 114:i?s.key=V.ESC+"[1;"+(i+1)+"R":s.key=V.ESC+"OR";break;case 115:i?s.key=V.ESC+"[1;"+(i+1)+"S":s.key=V.ESC+"OS";break;case 116:i?s.key=V.ESC+"[15;"+(i+1)+"~":s.key=V.ESC+"[15~";break;case 117:i?s.key=V.ESC+"[17;"+(i+1)+"~":s.key=V.ESC+"[17~";break;case 118:i?s.key=V.ESC+"[18;"+(i+1)+"~":s.key=V.ESC+"[18~";break;case 119:i?s.key=V.ESC+"[19;"+(i+1)+"~":s.key=V.ESC+"[19~";break;case 120:i?s.key=V.ESC+"[20;"+(i+1)+"~":s.key=V.ESC+"[20~";break;case 121:i?s.key=V.ESC+"[21;"+(i+1)+"~":s.key=V.ESC+"[21~";break;case 122:i?s.key=V.ESC+"[23;"+(i+1)+"~":s.key=V.ESC+"[23~";break;case 123:i?s.key=V.ESC+"[24;"+(i+1)+"~":s.key=V.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?s.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?s.key=V.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?s.key=V.DEL:e.keyCode===219?s.key=V.ESC:e.keyCode===220?s.key=V.FS:e.keyCode===221&&(s.key=V.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let l=IN[e.keyCode]?.[e.shiftKey?1:0];if(l)s.key=V.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){let a=e.ctrlKey?e.keyCode-64:e.keyCode+32,c=String.fromCharCode(a);e.shiftKey&&(c=c.toUpperCase()),s.key=V.ESC+c}else if(e.keyCode===32)s.key=V.ESC+(e.ctrlKey?V.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let a=e.code.slice(3,4);e.shiftKey||(a=a.toLowerCase()),s.key=V.ESC+a,s.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(s.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?s.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(s.key=V.US),e.key==="@"&&(s.key=V.NUL));break}return s}var Je=0,BN=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ya,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ya,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((s,i)=>this._getKey(s)-this._getKey(i)),t=0,n=0,r=new Array(this._array.length+this._insertedValues.length);for(let s=0;s=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[s]=e[t],t++):r[s]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Je=this._search(t),Je===-1)||this._getKey(this._array[Je])!==t)return!1;do if(this._array[Je]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Je),!0;while(++Jes-i),t=0,n=new Array(this._array.length-e.length),r=0;for(let s=0;s0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Je=this._search(e),!(Je<0||Je>=this._array.length)&&this._getKey(this._array[Je])===e))do yield this._array[Je];while(++Je=this._array.length)&&this._getKey(this._array[Je])===e))do t(this._array[Je]);while(++Je=t;){let r=t+n>>1,s=this._getKey(this._array[r]);if(s>e)n=r-1;else if(s0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},wu=0,Kg=0,zN=class extends be{constructor(){super(),this._decorations=new BN(e=>e?.marker.line),this._onDecorationRegistered=this._register(new re),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new re),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(We(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new FN(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),r=t.onDispose(()=>{r.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,s=0;for(let i of this._decorations.getKeyIterator(t))r=i.options.x??0,s=r+(i.options.width??1),e>=r&&e{wu=s.options.x??0,Kg=wu+(s.options.width??1),e>=wu&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let s=r-this._lastRefreshMs,i=this._debounceThresholdMS-s;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},i)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Vg=20,Xa=class extends be{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let s=this._coreBrowserService.mainDocument;this._accessibilityContainer=s.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=s.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let i=0;ithis._handleBoundaryFocus(i,0),this._bottomBoundaryFocusListener=i=>this._handleBoundaryFocus(i,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=s.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new WN(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(i=>this._handleResize(i.rows))),this._register(this._terminal.onRender(i=>this._refreshRows(i.start,i.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(i=>this._handleChar(i))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(i=>this._handleTab(i))),this._register(this._terminal.onKey(i=>this._handleKey(i.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(me(s,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(We(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Vg+1&&(this._liveRegion.textContent+=eh.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let s=e;s<=t;s++){let i=n.lines.get(n.ydisp+s),l=[],a=i?.translateToString(!0,void 0,void 0,l)||"",c=(n.ydisp+s+1).toString(),u=this._rowElements[s];u&&(a.length===0?(u.textContent=" ",this._rowColumns.set(u,[0,1])):(u.textContent=a,this._rowColumns.set(u,l)),u.setAttribute("aria-posinset",c),u.setAttribute("aria-setsize",r),this._alignRowWidth(u))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],s=n.getAttribute("aria-posinset"),i=t===0?"1":`${this._terminal.buffer.lines.length}`;if(s===i||e.relatedTarget!==r)return;let l,a;if(t===0?(l=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(l=this._rowElements.shift(),a=n,this._rowContainer.removeChild(l)),l.removeEventListener("focus",this._topBoundaryFocusListener),a.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let c=this._createAccessibilityTreeNode();this._rowElements.unshift(c),this._rowContainer.insertAdjacentElement("afterbegin",c)}else{let c=this._createAccessibilityTreeNode();this._rowElements.push(c),this._rowContainer.appendChild(c)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let s=({node:a,offset:c})=>{let u=a instanceof Text?a.parentNode:a,h=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(h))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(u);if(!d)return console.warn("columns is null. Race condition?"),null;let f=c=this._terminal.cols&&(++h,f=0),{row:h,column:f}},i=s(t),l=s(n);if(!(!i||!l)){if(i.row>l.row||i.row===l.row&&i.column>=l.column)throw new Error("invalid range");this._terminal.select(i.column,i.row,(l.row-i.row)*this._terminal.cols-i.column+l.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{ws(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(me(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(me(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(me(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(me(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let r=0;r{r?.forEach(s=>{s.link.dispose&&s.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,s]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):s.provideLinks(e.y,i=>{if(this._isMouseOut)return;let l=i?.map(a=>({link:a}));this._activeProviderReplies?.set(r,l),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:l.link.range.end.x;for(let u=a;u<=c;u++){if(n.has(u)){s.splice(i--,1);break}n.add(u)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),s=!1;for(let i=0;ithis._linkAtPosition(l.link,t));i&&(n=!0,this._handleNewLink(i))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let i=0;ithis._linkAtPosition(a.link,t));if(l){n=!0,this._handleNewLink(l);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&HN(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ws(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let r=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(r,s),this._lastMouseEvent)){let i=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);i&&this._askForLink(i,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,s=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(s)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,s=t.y*this._bufferService.cols+t.x;return n<=s&&s<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,s){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:s}}};Mh=Qe([le(1,tp),le(2,gr),le(3,Ft),le(4,kb)],Mh);function HN(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var UN=class extends MN{constructor(e={}){super(e),this._linkifier=this._register(new xi),this.browser=Hb,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new xi),this._onCursorMove=this._register(new re),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new re),this.onKey=this._onKey.event,this._onRender=this._register(new re),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new re),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new re),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new re),this.onBell=this._onBell.event,this._onFocus=this._register(new re),this._onBlur=this._register(new re),this._onA11yCharEmitter=this._register(new re),this._onA11yTabEmitter=this._register(new re),this._onWillOpen=this._register(new re),this._setup(),this._decorationService=this._instantiationService.createInstance(zN),this._instantiationService.setService(Ql,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Dj),this._instantiationService.setService(kb,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(nh)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(_t.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(_t.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(_t.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(_t.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(We(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let n,r="";switch(t.index){case 256:n="foreground",r="10";break;case 257:n="background",r="11";break;case 258:n="cursor",r="12";break;default:n="ansi",r="4;"+t.index}switch(t.type){case 0:let s=ze.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${V.ESC}]${r};${PN(s)}${$b.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(i=>i.ansi[t.index]=rt.toColor(...t.color));else{let i=n;this._themeService.modifyColors(l=>l[i]=rt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Xa,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,s=t.getWidth(n),i=this._renderService.dimensions.css.cell.width*s,l=this.buffer.y*this._renderService.dimensions.css.cell.height,a=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=l+"px",this.textarea.style.width=i+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(me(this.element,"copy",t=>{this.hasSelection()&&G1(t,this._selectionService)}));let e=t=>Y1(t,this.textarea,this.coreService,this.optionsService);this._register(me(this.textarea,"paste",e)),this._register(me(this.element,"paste",e)),Ub?this._register(me(this.element,"mousedown",t=>{t.button===2&&rg(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(me(this.element,"contextmenu",t=>{rg(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),cp&&this._register(me(this.element,"auxclick",t=>{t.button===1&&mb(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(me(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(me(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(me(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(me(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(me(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(me(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(me(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(me(this.screenElement,"mousemove",s=>this.updateCursorStyle(s))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Zd.get()),Vb||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Tj,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(mr,this._coreBrowserService),this._register(me(this.textarea,"focus",s=>this._handleTextAreaFocus(s))),this._register(me(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Sh,this._document,this._helperContainer),this._instantiationService.setService(Cc,this._charSizeService),this._themeService=this._instantiationService.createInstance(Nh),this._instantiationService.setService(Si,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Va),this._instantiationService.setService(Sb,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ch,this.rows,this.screenElement)),this._instantiationService.setService(gr,this._renderService),this._register(this._renderService.onRenderedViewportChange(s=>this._onRender.fire(s))),this.onResize(s=>this._renderService.resize(s.cols,s.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(_h,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(kh),this._instantiationService.setService(tp,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Mh,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(vh,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(s=>{super.scrollLines(s,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(jh,this.element,this.screenElement,r)),this._instantiationService.setService(rC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(s=>this.scrollLines(s.amount,s.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(s=>this._renderService.handleSelectionChanged(s.start,s.end,s.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(s=>{this.textarea.value=s,this.textarea.focus(),this.textarea.select()})),this._register(_t.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(yh,this.screenElement)),this._register(me(this.element,"mousedown",s=>this._selectionService.handleMouseDown(s))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Xa,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",s=>this._handleScreenReaderModeOptionChange(s))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Ka,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",s=>{!this._overviewRulerRenderer&&s&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Ka,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(wh,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(i){let l=e._mouseService.getMouseReportCoords(i,e.screenElement);if(!l)return!1;let a,c;switch(i.overrideType||i.type){case"mousemove":c=32,i.buttons===void 0?(a=3,i.button!==void 0&&(a=i.button<3?i.button:3)):a=i.buttons&1?0:i.buttons&4?1:i.buttons&2?2:3;break;case"mouseup":c=0,a=i.button<3?i.button:3;break;case"mousedown":c=1,a=i.button<3?i.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(i)===!1)return!1;let u=i.deltaY;if(u===0||e.coreMouseService.consumeWheelEvent(i,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;c=u<0?0:1,a=4;break;default:return!1}return c===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:l.col,row:l.row,x:l.x,y:l.y,button:a,action:c,ctrl:i.ctrlKey,alt:i.altKey,shift:i.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s={mouseup:i=>(n(i),i.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(i)),wheel:i=>(n(i),this.cancel(i,!0)),mousedrag:i=>{i.buttons&&n(i)},mousemove:i=>{i.buttons||n(i)}};this._register(this.coreMouseService.onProtocolChange(i=>{i?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(i)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),i&8?r.mousemove||(t.addEventListener("mousemove",s.mousemove),r.mousemove=s.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),i&16?r.wheel||(t.addEventListener("wheel",s.wheel,{passive:!1}),r.wheel=s.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),i&2?r.mouseup||(r.mouseup=s.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),i&4?r.mousedrag||(r.mousedrag=s.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(me(t,"mousedown",i=>{if(i.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(i)))return n(i),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(i)})),this._register(me(t,"wheel",i=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(i)===!1)return!1;if(!this.buffer.hasScrollback){if(i.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(i,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(i,!0);let l=V.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(i.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(l,!0),this.cancel(i,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){pb(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=ON(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let r=this.rows-1;return this.scrollLines(n.type===2?-r:r),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===V.ETX||n.key===V.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(qN(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new _n)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Gg=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new VN(t)}getNullCell(){return new _n}},GN=class extends be{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new re),this.onBufferChange=this._onBufferChange.event,this._normal=new Gg(this._core.buffers.normal,"normal"),this._alternate=new Gg(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},YN=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,r)=>t(n,r.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},XN=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},QN=["cols","rows"],On=0,JN=class extends be{constructor(e){super(),this._core=this._register(new UN(e)),this._addonManager=this._register(new KN),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],n=(r,s)=>{this._checkReadonlyOptions(r),this._core.options[r]=s};for(let r in this._core.options){let s={get:t.bind(this,r),set:n.bind(this,r)};Object.defineProperty(this._publicOptions,r,s)}}_checkReadonlyOptions(e){if(QN.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new YN(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new XN(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new GN(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Zd.get()},set promptLabel(e){Zd.set(e)},get tooMuchOutput(){return eh.get()},set tooMuchOutput(e){eh.set(e)}}}_verifyIntegers(...e){for(On of e)if(On===1/0||isNaN(On)||On%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(On of e)if(On&&(On===1/0||isNaN(On)||On%1!==0||On<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var ZN=2,eE=1,tE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),s=Math.max(0,parseInt(n.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),l={top:parseInt(i.getPropertyValue("padding-top")),bottom:parseInt(i.getPropertyValue("padding-bottom")),right:parseInt(i.getPropertyValue("padding-right")),left:parseInt(i.getPropertyValue("padding-left"))},a=l.top+l.bottom,c=l.right+l.left,u=r-a,h=s-c-t;return{cols:Math.max(ZN,Math.floor(h/e.css.cell.width)),rows:Math.max(eE,Math.floor(u/e.css.cell.height))}}};function jt(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}function Ui(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Jr,hn,Rs,Lo;const Yg="__TAURI_TO_IPC_KEY__";function rw(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}class Wl{constructor(t){Jr.set(this,void 0),hn.set(this,0),Rs.set(this,[]),Lo.set(this,void 0),Ui(this,Jr,t||(()=>{})),this.id=rw(n=>{const r=n.index;if("end"in n){r==jt(this,hn,"f")?this.cleanupCallback():Ui(this,Lo,r);return}const s=n.message;if(r==jt(this,hn,"f")){for(jt(this,Jr,"f").call(this,s),Ui(this,hn,jt(this,hn,"f")+1);jt(this,hn,"f")in jt(this,Rs,"f");){const i=jt(this,Rs,"f")[jt(this,hn,"f")];jt(this,Jr,"f").call(this,i),delete jt(this,Rs,"f")[jt(this,hn,"f")],Ui(this,hn,jt(this,hn,"f")+1)}jt(this,hn,"f")===jt(this,Lo,"f")&&this.cleanupCallback()}else jt(this,Rs,"f")[r]=s})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(t){Ui(this,Jr,t)}get onmessage(){return jt(this,Jr,"f")}[(Jr=new WeakMap,hn=new WeakMap,Rs=new WeakMap,Lo=new WeakMap,Yg)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[Yg]()}}async function F(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}var Xg;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_SUSPENDED="tauri://suspended",e.WINDOW_RESUMED="tauri://resumed",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"})(Xg||(Xg={}));async function nE(e,t){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,t),await F("plugin:event|unlisten",{event:e,eventId:t})}async function Qa(e,t,n){var r;const s=(r=void 0)!==null&&r!==void 0?r:{kind:"Any"};return F("plugin:event|listen",{event:e,target:s,handler:rw(t)}).then(i=>async()=>nE(e,i))}async function Qg(e={}){return typeof e=="object"&&Object.freeze(e),await F("plugin:dialog|open",{options:e})}const rE="domain://event",sE="app-exit-work-guard";class iE{async health(t){return F("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await Qa(rE,r=>{t(r.payload)})}async pickFolder(){const t=await Qg({directory:!0,multiple:!1});return t==null?null:typeof t=="string"?t:null}async pickArchiveFile(){const t=await Qg({directory:!1,multiple:!1,filters:[{name:"Plugin archive",extensions:["ideaplug","zip","vsix"]}]});return typeof t=="string"?t:null}async onAppExitWorkGuard(t){return await Qa(sE,r=>{t(r.payload)})}async confirmAppExit(){await F("confirm_app_exit")}}function Ja(e,t){let n=Promise.resolve();return{sessionId:e,write(r){const s=n.then(async()=>{Jg("start",e,r),await F("write_terminal",{request:{sessionId:e,data:Array.from(r)}}),Jg("ok",e,r)});return n=s.catch(()=>{}),s},async resize(r,s){await F("resize_terminal",{request:{sessionId:e,rows:r,cols:s}})},detach(){t.onmessage=()=>{}},async close(){await F("close_terminal",{sessionId:e})}}}function Jg(e,t,n){n.length===1&&n[0]>=32&&n[0]!==127||console.info("[terminal-write]",e,{sessionId:t,bytes:n.length,control:lE(n)})}function lE(e){return e.length===0?"":e.length>16?"":Array.from(e).map(t=>{switch(t){case 13:return"\\r";case 10:return"\\n";case 127:return"\\x7f";default:return t<32?`\\x${t.toString(16).padStart(2,"0")}`:String.fromCharCode(t)}}).join("")}class oE{async openTerminal(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("open_terminal",{request:{cwd:t.cwd,rows:t.rows,cols:t.cols},onOutput:r});return Ja(s.sessionId,r)}async reattach(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Ja(s.sessionId,r),scrollback:Uint8Array.from(s.scrollback)}}async closeTerminal(t){await F("close_terminal",{sessionId:t})}}class aE{listAgents(t){return F("list_agents",{projectId:t})}listLiveAgents(t){return F("list_live_agents",{projectId:t})}listResumableAgents(t){return F("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return F("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return F("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return F("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,s,i){return F("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:s,cols:i}})}readContext(t,n){return F("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await F("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await F("delete_agent",{projectId:t,agentId:n})}async launchAgent(t,n,r,s){const i=new Wl;i.onmessage=c=>s(Uint8Array.from(c));const l=await F("launch_agent",{request:{projectId:t,agentId:n,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,nodeId:r.nodeId??null},onOutput:i});return{...Ja(l.sessionId,i),...l.assignedConversationId?{assignedConversationId:l.assignedConversationId}:{}}}async reattach(t,n){const r=new Wl;r.onmessage=i=>n(Uint8Array.from(i));const s=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Ja(s.sessionId,r),scrollback:Uint8Array.from(s.scrollback)}}inspectConversation(t,n,r){return F("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}}class cE{async interrupt(t,n){await F("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){console.info("[input-gateway] delegationDelivered:start",{projectId:t,agentId:n,ticket:r}),await F("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}}),console.info("[input-gateway] delegationDelivered:ok",{projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){console.info("[input-gateway] setFrontAttached:start",{agentId:t,attached:n}),await F("set_front_attached",{request:{agentId:t,attached:n}}),console.info("[input-gateway] setFrontAttached:ok",{agentId:t,attached:n})}async cancelResume(t){return F("cancel_resume",{agentId:t})}async setResumeAt(t,n){await F("set_resume_at",{agentId:t,resetsAtMs:n})}}class uE{listProjects(){return F("list_projects")}createProject(t,n){return F("create_project",{request:{name:t,root:n}})}openProject(t){return F("open_project",{projectId:t})}async closeProject(t){await F("close_project",{projectId:t})}readProjectContext(t){return F("read_project_context",{projectId:t})}async updateProjectContext(t,n){await F("update_project_context",{request:{projectId:t,content:n}})}}class dE{loadLayout(t,n){return F("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return F("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return F("list_layouts",{projectId:t})}createLayout(t,n,r){return F("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return F("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return F("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return F("set_active_layout",{request:{projectId:t,layoutId:n}})}}class hE{firstRunState(){return F("first_run_state")}referenceProfiles(){return F("reference_profiles")}detectProfiles(t){return F("detect_profiles",{request:{candidates:t}})}listProfiles(){return F("list_profiles")}saveProfile(t){return F("save_profile",{request:{profile:t}})}async deleteProfile(t){await F("delete_profile",{profileId:t})}configureProfiles(t){return F("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return F("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return F("list_opencode_providers")}saveOpenCodeProviderProfile(t){return F("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}listCodexProviders(){return F("list_codex_providers")}saveCodexProviderProfile(t){return F("save_codex_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}listClaudeProviders(){return F("list_claude_providers")}saveClaudeProviderProfile(t){return F("save_claude_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey}})}}class fE{listModelServers(){return F("list_model_servers")}saveModelServer(t){return F("save_model_server",{request:{config:t}})}async deleteModelServer(t){await F("delete_model_server",{serverId:t})}previewModelServerCommand(t){return F("preview_model_server_command",{config:t})}}const pE=2e3;class mE{constructor(t=pE){this.pollMs=t}getExposureSettings(){return F("get_server_exposure_settings")}async saveExposureSettings(t){await F("save_server_exposure_settings",{settings:t})}previewExposure(t){return F("preview_server_exposure_settings",{settings:t})}status(){return F("embedded_server_status")}start(){return F("embedded_server_start")}stop(){return F("embedded_server_stop")}async onStatusChanged(t){let n=!1;const r=setInterval(()=>{this.status().then(s=>{n||t(s)},()=>{})},this.pollMs);return()=>{n=!0,clearInterval(r)}}}class gE{listTemplates(){return F("list_templates")}createTemplate(t){return F("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return F("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await F("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return F("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return F("detect_agent_drift",{projectId:t})}syncAgent(t,n){return F("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class xE{listSkills(t,n){return F("list_skills",{projectId:t,scope:n})}createSkill(t){return F("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,s){return F("update_skill",{request:{projectId:t,scope:n,skillId:r,content:s}})}async deleteSkill(t,n,r){await F("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,s){await F("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:s}})}async unassignSkill(t,n,r){await F("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class vE{listMemories(t){return F("list_memories",{projectId:t})}getMemory(t,n){return F("get_memory",{projectId:t,slug:n})}createMemory(t){return F("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,s,i){return F("update_memory",{request:{projectId:t,slug:n,description:r,type:s,content:i}})}async deleteMemory(t,n){await F("delete_memory",{projectId:t,slug:n})}readIndex(t){return F("read_memory_index",{projectId:t})}resolveLinks(t,n){return F("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return F("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class yE{listEmbedderProfiles(){return F("list_embedder_profiles")}saveEmbedderProfile(t){return F("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await F("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return F("describe_embedder_engines")}}class _E{async listDevices(){return(await F("list_devices")).devices}createPairingCode(){return F("create_pairing_code")}renameDevice(t,n){return F("rename_device",{request:{deviceId:t,name:n}})}revokeDevice(t){return F("revoke_device",{request:{deviceId:t}})}revokeAllDevices(){return F("revoke_all_devices")}}class bE{status(t){return F("git_status",{projectId:t})}async stage(t,n){await F("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await F("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return F("git_commit",{request:{projectId:t,message:n}})}branches(t){return F("git_branches",{projectId:t})}async checkout(t,n){await F("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return F("git_log",{projectId:t,limit:n})}async init(t){await F("git_init",{projectId:t})}graph(t,n){return F("git_graph",{projectId:t,limit:n})}}class wE{getProjectPermissions(t){return F("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return F("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return F("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return F("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getProjectSystemPermissions(t){return F("get_project_system_permissions",{projectId:t})}updateProjectSystemPermissions(t,n){return F("update_project_system_permissions",{request:{projectId:t,permissions:n}})}updateAgentSystemPermissions(t,n,r){return F("update_agent_system_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentSystemPermissions(t,n){return F("resolve_agent_system_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return F("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return F("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return F("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}function Tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xe(e,t=""){return typeof e=="string"?e:t}function Xn(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function SE(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ms(e){return Array.isArray(e)?e:[]}function Zg(e){return typeof e=="string"?e:void 0}function ci(e){return typeof e=="string"?e:null}function sw(e){return Tn(e)?e.kind==="agent"?{kind:"agent",agentId:Xe(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function kE(e){return e==="inProgress"?"inProgress":"queued"}function CE(e){return Tn(e)&&e.state==="busy"?{state:"busy",ticket:Xe(e.ticket,"unknown"),sinceMs:Xn(e.sinceMs,0)}:{state:"idle"}}function jE(e,t){const n=Tn(e)?e:{},r=Xe(n.taskPreview);return{ticketId:Xe(n.ticketId,`legacy-ticket-${t}`),conversationId:Xe(n.conversationId),position:Xn(n.position,t),status:kE(n.status),source:sw(n.source),requesterLabel:Xe(n.requesterLabel),taskPreview:r,taskLen:Xn(n.taskLen,r.length)}}function NE(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="completed"||t==="success"||t==="succeeded"?"completed":t==="failed"||t==="failure"?"failed":t==="cancelled"||t==="canceled"||t==="expired"?"cancelled":t==="running"||t==="started"?"running":t==="delivered"?"delivered":"pending"}function EE(e,t,n){const r=Tn(e)?e:{};return{taskId:Xe(r.taskId,`legacy-task-${t}`),ownerAgentId:Xe(r.ownerAgentId,n),projectId:Xe(r.projectId),kind:Xe(r.kind,"background"),status:NE(r.status??r.state),exitCode:SE(r.exitCode),summary:ci(r.summary),stdoutTail:ci(r.stdoutTail),stderrTail:ci(r.stderrTail),updatedAtMs:Xn(r.updatedAtMs)}}function iw(e,t,n){const r=Tn(e)?e:{};return{id:Xe(r.id,`legacy-inbox-${t}`),agentId:Xe(r.agentId??r.agent_id,n),source:Xe(r.source,"unknown"),kind:Xe(r.kind,"message"),body:Xe(r.body),createdAtMs:Xn(r.createdAtMs??r.created_at_ms,0),...Zg(r.correlationId??r.correlation_id)?{correlationId:Zg(r.correlationId??r.correlation_id)}:{},priority:Xn(r.priority,0)}}function PE(e,t){const n=Tn(e)?e:{},r=Tn(n.live)&&n.live.kind==="structured"?"structured":"pty",s=Tn(n.live)?{nodeId:Xe(n.live.nodeId),sessionId:Xe(n.live.sessionId),kind:r}:void 0,i=Xe(n.agentId,`legacy-agent-${t}`),l=ms(n.inbox).map((c,u)=>iw(c,u,i)),a=ms(n.backgroundTasks??n.backgroundCompletions).map((c,u)=>EE(c,u,i));return{agentId:i,name:Xe(n.name,"Unnamed agent"),profileId:Xe(n.profileId,"unknown"),...s?{live:s}:{},busy:CE(n.busy),tickets:ms(n.tickets).map(jE),inboxDepth:Xn(n.inboxDepth,l.length),inbox:l,backgroundTasks:a}}function AE(e){return e==="ready"||e==="partial"||e==="unavailable"||e==="missing"?e:"missing"}function TE(e,t){const n=Tn(e)?e:{},r=Xe(n.textPreview);return{role:n.role==="response"||n.role==="toolActivity"?n.role:"prompt",source:sw(n.source),atMs:Xn(n.atMs,t),textPreview:r,textLen:Xn(n.textLen,r.length)}}function LE(e,t){const n=Tn(e)?e:{};return{conversationId:Xe(n.conversationId,`legacy-conversation-${t}`),status:AE(n.status),objectivePreview:ci(n.objectivePreview),summaryPreview:ci(n.summaryPreview),summaryLen:Xn(n.summaryLen,0),upTo:ci(n.upTo),recentTurns:ms(n.recentTurns).map(TE)}}function up(e){const t=Tn(e)?e:{},n=ms(t.agents).map(PE),r=ms(t.inboxItems).map((s,i)=>iw(s,i,""));for(const s of r){const i=n.find(l=>l.agentId===s.agentId);i&&(i.inbox??=[],i.inboxDepth??=0,i.inbox.some(l=>l.id===s.id)||(i.inbox.push(s),i.inboxDepth=Math.max(i.inboxDepth,i.inbox.length)))}return{agents:n,conversations:ms(t.conversations).map(LE)}}class DE{async getProjectWorkState(t){const n=await F("get_project_work_state",{projectId:t});return up(n)}async cancelBackgroundTask(t){await F("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await F("retry_background_task",{taskId:t})}}function dp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ih(e,t=""){return typeof e=="string"?e:t}function ex(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function RE(e){return Array.isArray(e)?e:[]}function ME(e){return dp(e)?e.kind==="agent"?{kind:"agent",agentId:Ih(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function IE(e){return e==="response"||e==="toolActivity"?e:"prompt"}function OE(e,t){const n=dp(e)?e:{},r=Ih(n.text);return{id:Ih(n.id,`turn-${t}`),atMs:ex(n.atMs,t),role:IE(n.role),source:ME(n.source),text:r,textLen:ex(n.textLen,r.length)}}function lw(e){const t=dp(e)?e:{},n=t.nextAnchor;return{turns:RE(t.turns).map(OE),hasMore:t.hasMore===!0,...typeof n=="string"?{nextAnchor:n}:{}}}class BE{async readPage(t,n,r){const s=await F("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return lw(s)}}class zE{async create(t,n){return F("ticket_create",{request:{projectId:t,...n}})}async read(t,n,r=!1){return F("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}async list(t,n){const{statuses:r,priorities:s,...i}=n??{};return F("ticket_list",{request:{projectId:t,statuses:r??[],priorities:s??[],...i}})}async update(t,n,r){return F("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await F("ticket_delete",{request:{projectId:t,ref:n}})}async readCarnet(t,n){return F("ticket_read_carnet",{request:{projectId:t,ref:n}})}async updateCarnet(t,n,r,s){return F("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:s}})}async link(t,n,r,s,i){return F("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:s,expectedVersion:i}})}async unlink(t,n,r,s,i){return F("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:s,kind:i}})}async assign(t,n,r,s,i){return F("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:s,expectedVersion:i}})}async listSprints(t){return(await F("sprint_list",{request:{projectId:t}})).items}async setTicketSprint(t,n,r,s){return r===null?F("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:s}}):F("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:s}})}async createSprint(t,n){return F("sprint_create",{request:{projectId:t,name:n}})}async renameSprint(t,n,r,s){return F("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:s}})}async reorderSprints(t,n){return(await F("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await F("sprint_delete",{request:{projectId:t,sprintId:n}})}async openTicketChat(t,n,r){return F("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await F("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const s=new Wl;s.onmessage=i=>r(i),await F("agent_send",{sessionId:t,prompt:n,onReply:s})}}const FE="view-window://lifecycle";class $E{async openViewWindow(t){await F("open_view_window",{panel:t})}async closeViewWindow(t){await F("close_view_window",{panel:t})}async listOpenViewWindows(){return F("list_open_view_windows")}async onViewWindowClosed(t){return await Qa(FE,r=>{r.payload.kind==="closed"&&t({panel:r.payload.panel})})}}const WE="focused-project://changed";class HE{async setFocusedProject(t){await F("set_focused_project",{project:t})}async getFocusedProject(){return await F("get_focused_project")??null}async onFocusedProjectChanged(t){return await Qa(WE,r=>t(r.payload.project??null))}}function Su(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}class ow{read(t){const n=Su();if(!n)return null;let r;try{r=n.getItem(t)}catch{return null}if(r===null)return null;try{return JSON.parse(r)}catch{try{n.removeItem(t)}catch{}return null}}write(t,n){const r=Su();if(r)try{r.setItem(t,JSON.stringify(n))}catch{}}remove(t){const n=Su();if(n)try{n.removeItem(t)}catch{}}}class UE{listPlugins(){return F("plugin_list_plugins")}reviewPackage(t){return F("plugin_review_package",{request:{sourceKind:t.sourceKind,path:t.path}})}installFromArchive(t){return F("plugin_install_from_archive",{path:t})}installFromDirectory(t){return F("plugin_install_from_directory",{path:t})}setEnabled(t,n){return F("plugin_set_enabled",{pluginId:t,enabled:n})}uninstall(t){return F("plugin_uninstall",{pluginId:t})}listRuntimeContributions(){return F("plugin_list_runtime_contributions")}async openPluginsFolder(t){await F("plugin_open_plugins_folder",{pluginId:t??null})}}function qE(e){throw{code:"NOT_IMPLEMENTED",message:`${e} is not implemented yet (pending its lot).`}}class KE{connect(){return qE("RemoteGateway.connect")}}function VE(){return{system:new iE,agent:new aE,input:new cE,terminal:new oE,project:new uE,layout:new dE,git:new bE,remote:new KE,profile:new hE,modelServer:new fE,desktopServer:new mE,template:new gE,skill:new xE,memory:new vE,embedder:new yE,device:new _E,permission:new wE,workState:new DE,conversation:new BE,ticket:new zE,window:new $E,focusedProject:new HE,uiPreferences:new ow,plugin:new UE}}function Oh(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Do(e=Oh()){return{root:{type:"leaf",node:{id:e,session:null}}}}function Bh(e){if(e.length===0)return[];const t=1e-6,n=e.map(s=>Number.isFinite(s)&&s>0?s:t),r=n.reduce((s,i)=>s+i,0);if(r<=0){const s=100/n.length;return n.map(()=>s)}return n.map(s=>s/r*100)}function tx(e,t,n){const r=[...e];if(t<0||t+1>=r.length)return r;const s=r.reduce((u,h)=>u+h,0),i=n*s,l=s*.05,a=r[t]+i,c=r[t+1]-i;return a({node:Ut(r.node,t),weight:r.weight}))}};break;case"grid":n={type:"grid",node:{...e.node,cells:e.node.cells.map(r=>({...r,node:Ut(r.node,t)}))}};break}return t(n)}function nx(e,t){let n;return Ut(e,r=>(r.type==="leaf"&&r.node.id===t&&(n=r.node.session??null),r)),n}function GE(e,t){switch(t.type){case"split":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const i={id:t.newLeaf,session:null};return{type:"split",node:{id:t.container,direction:t.direction,children:[{node:s,weight:1},{node:{type:"leaf",node:i},weight:1}]}}}return s});if(!n)throw tr(t.target);return{root:r}}case"merge":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="split"&&s.node.id===t.container){const i=s.node.children[t.keepIndex];if(!i)throw Ro(`merge keepIndex ${t.keepIndex} out of range`);return n=!0,i.node}return s});if(!n)throw tr(t.container);return{root:r}}case"resize":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="split"&&s.node.id===t.container){if(s.node.children.length!==t.weights.length)throw Ro("resize weight count mismatch");n=!0;const i=s.node.children.map((l,a)=>({node:l.node,weight:t.weights[a]}));return{type:"split",node:{...s.node,children:i}}}return s});if(!n)throw tr(t.container);return{root:r}}case"move":{const n=nx(e.root,t.from);if(n===void 0)throw tr(t.from);if(n===null)throw Ro("source cell has no session");const r=nx(e.root,t.to);if(r===void 0)throw tr(t.to);if(r!==null)throw Ro("target cell is occupied");return{root:Ut(e.root,i=>i.type==="leaf"&&i.node.id===t.from?{type:"leaf",node:{...i.node,session:null}}:i.type==="leaf"&&i.node.id===t.to?{type:"leaf",node:{...i.node,session:n}}:i)}}case"setSession":{let n=!1;const r=Ut(e.root,s=>s.type==="leaf"&&s.node.id===t.target?(n=!0,{type:"leaf",node:{...s.node,session:t.session??null}}):s);if(!n)throw tr(t.target);return{root:r}}case"setCellAgent":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{agent:i,...l}=s.node;return{type:"leaf",node:t.agent!==null?{...l,agent:t.agent}:l}}return s});if(!n)throw tr(t.target);return{root:r}}case"setCellConversation":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{conversationId:i,...l}=s.node;return{type:"leaf",node:t.conversationId!==null?{...l,conversationId:t.conversationId}:l}}return s});if(!n)throw tr(t.target);return{root:r}}case"setAgentRunning":{let n=!1;const r=Ut(e.root,s=>{if(s.type==="leaf"&&s.node.id===t.target){n=!0;const{agentWasRunning:i,...l}=s.node;return{type:"leaf",node:t.running?{...l,agentWasRunning:!0}:l}}return s});if(!n)throw tr(t.target);return{root:r}}}}function Za(e){const t=[];return Ut(e.root,n=>(n.type==="leaf"&&t.push(n.node),n)),t}function YE(e,t,n){return{root:Ut(e.root,r=>r.type==="customPluginLayout"&&r.node.id===t?{type:"customPluginLayout",node:{...r.node,state:n}}:r)}}function XE(e,t){return{root:Ut(e.root,n=>n.type==="customPluginLayout"&&n.node.id===t?{type:"leaf",node:{id:t}}:n)}}function QE(e,t){return{type:"split",target:e,direction:t,newLeaf:Oh(),container:Oh()}}function tr(e){return{code:"NOT_FOUND",message:`layout node ${e} not found`}}function Ro(e){return{code:"INVALID",message:e}}const rx={low:0,medium:1,high:2,critical:3},sx={open:0,inProgress:1,QA:2,closed:3};function JE(e,t){return e.sort((n,r)=>{let s=0;return t.field==="number"?s=n.number-r.number:t.field==="priority"?s=rx[n.priority]-rx[r.priority]:t.field==="status"?s=sx[n.status]-sx[r.status]:s=n.title.localeCompare(r.title,void 0,{sensitivity:"base"})||n.title.localeCompare(r.title),(t.direction==="desc"?-s:s)||n.number-r.number})}class ZE{constructor(){X(this,"listeners",new Set);X(this,"exitGuardListeners",new Set);X(this,"confirmAppExitCallCount",0)}async health(t){const n={version:"0.1.0-mock",alive:!0,timeMillis:Date.now(),correlationId:`mock-${Math.random().toString(36).slice(2,10)}`,note:t??null};return this.emit({type:"projectCreated",projectId:n.correlationId}),n}async onDomainEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(t){for(const n of this.listeners)n(t)}async pickFolder(){return"/home/user/mock-project"}async pickArchiveFile(){return"/home/user/mock-plugin.ideaplug"}async onAppExitWorkGuard(t){return this.exitGuardListeners.add(t),()=>{this.exitGuardListeners.delete(t)}}emitAppExitWorkGuard(t){for(const n of this.exitGuardListeners)n(t)}async confirmAppExit(){this.confirmAppExitCallCount+=1}}function hp(e){let t="",n=!1;for(const r of e.trim())/[a-zA-Z0-9]/.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="-",n=!0);return t.replace(/^-+|-+$/g,"")}class zh{constructor(t,n){X(this,"scrollback",[]);X(this,"sink",null);X(this,"closed",!1);this.sessionId=t,this.sink=n}emit(t){if(!this.closed){for(const n of t)this.scrollback.push(n);this.sink?.(t)}}detach(){this.sink=null}reattach(t){return this.sink=t,Uint8Array.from(this.scrollback)}}class e2{constructor(){X(this,"agents",new Map);X(this,"contexts",new Map);X(this,"sessionSeq",0);X(this,"sessions",new Map);X(this,"liveByAgent",new Map);X(this,"liveSessionByAgent",new Map);X(this,"resumable",new Map);X(this,"conversationDetails",new Map)}getAgents(t){return this.agents.has(t)||this.agents.set(t,[]),this.agents.get(t)}contextKey(t,n){return`${t}::${n}`}async listAgents(t){return structuredClone(this.getAgents(t))}async listLiveAgents(t){const n=new Set(this.getAgents(t).map(r=>r.id));return[...this.liveByAgent.entries()].filter(([r])=>n.has(r)).map(([r,s])=>({agentId:r,nodeId:s,sessionId:this.liveSessionByAgent.get(r),kind:"pty"}))}_setResumableAgents(t,n){this.resumable.set(t,n)}async listResumableAgents(t){return structuredClone(this.resumable.get(t)??[])}async attachLiveAgent(t,n,r){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const i=this.liveSessionByAgent.get(n);if(!i||!this.sessions.has(i))throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};return this.liveByAgent.set(n,r),{agentId:n,nodeId:r,sessionId:i,kind:"pty"}}async stopLiveAgent(t,n){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const s=this.liveSessionByAgent.get(n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};const i=this.sessions.get(s);return i&&(i.closed=!0),this.sessions.delete(s),this.liveSessionByAgent.delete(n),this.liveByAgent.delete(n),{agentId:n,sessionId:s,kind:"pty"}}async createAgent(t,n){const r=this.getAgents(t),s=hp(n.name)||"agent",i=new Set(r.map(u=>u.contextPath));let l=`agents/${s}.md`,a=2;for(;i.has(l);)l=`agents/${s}-${a}.md`,a+=1;const c={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:n.name,contextPath:l,profileId:n.profileId,origin:{type:"scratch"},synchronized:!1,skills:[]};return r.push(c),this.contexts.set(this.contextKey(t,c.id),n.initialContent??""),structuredClone(c)}async readContext(t,n){if(!this.getAgents(t).some(s=>s.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};return this.contexts.get(this.contextKey(t,n))??""}async updateContext(t,n,r){if(!this.getAgents(t).some(i=>i.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.contexts.set(this.contextKey(t,n),r)}async deleteAgent(t,n){const r=this.getAgents(t),s=r.findIndex(i=>i.id===n);if(s===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};r.splice(s,1),this.contexts.delete(this.contextKey(t,n))}async changeAgentProfile(t,n,r,s,i){const l=this.getAgents(t),a=l.findIndex(m=>m.id===n);if(a===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};l[a]={...l[a],profileId:r};const c=structuredClone(l[a]),u=this.liveByAgent.get(n),h=this.liveSessionByAgent.get(n);if(!u||!h)return{agent:c};const d=this.sessions.get(h);d&&(d.closed=!0),this.sessions.delete(h),this.sessionSeq+=1;const f=`mock-agent-session-${this.sessionSeq}`,p=new zh(f,()=>{});return p.detach(),this.sessions.set(f,p),this.liveSessionByAgent.set(n,f),this.liveByAgent.set(n,u),{agent:c,relaunchedSession:{sessionId:f,cwd:"/home/user/mock-project",rows:s,cols:i}}}_insertAgent(t,n,r){this.getAgents(t).push(n),this.contexts.set(this.contextKey(t,n.id),r)}_updateAgent(t,n,r,s){const i=this.getAgents(t),l=i.findIndex(a=>a.id===n);l!==-1&&(i[l]={...i[l],...r},s!==void 0&&this.contexts.set(this.contextKey(t,n),s))}_rawAgents(t){return this.getAgents(t)}_setSkills(t,n,r){const s=this.getAgents(t),i=s.findIndex(l=>l.id===n);i!==-1&&(s[i]={...s[i],skills:r})}async launchAgent(t,n,r,s){if(!this.getAgents(t).some(p=>p.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const l=this.liveByAgent.get(n);if(l!==void 0&&r.nodeId&&l!==r.nodeId)throw{code:"AGENT_ALREADY_RUNNING",message:`agent ${n} is already running in cell ${l}`};this.sessionSeq+=1;const a=`mock-agent-session-${this.sessionSeq}`,c=r.cwd;r.nodeId&&(this.liveByAgent.set(n,r.nodeId),this.liveSessionByAgent.set(n,a));const u=()=>{this.liveByAgent.get(n)===r.nodeId&&(this.liveByAgent.delete(n),this.liveSessionByAgent.delete(n))},h=new TextEncoder,d=new zh(a,s);this.sessions.set(a,d),queueMicrotask(()=>d.emit(h.encode(`agent ${n} @ ${c}\r -`)));const f=ec(d,()=>{this.sessions.delete(a),u()});return r.conversationId?f:{...f,assignedConversationId:`mock-conversation-${a}`}}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`agent session ${t} is not alive`};const s=r.reattach(n);return{handle:ec(r,()=>{this.sessions.delete(t);for(const[i,l]of this.liveSessionByAgent)l===t&&(this.liveSessionByAgent.delete(i),this.liveByAgent.delete(i))}),scrollback:s}}_setConversationDetails(t,n){this.conversationDetails.set(t,n)}async inspectConversation(t,n,r){return structuredClone(this.conversationDetails.get(r)??{})}}function ec(e,t){return{sessionId:e.sessionId,async write(n){if(e.closed)return;const r=[];for(const s of n)s===13?r.push(13,10):r.push(s);e.emit(Uint8Array.from(r))},async resize(){},detach(){e.detach()},async close(){e.closed=!0,t()}}}class t2{constructor(){X(this,"seq",0);X(this,"sessions",new Map)}async openTerminal(t,n){this.seq+=1;const r=`mock-session-${this.seq}`,s=new TextEncoder,i=new zh(r,n);return this.sessions.set(r,i),queueMicrotask(()=>i.emit(s.encode(`mock terminal @ ${t.cwd}\r -`))),ec(i,()=>this.sessions.delete(r))}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`terminal session ${t} is not alive`};const s=r.reattach(n);return{handle:ec(r,()=>this.sessions.delete(t)),scrollback:s}}async closeTerminal(t){const n=this.sessions.get(t);n&&(n.closed=!0,this.sessions.delete(t))}}class n2{constructor(){X(this,"projects",[]);X(this,"contexts",new Map)}async listProjects(){return[...this.projects]}async createProject(t,n){if(this.projects.some(s=>s.root===n))throw{code:"INVALID",message:`a project already exists at ${n} for this remote`};const r={id:`mock-project-${Math.random().toString(36).slice(2,10)}`,name:t,root:n,remote:{kind:"local"},createdAt:Date.now()};return this.projects.push(r),r}async openProject(t){const n=this.projects.find(r=>r.id===t);if(!n)throw{code:"NOT_FOUND",message:`project ${t} not found`};return n}async closeProject(){}async readProjectContext(t){if(!this.projects.some(n=>n.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};return this.contexts.get(t)??""}async updateProjectContext(t,n){if(!this.projects.some(r=>r.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};this.contexts.set(t,n)}}class r2{constructor(){X(this,"store",new Map)}getProjectLayouts(t){if(!this.store.has(t)){const n=`layout-default-${Math.random().toString(36).slice(2,8)}`;this.store.set(t,{activeId:n,layouts:[{id:n,name:"Default",kind:"terminal",tree:Do()}]})}return this.store.get(t)}getActiveTree(t){const n=this.getProjectLayouts(t),r=n.layouts.find(s=>s.id===n.activeId);return r?r.tree:Do()}getTree(t,n){if(!n)return this.getActiveTree(t);const s=this.getProjectLayouts(t).layouts.find(i=>i.id===n);return s?s.tree:Do()}setTree(t,n,r){const s=this.getProjectLayouts(t),i=r??s.activeId,l=s.layouts.find(a=>a.id===i);l&&(l.tree=n)}async loadLayout(t,n){const r=this.getTree(t,n);return structuredClone(r)}async mutateLayout(t,n,r){const s=this.getTree(t,r),i=GE(s,n);return this.setTree(t,i,r),structuredClone(i)}async listLayouts(t){const n=this.getProjectLayouts(t);return{layouts:n.layouts.map(s=>({id:s.id,name:s.name,kind:s.kind})),activeId:n.activeId}}async createLayout(t,n,r="terminal"){const s=this.getProjectLayouts(t),i=`layout-${Math.random().toString(36).slice(2,10)}`;return s.layouts.push({id:i,name:n,kind:r,tree:Do()}),{layoutId:i}}async renameLayout(t,n,r){const i=this.getProjectLayouts(t).layouts.find(l=>l.id===n);i&&(i.name=r)}async deleteLayout(t,n){const r=this.getProjectLayouts(t),s=r.layouts.findIndex(i=>i.id===n);return s!==-1&&r.layouts.splice(s,1),r.activeId===n&&r.layouts.length>0&&(r.activeId=r.layouts[0].id),{activeId:r.activeId}}async setActiveLayout(t,n){const r=this.getProjectLayouts(t);return r.layouts.some(s=>s.id===n)&&(r.activeId=n),{activeId:r.activeId}}}const s2=[{hash:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",summary:"Merge feature into main",parents:["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","dddddddddddddddddddddddddddddddddddddddd"],refs:["main","HEAD"],author:"Alice",timestamp:17172e5},{hash:"dddddddddddddddddddddddddddddddddddddddd",summary:"Implement feature (step 2)",parents:["cccccccccccccccccccccccccccccccccccccccc"],refs:["feature"],author:"Bob",timestamp:17171e5},{hash:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",summary:"Hotfix on main",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Alice",timestamp:171709e4},{hash:"cccccccccccccccccccccccccccccccccccccccc",summary:"Implement feature (step 1)",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Bob",timestamp:171708e4},{hash:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",summary:"Initial commit",parents:[],refs:["tag: v1.0"],author:"Alice",timestamp:1717e6}];class i2{constructor(){X(this,"projects",new Map)}getState(t){return this.projects.has(t)||this.projects.set(t,this._seedState()),this.projects.get(t)}_seedState(){const t=new Map;return t.set("src/main.rs",!1),t.set("README.md",!1),{files:t,branches:["main"],current:"main",log:[],commitSeq:0}}async init(t){this.projects.has(t)||this.projects.set(t,this._seedState())}async status(t){const n=this.getState(t);return Array.from(n.files.entries()).map(([r,s])=>({path:r,staged:s}))}async stage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!0)}async unstage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!1)}async commit(t,n){const r=this.getState(t);r.commitSeq+=1;const s={hash:`mock-${r.commitSeq}`,summary:n.split(` -`)[0]};for(const[i,l]of Array.from(r.files.entries()))l&&r.files.delete(i);return r.log.unshift(s),s}async branches(t){const n=this.getState(t);return{branches:[...n.branches],current:n.current}}async checkout(t,n){const r=this.getState(t);r.branches.includes(n)||r.branches.push(n),r.current=n}async log(t,n){return this.getState(t).log.slice(0,n)}async graph(t,n){return s2.slice(0,n)}}class l2{async connect(){}}class o2{constructor(){X(this,"open",new Set);X(this,"listeners",new Set)}async openViewWindow(t){this.open.add(t)}async closeViewWindow(t){this.open.delete(t)&&this.emit({panel:t})}async listOpenViewWindows(){return[...this.open].map(t=>({panel:t,label:t,visible:!0}))}async onViewWindowClosed(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}simulateOsClose(t){this.open.delete(t),this.emit({panel:t})}emit(t){for(const n of this.listeners)n(t)}}class a2{constructor(){X(this,"focused",null);X(this,"listeners",new Set)}async setFocusedProject(t){this.focused=t;for(const n of this.listeners)n(t)}async getFocusedProject(){return this.focused}async onFocusedProjectChanged(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}}const ku=[{id:"mock-claude",name:"Claude Code",command:"claude",args:[],contextInjection:{strategy:"conventionFile",target:"CLAUDE.md"},detect:"claude --version",cwdTemplate:"{projectRoot}",structuredAdapter:"claude"},{id:"mock-codex",name:"OpenAI Codex CLI",command:"codex",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"codex --version",cwdTemplate:"{projectRoot}",structuredAdapter:"codex"},{id:"mock-opencode",name:"OpenCode + llama.cpp",command:"opencode",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"opencode --version",cwdTemplate:"{projectRoot}",structuredAdapter:"openCode",opencode:{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}],c2=[{providerId:"anthropic",displayName:"Anthropic",models:["claude-sonnet-5","claude-opus-4-8","claude-haiku-4-5"]},{providerId:"openrouter",displayName:"OpenRouter",models:["openrouter/auto","qwen/qwen3-coder"]}],u2=[{providerId:"openai",displayName:"OpenAI",models:["gpt-5","gpt-5-mini","gpt-5-codex","o3"],customSupported:!0}],d2=[{providerId:"anthropic",displayName:"Anthropic",models:["claude-sonnet-4-5","claude-opus-4-1","claude-haiku-3-5"]}];class h2{constructor(){X(this,"profiles",[]);X(this,"configured",!1);X(this,"cloneCounter",0)}async firstRunState(){return{isFirstRun:!this.configured,referenceProfiles:structuredClone(ku)}}async referenceProfiles(){return structuredClone(ku)}async detectProfiles(t){return t.map(n=>({profile:n,available:n.command==="claude"}))}async listProfiles(){return structuredClone(this.profiles)}async saveProfile(t){const n=this.profiles.findIndex(r=>r.id===t.id);return n>=0?this.profiles[n]=t:this.profiles.push(t),this.configured=!0,structuredClone(t)}async deleteProfile(t){this.profiles=this.profiles.filter(n=>n.id!==t)}async configureProfiles(t){return this.profiles=structuredClone(t),this.configured=!0,structuredClone(t)}async cloneOpenCodeProfileFromSeed(t={}){const n=ku.find(r=>r.structuredAdapter==="openCode");if(!n)throw new Error("no OpenCode seed profile");return this.cloneCounter+=1,structuredClone({...n,id:`mock-opencode-clone-${this.cloneCounter}`,name:t.name??`${n.name} (copy ${this.cloneCounter})`,opencode:t.opencode??n.opencode})}async listOpenCodeProviders(){return structuredClone(c2)}async saveOpenCodeProviderProfile(t){const n={...structuredClone(t.profile),opencode:void 0,opencodeProvider:{providerId:t.providerId,model:t.model,apiKeyRef:`mock-secret-${t.profile.id}`,custom:t.custom}},r=this.profiles.findIndex(s=>s.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}async listCodexProviders(){return structuredClone(u2)}async saveCodexProviderProfile(t){const n={...structuredClone(t.profile),codexProvider:{providerId:t.providerId,model:t.model,apiKeyRef:t.profile.codexProvider?.apiKeyRef??`mock-secret-${t.profile.id}`,custom:t.custom}},r=this.profiles.findIndex(s=>s.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}async listClaudeProviders(){return structuredClone(d2)}async saveClaudeProviderProfile(t){const n={...structuredClone(t.profile),claudeProvider:{providerId:t.providerId,model:t.model,apiKeyRef:t.profile.claudeProvider?.apiKeyRef??`mock-secret-${t.profile.id}`}},r=this.profiles.findIndex(s=>s.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}}class f2{constructor(){X(this,"servers",[]);X(this,"inUse",new Set)}async listModelServers(){return structuredClone(this.servers)}async saveModelServer(t){const n=this.servers.findIndex(r=>r.id===t.id);return n>=0?this.servers[n]=structuredClone(t):this.servers.push(structuredClone(t)),structuredClone(t)}async deleteModelServer(t){if(this.inUse.has(t))throw{code:"model_server_in_use",message:"A profile still references this server."};this.servers=this.servers.filter(n=>n.id!==t)}async previewModelServerCommand(t){if(!t.modelSource)throw{code:"INVALID",message:"model.source missing"};const n=t.binaryPath&&t.binaryPath.trim().length>0?t.binaryPath:"llama-server",r=[];t.modelSource.type==="localPath"?r.push("--model",t.modelSource.path):r.push("-hf",t.modelSource.repo),r.push("--port",String(t.port),"--host",t.host),t.gpuLayers!==void 0&&r.push("-ngl",String(t.gpuLayers)),t.contextSize!==void 0&&r.push("-c",String(t.contextSize)),t.jinja&&r.push("--jinja"),r.push(...t.args);const s=[n,...r].map(i=>/\s/.test(i)?`'${i}'`:i).join(" ");return{command:n,args:r,display:s}}markInUse(t){this.inUse.add(t)}}const p2={mode:"localOnly",autoStart:!1,port:17373,trustedProxies:[]},m2=["192.168.1.42","10.0.0.17"];function Ms(e){throw{code:"INVALID",message:e}}class g2{constructor(){X(this,"settings",structuredClone(p2));X(this,"current",{state:"stopped"});X(this,"handlers",new Set)}async getExposureSettings(){return structuredClone(this.settings)}async saveExposureSettings(t){this.validate(t),this.settings=structuredClone(t)}async previewExposure(t){this.validate(t);const n=[];t.mode==="remoteProxyOtherMachine"&&t.trustedProxies.length===0&&n.push({code:"missingTrustedProxy",message:"Add the IP address or CIDR of the reverse proxy that connects to this server."});const r=t.mode==="remoteProxyOtherMachine"?t.lanBindAddress:"127.0.0.1",s=t.mode!=="localOnly"&&r?`http://${r}:${t.port}`:void 0;return{candidateLanAddresses:[...m2],upstreamUrl:s,warnings:n}}async status(){return structuredClone(this.current)}async start(){this.validate(this.settings);const t=await this.previewExposure(this.settings);return this.emit({state:"running",localUrl:`http://127.0.0.1:${this.settings.port}`,publicUrl:this.settings.mode==="localOnly"?void 0:this.settings.publicOrigin,upstreamUrl:t.upstreamUrl}),structuredClone(this.current)}async stop(){return this.emit({state:"stopped"}),structuredClone(this.current)}async onStatusChanged(t){return this.handlers.add(t),()=>this.handlers.delete(t)}setStatus(t){this.emit(t)}emit(t){this.current=t;for(const n of this.handlers)n(structuredClone(t))}validate(t){if(t.mode!=="localOnly"){const n=t.publicOrigin;n||Ms("remote exposure requires publicOrigin"),n.startsWith("https://")||Ms("remote exposure requires publicOrigin to start with https://"),n.includes("*")&&Ms("publicOrigin must be exact, not a wildcard"),n.endsWith("/")&&Ms("publicOrigin must not end with '/'")}t.mode==="remoteProxyOtherMachine"&&(t.lanBindAddress||Ms("remoteProxyOtherMachine requires lanBindAddress"),t.trustedProxies.length===0&&Ms("remoteProxyOtherMachine requires at least one trustedProxies entry"))}}class x2{constructor(t){X(this,"templates",[]);X(this,"seq",0);this.agentGateway=t}async listTemplates(){return structuredClone(this.templates)}async createTemplate(t){this.seq+=1;const n={id:`mock-template-${this.seq}`,name:t.name,contentMd:t.content,version:1,defaultProfileId:t.defaultProfileId};return this.templates.push(n),structuredClone(n)}async updateTemplate(t,n){const r=this.templates.findIndex(s=>s.id===t);if(r===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};return this.templates[r]={...this.templates[r],contentMd:n,version:this.templates[r].version+1},structuredClone(this.templates[r])}async deleteTemplate(t){const n=this.templates.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};this.templates.splice(n,1)}async createAgentFromTemplate(t,n,r){const s=this.templates.find(f=>f.id===n);if(!s)throw{code:"NOT_FOUND",message:`template ${n} not found`};const i=r?.synchronized??!0,l=r?.name??s.name,a=hp(l)||"agent",c=new Set(this.agentGateway._rawAgents(t).map(f=>f.contextPath));let u=`agents/${a}.md`,h=2;for(;c.has(u);)u=`agents/${a}-${h}.md`,h+=1;const d={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:l,contextPath:u,profileId:s.defaultProfileId,origin:{type:"fromTemplate",templateId:n,syncedTemplateVersion:s.version},synchronized:i,skills:[]};return this.agentGateway._insertAgent(t,d,s.contentMd),structuredClone(d)}async detectDrift(t){const n=this.agentGateway._rawAgents(t),r=[];for(const s of n){if(!s.synchronized||s.origin.type!=="fromTemplate")continue;const{templateId:i,syncedTemplateVersion:l}=s.origin,a=this.templates.find(c=>c.id===i);a&&a.version>l&&r.push({agentId:s.id,from:l,to:a.version})}return r}async syncAgent(t,n){const s=this.agentGateway._rawAgents(t).find(a=>a.id===n);if(!s||!s.synchronized||s.origin.type!=="fromTemplate")return{synced:!1,version:null};const{templateId:i}=s.origin,l=this.templates.find(a=>a.id===i);return l?(this.agentGateway._updateAgent(t,n,{origin:{type:"fromTemplate",templateId:i,syncedTemplateVersion:l.version}},l.contentMd),{synced:!0,version:l.version}):{synced:!1,version:null}}}class v2{constructor(t){X(this,"global",[]);X(this,"byProject",new Map);X(this,"seq",0);this.agentGateway=t}bucket(t,n){if(n==="global")return this.global;let r=this.byProject.get(t);return r||(r=[],this.byProject.set(t,r)),r}async listSkills(t,n){return structuredClone(this.bucket(t,n))}async createSkill(t){this.seq+=1;const n={id:`mock-skill-${this.seq}`,name:t.name,contentMd:t.content,scope:t.scope};return this.bucket(t.projectId,t.scope).push(n),structuredClone(n)}async updateSkill(t,n,r,s){const i=this.bucket(t,n),l=i.findIndex(a=>a.id===r);if(l===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};return i[l]={...i[l],contentMd:s},structuredClone(i[l])}async deleteSkill(t,n,r){const s=this.bucket(t,n),i=s.findIndex(l=>l.id===r);if(i===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};s.splice(i,1)}async assignSkill(t,n,r,s){const i=this.agentGateway._rawAgents(t).find(l=>l.id===n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};i.skills.some(l=>l.skillId===r)||this.agentGateway._setSkills(t,n,[...i.skills,{skillId:r,scope:s}])}async unassignSkill(t,n,r){const s=this.agentGateway._rawAgents(t).find(i=>i.id===n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.agentGateway._setSkills(t,n,s.skills.filter(i=>i.skillId!==r))}}class y2{constructor(){X(this,"byProject",new Map)}bucket(t){let n=this.byProject.get(t);return n||(n=new Map,this.byProject.set(t,n)),n}notFound(t,n){return{code:"NOT_FOUND",message:`memory ${t} not found in project ${n}`}}async listMemories(t){return structuredClone([...this.bucket(t).values()])}async getMemory(t,n){const r=this.bucket(t).get(n);if(!r)throw this.notFound(n,t);return structuredClone(r)}async createMemory(t){const n={name:t.name,description:t.description,type:t.type,content:t.content};return this.bucket(t.projectId).set(hp(t.name),n),structuredClone(n)}async updateMemory(t,n,r,s,i){const l=this.bucket(t),a=l.get(n);if(!a)throw this.notFound(n,t);const c={...a,description:r,type:s,content:i};return l.set(n,c),structuredClone(c)}async deleteMemory(t,n){if(!this.bucket(t).delete(n))throw this.notFound(n,t)}async readIndex(t){return[...this.bucket(t).entries()].map(([n,r])=>({slug:n,title:r.name,hook:r.description,type:r.type}))}async resolveLinks(t,n){const r=this.bucket(t),s=r.get(n);if(!s)throw this.notFound(n,t);const i=new Set;for(const l of s.content.matchAll(/\[\[([^\]]+)\]\]/g)){const a=l[1].trim();a!==n&&r.has(a)&&i.add(a)}return[...i]}async recall(t,n,r){const s=await this.readIndex(t),i=Math.max(0,Math.floor(r/16));return s.slice(0,i)}}class _2{constructor(t,n=[]){X(this,"profiles",new Map);X(this,"engines");this.engines={recommendedOnnx:[{id:"e5-small",displayName:"E5 Small (multilingual)",dimension:384,approxSizeMb:120,recommended:!0},{id:"bge-small",displayName:"BGE Small",dimension:384,approxSizeMb:130,recommended:!1}],ollamaDetected:!1,onnxCachedModels:[],vectorHttpEnabled:!0,vectorOnnxEnabled:!0,...t};for(const r of n)this.profiles.set(r.id,r)}async listEmbedderProfiles(){return structuredClone([...this.profiles.values()])}async saveEmbedderProfile(t){if(!t.id.trim()||!t.name.trim())throw{code:"INVALID",message:"embedder profile id/name must not be empty"};if(t.dimension<=0)throw{code:"INVALID",message:"embedder profile dimension must be > 0"};return this.profiles.set(t.id,structuredClone(t)),structuredClone(t)}async deleteEmbedderProfile(t){this.profiles.delete(t)}async describeEmbedderEngines(){return structuredClone(this.engines)}}class b2{constructor(){X(this,"interrupts",[]);X(this,"delivered",[]);X(this,"frontAttached",[]);X(this,"cancelledResumes",[]);X(this,"resumeArmings",[]);X(this,"cancelResumeResult",!0)}async interrupt(t,n){this.interrupts.push({projectId:t,agentId:n})}async delegationDelivered(t,n,r){this.delivered.push({projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){this.frontAttached.push({agentId:t,attached:n})}async cancelResume(t){return this.cancelledResumes.push(t),this.cancelResumeResult}async setResumeAt(t,n){this.resumeArmings.push({agentId:t,resetsAtMs:n})}}class w2{constructor(){X(this,"devices",[]);X(this,"issued",0);X(this,"_issuedCodes",[])}_setDevices(t){this.devices=structuredClone(t)}async listDevices(){return structuredClone(this.devices)}async createPairingCode(){const t=(268435456+this.issued++).toString(16).toUpperCase().slice(0,8);this._issuedCodes.push(t);const n=600;return{code:t,expiresAtMs:Date.now()+n*1e3,ttlSeconds:n}}async renameDevice(t,n){const r=this.devices.find(s=>s.deviceId===t);if(!r)throw{code:"NOT_FOUND",message:`unknown device ${t}`};r.name=n}async revokeDevice(t){this.devices=this.devices.filter(n=>n.deviceId!==t)}async revokeAllDevices(){this.devices=[]}}class S2{constructor(){X(this,"docs",new Map);X(this,"systemDocs",new Map);X(this,"systemRuntime",new Map);X(this,"mcpCatalogue",{readOnlyTools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read","idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"],writeActionTools:["idea_ask_agent","idea_run_in_background","idea_launch_agent","idea_stop_agent","idea_update_context","idea_context_propose","idea_memory_write","idea_workstate_set","idea_create_skill","idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]});X(this,"mcpDocs",new Map)}doc(t){return this.docs.has(t)||this.docs.set(t,{version:1,agents:[]}),this.docs.get(t)}async getProjectPermissions(t){return structuredClone(this.doc(t))}async updateProjectPermissions(t,n){const r=this.doc(t);return n?r.projectDefaults=structuredClone(n):delete r.projectDefaults,structuredClone(r)}async updateAgentPermissions(t,n,r){const s=this.doc(t),i=(s.agents??[]).filter(l=>l.agentId!==n);return r&&i.push({agentId:n,permissions:structuredClone(r)}),s.agents=i,structuredClone(s)}async resolveAgentPermissions(t,n){const r=this.doc(t),s=r.projectDefaults,i=r.agents?.find(l=>l.agentId===n)?.permissions;return!s&&!i?null:{rules:[...s?.rules??[],...i?.rules??[]],fallback:E2(s?.fallback,i?.fallback)}}systemDoc(t){return this.systemDocs.has(t)||this.systemDocs.set(t,{version:1,agents:[]}),this.systemDocs.get(t)}async getProjectSystemPermissions(t){return structuredClone(this.systemDoc(t))}async updateProjectSystemPermissions(t,n){const r=this.systemDoc(t);return n&&Object.keys(n).length>0?r.projectDefault=structuredClone(n):delete r.projectDefault,structuredClone(r)}async updateAgentSystemPermissions(t,n,r){const s=this.systemDoc(t),i=(s.agents??[]).filter(l=>l.agentId!==n);return r&&Object.keys(r).length>0&&i.push({agentId:n,permissions:structuredClone(r)}),s.agents=i,structuredClone(s)}async resolveAgentSystemPermissions(t,n){const r=this.systemRuntime.get(n);if(r)return structuredClone(r);const s=this.systemDoc(t),i=s.agents?.find(l=>l.agentId===n)?.permissions.network??s.projectDefault?.network??null;return{wanted:i,effective:i??"ask",runtimeLock:{state:"none"},control:{mode:"editable"},runtimeControl:{mode:"readOnly",reason:"No active runtime network permission state is currently observed."}}}setResolvedAgentSystemPermissions(t,n){this.systemRuntime.set(t,structuredClone(n))}mcpDoc(t){return this.mcpDocs.has(t)||this.mcpDocs.set(t,{version:1,catalogue:this.mcpCatalogue,projectDefault:null,agents:[]}),this.mcpDocs.get(t)}async getMcpToolPermissions(t){return structuredClone(this.mcpDoc(t))}async updateProjectMcpToolPermissions(t,n){const r=this.mcpDoc(t);return r.projectDefault=n?structuredClone(n):null,structuredClone(r)}async updateAgentMcpToolPermissions(t,n,r){const s=this.mcpDoc(t);return s.agents=s.agents.filter(i=>i.agentId!==n),r&&s.agents.push({agentId:n,policy:structuredClone(r)}),structuredClone(s)}}class k2{constructor(){X(this,"states",new Map)}_setProjectWorkState(t,n){this.states.set(t,up(n))}async getProjectWorkState(t){return structuredClone(this.states.get(t)??{agents:[],conversations:[]})}async cancelBackgroundTask(t){}async retryBackgroundTask(t){}}class C2{constructor(){X(this,"threads",new Map)}key(t,n){return`${t}::${n}`}_setTurns(t,n,r){this.threads.set(this.key(t,n),r.map(s=>structuredClone(s)))}async readPage(t,n,r){const s=this.threads.get(this.key(t,n))??[],i=s.length,l=r?.limit,a=Math.min(Math.max(l&&l>0?l:50,1),200),c=r?.direction??"backward",u=r?.anchor;let h,d,f;if(u===void 0)c==="forward"?(h=0,d=Math.min(a,i),f=d0);else{const x=s.findIndex(w=>w.id===u);x===-1?(h=0,d=0,f=!1):c==="forward"?(h=x+1,d=Math.min(h+a,i),f=d0)}const p=s.slice(h,d).map(x=>structuredClone(x)),m=p.at(-1);return{turns:p,hasMore:f,...m?{nextAnchor:m.id}:{}}}}class j2{constructor(t){X(this,"tickets",new Map);X(this,"carnets",new Map);X(this,"counters",new Map);X(this,"sprints",new Map);X(this,"sprintCounters",new Map);X(this,"chatSessions",new Map);X(this,"chatCounter",0);this.system=t}_seedTicket(t,n){const r=structuredClone(n);return r.sprintId===void 0&&(r.sprintId=null),this.projectTickets(t).set(r.ref,r),this.counters.set(t,Math.max(this.counters.get(t)??0,r.number)),structuredClone(r)}_seedSprint(t,n){const r={status:"planned",ticketCount:0,version:1,...n};return this.projectSprints(t).set(r.id,r),structuredClone(r)}projectSprints(t){let n=this.sprints.get(t);return n||(n=new Map,this.sprints.set(t,n)),n}recountSprints(t){const n=this.projectSprints(t),r=new Map;for(const s of this.projectTickets(t).values())s.sprintId&&r.set(s.sprintId,(r.get(s.sprintId)??0)+1);for(const s of n.values())s.ticketCount=r.get(s.id)??0}projectTickets(t){let n=this.tickets.get(t);return n||(n=new Map,this.tickets.set(t,n)),n}projectCarnets(t){let n=this.carnets.get(t);return n||(n=new Map,this.carnets.set(t,n)),n}require(t,n){const r=this.projectTickets(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`ticket ${n} not found`};return r}guard(t,n){if(t.version!==n)throw{code:"INVALID",message:`issue version conflict: expected ${n}, actual ${t.version}`}}async create(t,n){const r=(this.counters.get(t)??0)+1;this.counters.set(t,r);const s=Date.now(),i={id:`mock-ticket-${t}-${r}`,ref:`#${r}`,number:r,title:n.title,description:n.description??"",status:n.status??"open",priority:n.priority??"medium",sprintId:null,links:[],assignedAgentIds:[...n.assignedAgentIds??[]],createdBy:{kind:"user"},updatedBy:{kind:"user"},createdAt:s,updatedAt:s,version:1};return this.projectTickets(t).set(i.ref,i),this.system?.emit({type:"issueCreated",issueId:i.id,issueRef:i.ref}),structuredClone(i)}async read(t,n,r=!1){const s=structuredClone(this.require(t,n));return r&&(s.carnet=this.projectCarnets(t).get(n)??""),s}async list(t,n){const r=n??{},s=r.text?.trim().toLowerCase(),i=r.statuses??[],l=r.priorities??[];let a=[...this.projectTickets(t).values()].filter(d=>i.length===0||i.includes(d.status)).filter(d=>l.length===0||l.includes(d.priority)).filter(d=>!r.assignedAgentId||d.assignedAgentIds.includes(r.assignedAgentId)).filter(d=>!s||d.title.toLowerCase().includes(s)||d.description.toLowerCase().includes(s));a=r.sort?JE(a,r.sort):a.sort((d,f)=>f.number-d.number);const c=Number.parseInt(r.cursor??"0",10)||0,u=Math.min(Math.max(r.limit??100,1),500),h=Math.min(a.length,c+u);return{items:a.slice(c,h).map(d=>({ref:d.ref,path:`.ideai/tickets/${d.number}.md`,title:d.title,status:d.status,priority:d.priority,sprintId:d.sprintId??null,assignedAgentIds:[...d.assignedAgentIds],updatedAt:d.updatedAt})),...hc.targetRef===r&&c.kind===s)||l.links.push({targetRef:r,kind:s}),this.bump(l),this.system?.emit({type:"issueLinked",issueRef:n,target:r,kind:s,version:l.version}),structuredClone(l)}async unlink(t,n,r,s,i){const l=this.require(t,n);return this.guard(l,s),l.links=l.links.filter(a=>a.targetRef!==r||i!==void 0&&a.kind!==i),this.bump(l),this.system?.emit({type:"issueUnlinked",issueRef:n,target:r,kind:i??"relatesTo",version:l.version}),structuredClone(l)}async assign(t,n,r,s,i){const l=this.require(t,n);this.guard(l,i);const a=l.assignedAgentIds.includes(r);return s&&!a&&l.assignedAgentIds.push(r),!s&&a&&(l.assignedAgentIds=l.assignedAgentIds.filter(c=>c!==r)),this.bump(l),this.system?.emit({type:s?"issueAgentAssigned":"issueAgentUnassigned",issueRef:n,agentId:r,version:l.version}),structuredClone(l)}async listSprints(t){return this.recountSprints(t),[...this.projectSprints(t).values()].sort((n,r)=>n.order-r.order).map(n=>structuredClone(n))}async setTicketSprint(t,n,r,s){const i=this.require(t,n);if(this.guard(i,s),r!==null&&!this.projectSprints(t).has(r))throw{code:"NOT_FOUND",message:`sprint ${r} not found`};const l=i.sprintId??null;return i.sprintId=r,this.bump(i),this.recountSprints(t),this.system?.emit({type:"issueSprintChanged",issueRef:n,from:l,to:r,version:i.version}),structuredClone(i)}async createSprint(t,n){const r=this.projectSprints(t),s=(this.sprintCounters.get(t)??0)+1;this.sprintCounters.set(t,s);const i=r.size===0?1:Math.max(...[...r.values()].map(a=>a.order))+1,l={id:`mock-sprint-${t}-${s}`,order:i,name:n,status:"planned",ticketCount:0,version:1};return r.set(l.id,l),this.system?.emit({type:"sprintCreated",sprintId:l.id,order:l.order}),structuredClone(l)}async renameSprint(t,n,r,s){const i=this.requireSprint(t,n);return this.guardSprint(i,s),i.name=r,i.version+=1,this.system?.emit({type:"sprintRenamed",sprintId:n,name:r,version:i.version}),structuredClone(i)}async reorderSprints(t,n){const r=this.projectSprints(t);for(const i of n)this.requireSprint(t,i);const s=[...r.values()].filter(i=>!n.includes(i.id)).sort((i,l)=>i.order-l.order).map(i=>i.id);return[...n,...s].forEach((i,l)=>{const a=r.get(i);a&&(a.order=l+1,this.system?.emit({type:"sprintReordered",sprintId:i,order:a.order,version:a.version}))}),this.listSprints(t)}async deleteSprint(t,n){this.requireSprint(t,n);for(const r of this.projectTickets(t).values())r.sprintId===n&&(r.sprintId=null,this.bump(r),this.system?.emit({type:"issueSprintChanged",issueRef:r.ref,from:n,to:null,version:r.version}));this.projectSprints(t).delete(n),this.system?.emit({type:"sprintDeleted",sprintId:n})}async openTicketChat(t,n,r){this.require(t,n);const s=`mock-ticket-chat-${++this.chatCounter}`;return this.chatSessions.set(n,s),this.system?.emit({type:"ticketAssistantOpened",issueRef:n,profileId:r}),{sessionId:s,requester:"ticket-assistant",issueRef:n}}async closeTicketChat(t,n){this.chatSessions.delete(n)&&this.system?.emit({type:"ticketAssistantClosed",issueRef:n})}async sendTicketChat(t,n,r){if(![...this.chatSessions.values()].includes(t))throw{code:"NOT_FOUND",message:`chat session ${t} not found`};const s=`Assistant: reçu « ${n} ».`,i=[{kind:"textDelta",text:"Assistant: reçu "},{kind:"textDelta",text:`« ${n} ».`},{kind:"final",content:s}];for(const l of i)await Promise.resolve(),r(l)}requireSprint(t,n){const r=this.projectSprints(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`sprint ${n} not found`};return r}guardSprint(t,n){if(t.version!==n)throw{code:"INVALID",message:`sprint version conflict: expected ${n}, actual ${t.version}`}}}class N2{constructor(){X(this,"store",new Map)}read(t){const n=this.store.get(t);if(n===void 0)return null;try{return JSON.parse(n)}catch{return this.store.delete(t),null}}write(t,n){try{this.store.set(t,JSON.stringify(n))}catch{}}remove(t){this.store.delete(t)}}function E2(e,t){const n={allow:0,ask:1,deny:2},r=e??t??"ask";return t&&n[t]>=n[r]?t:r}class P2{constructor(){X(this,"plugins",[]);X(this,"seq",0)}summaryFor(t){return{topLevelMenus:0,menuItems:0,layouts:0,mcpServers:0}}_seedPlugin(t){this.plugins.push(t)}async listPlugins(){return structuredClone(this.plugins)}async reviewPackage(t){this.seq+=1;const n=t.path.split("/").pop()??t.path;return{id:`mock.plugin.${this.seq}`,displayName:n.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",description:`Reviewed from ${t.sourceKind}: ${t.path}`,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`),issues:[],installable:!0}}async install(t,n){this.seq+=1;const r=n.split("/").pop()??n,s={id:`mock.plugin.${this.seq}`,displayName:r.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",sourceKind:t,sourceLabel:n,lifecycleState:"enabled",enabled:!0,pendingUninstall:!1,restartRequired:!0,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`)};return this.plugins.push(s),{plugin:structuredClone(s),restartRequired:!0}}installFromArchive(t){return this.install("archive",t)}installFromDirectory(t){return this.install("directory",t)}async setEnabled(t,n){const r=this.plugins.find(i=>i.id===t);if(!r)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};const s=n?"enabled":"disabled";return r.enabled=n,r.lifecycleState=s,r.restartRequired=!0,structuredClone(r)}async uninstall(t){const n=this.plugins.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};return this.plugins.splice(n,1),{pluginId:t,restartRequired:!0}}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){}}function A2(){const e=new e2,t=new ZE;return{system:t,agent:e,input:new b2,terminal:new t2,project:new n2,layout:new r2,git:new i2,remote:new l2,profile:new h2,modelServer:new f2,desktopServer:new g2,template:new x2(e),skill:new v2(e),memory:new y2,embedder:new _2,device:new w2,permission:new S2,workState:new k2,conversation:new C2,ticket:new j2(t),window:new o2,focusedProject:new a2,uiPreferences:new N2,plugin:new P2}}function aw(){const e=globalThis.fetch;return typeof e=="function"?e.bind(globalThis):e}function T2(e,t){if(e&&typeof e=="object"){const n=e,r=typeof n.code=="string"?n.code:void 0,s=typeof n.message=="string"?n.message:void 0;if(r||s)return{code:r??"ERROR",message:s??t}}return{code:"TRANSPORT_ERROR",message:t}}class L2{constructor(t){X(this,"baseUrl");X(this,"token");X(this,"fetchImpl");X(this,"onUnauthorized");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.onUnauthorized=t.onUnauthorized,this.fetchImpl=t.fetchImpl??aw()}invoke(t,n={}){return this.request("POST","/api/invoke",{command:t,args:n},`command '${t}'`)}async request(t,n,r,s=`${t} ${n}`){const i={"Content-Type":"application/json"};this.token&&(i.Authorization=`Bearer ${this.token}`);let l;try{l=await this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:i,body:r===void 0?void 0:JSON.stringify(r),credentials:"same-origin"})}catch(c){throw{code:"TRANSPORT_ERROR",message:`HTTP request for ${s} failed: ${String(c)}`}}if(!l.ok){l.status===401&&this.onUnauthorized?.();let c;try{c=await l.json()}catch{c=void 0}throw T2(c,`${s} failed (HTTP ${l.status})`)}let a;try{a=await l.json()}catch{a=void 0}return a}}function D2(e){let t="";for(let n=0;ncw(i.bytesBase64)),n=t.reduce((i,l)=>i+l.length,0),r=new Uint8Array(n);let s=0;for(const i of t)r.set(i,s),s+=i.length;return r}class uw{constructor(t){X(this,"wsUrl");X(this,"token");X(this,"socketFactory");X(this,"reconnectBaseMs");X(this,"reconnectMaxMs");X(this,"setTimeoutImpl");X(this,"clearTimeoutImpl");X(this,"onReconnectFailed");X(this,"socket",null);X(this,"opening",null);X(this,"disposed",!1);X(this,"everConnected",!1);X(this,"connState","connecting");X(this,"reconnectAttempt",0);X(this,"reconnectHandle",null);X(this,"outputSinks",new Map);X(this,"terminals",new Map);X(this,"pending",new Map);X(this,"domainEventHandler",null);X(this,"connListeners",new Set);this.wsUrl=t.wsUrl.replace(/\/+$/,""),this.token=t.token,this.socketFactory=t.socketFactory??(n=>new WebSocket(n)),this.reconnectBaseMs=t.reconnectBaseMs??500,this.reconnectMaxMs=t.reconnectMaxMs??1e4,this.setTimeoutImpl=t.setTimeoutImpl??((n,r)=>setTimeout(n,r)),this.clearTimeoutImpl=t.clearTimeoutImpl??(n=>clearTimeout(n)),this.onReconnectFailed=t.onReconnectFailed}getConnectionState(){return this.connState}onConnectionStateChange(t){return this.connListeners.add(t),()=>this.connListeners.delete(t)}setConnState(t){if(this.connState!==t){this.connState=t;for(const n of this.connListeners)n(t)}}setDomainEventHandler(t){this.domainEventHandler=t}clearDomainEventHandler(){this.domainEventHandler=null}setOutputSink(t,n){this.outputSinks.set(t,n)}removeOutputSink(t){this.outputSinks.delete(t)}async ensureConnected(){if(!this.socket)return this.opening?this.opening:this.connect()}connect(){return this.setConnState(this.everConnected?"reconnecting":"connecting"),this.opening=new Promise((t,n)=>{const r=this.token?`${this.wsUrl}${ix}?token=${encodeURIComponent(this.token)}`:`${this.wsUrl}${ix}`,s=this.socketFactory(r);s.onopen=()=>{this.socket=s,this.opening=null,this.everConnected=!0,this.reconnectAttempt=0,this.setConnState("connected"),t()},s.onerror=i=>{this.opening=null,n(i)},s.onclose=()=>this.handleSocketClosed(),s.onmessage=i=>this.handleMessage(i.data)}),this.opening}handleSocketClosed(){if(this.socket=null,this.opening=null,this.rejectAllPending({code:"WS_CLOSED",message:"socket closed"}),this.disposed){this.setConnState("closed");return}if(this.setConnState("reconnecting"),this.terminals.size>0)for(const t of this.terminals.values())t.onData(Cu("déconnecté — reconnexion…"));this.needsReconnect()&&this.scheduleReconnect()}needsReconnect(){return this.terminals.size>0||this.domainEventHandler!==null}scheduleReconnect(){if(this.disposed||this.reconnectHandle)return;const t=Math.min(this.reconnectMaxMs,this.reconnectBaseMs*2**this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectHandle=this.setTimeoutImpl(()=>{this.reconnectHandle=null,this.reconnectNow()},t)}async reconnectNow(){if(!this.disposed)try{await this.connect(),await this.reattachAll()}catch{this.onReconnectFailed?.(),this.needsReconnect()&&this.scheduleReconnect()}}async reattachAll(){for(const[t,n]of this.terminals)try{const s=(await this.send("terminal.attach",{sessionId:t,lastSeq:n.lastSeq})).payload;n.onData(Cu("reconnecté"));const i=ax(s);i.length>0&&n.onData(i),typeof s.nextSeq=="number"&&(n.lastSeq=Math.max(0,s.nextSeq-1))}catch{}}openTerminal(t){return this.attachInternal("terminal.open",{cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}launchAgent(t){return this.attachInternal("agent.launch",{projectId:t.projectId,agentId:t.agentId,nodeId:t.nodeId??null,rows:t.rows,cols:t.cols,conversationId:t.conversationId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}attachTerminal(t){return this.attachInternal("terminal.attach",{sessionId:t.sessionId,rows:t.rows,cols:t.cols,lastSeq:t.lastSeq??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:t.lastSeq??0},t.sessionId)}async attachInternal(t,n,r,s){const l=(await this.send(t,n)).payload,a=s??l.session.sessionId;return typeof l.nextSeq=="number"&&(r.lastSeq=Math.max(0,l.nextSeq-1)),this.terminals.set(a,r),this.setOutputSink(a,r.onData),{sessionId:a,scrollback:ax(l),assignedConversationId:l.assignedConversationId,status:l.status}}async detachTerminal(t){this.removeTerminal(t),await this.sendFireAndForget("terminal.detach",{sessionId:t})}async closeTerminalSession(t){this.removeTerminal(t),await this.send("terminal.close",{sessionId:t})}removeTerminal(t){this.terminals.delete(t),this.outputSinks.delete(t)}async send(t,n){await this.ensureConnected();const r=this.socket;if(!r)throw{code:"WS_CLOSED",message:"socket not connected"};const s=ox(),i={id:s,kind:t,payload:n},l=new Promise((a,c)=>{this.pending.set(s,{resolve:a,reject:c})});return r.send(JSON.stringify(i)),l}async sendFireAndForget(t,n){await this.ensureConnected();const s={id:ox(),kind:t,payload:n};this.socket?.send(JSON.stringify(s))}static encodeInput(t){return D2(t)}disconnect(){this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disconnected"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null;const t=this.socket;t&&(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close()),this.socket=null,this.opening=null,this.everConnected=!1,this.reconnectAttempt=0,this.setConnState("closed")}dispose(){this.disposed=!0,this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disposed"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null,this.socket?.close(),this.socket=null,this.opening=null,this.setConnState("closed")}rejectAllPending(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}switch(n.kind){case"terminal.output":{const r=n.payload,s=this.terminals.get(r.sessionId);s&&typeof r.seq=="number"&&(s.lastSeq=r.seq);const i=this.outputSinks.get(r.sessionId);i&&i(cw(r.bytesBase64));return}case"terminal.status":{const r=n.payload;this.handleStatus(r);return}case"event.domain":{this.domainEventHandler?.(n.payload);return}}if(n.replyTo){const r=this.pending.get(n.replyTo);r&&(this.pending.delete(n.replyTo),n.kind==="error"?r.reject(n.payload):r.resolve(n))}}handleStatus(t){const n=this.terminals.get(t.sessionId);if(n)if(t.status==="exited"||t.status==="closed"){const r=t.exitCode;n.onData(Cu(r==null?"session terminée":`session terminée (code ${r})`)),n.onStatus?.(t.status,t.exitCode),this.removeTerminal(t.sessionId)}else n.onStatus?.(t.status,t.exitCode)}}const ju="idea.web.paired";function M2(){const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n),removeItem:t=>void e.delete(t)}}function I2(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return M2()}function O2(){return typeof window<"u"&&window.location?window.location.origin:"http://localhost"}const B2={invalidOrExpired:"Code invalide ou expiré.",invalidName:"Nom d'appareil invalide (1 à 40 caractères). Le code reste valable.",rateLimited:"Trop de tentatives. Réessayez dans quelques minutes avec un nouveau code.",pairingFailed:"Échec de l'appairage."};function z2(e,t){const n=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;let r;return n==="invalid_or_expired"?r="invalidOrExpired":n==="invalid_name"?r="invalidName":n==="rate_limited"||t===429?r="rateLimited":t===401||t===403?r="invalidOrExpired":r="pairingFailed",{code:r,message:B2[r]}}class F2{constructor(t={}){X(this,"baseUrl");X(this,"fetchImpl");X(this,"store");X(this,"unauthorizedHandlers",new Set);this.baseUrl=(t.baseUrl??O2()).replace(/\/+$/,""),this.fetchImpl=t.fetchImpl??aw(),this.store=t.store??I2()}isPaired(){return this.store.getItem(ju)==="1"}markPaired(){this.store.setItem(ju,"1")}forget(){this.store.removeItem(ju)}async logout(){try{await this.fetchImpl(`${this.baseUrl}/api/logout`,{method:"POST",credentials:"same-origin"})}catch{}finally{this.forget()}}async pair(t,n){let r;try{r=await this.fetchImpl(`${this.baseUrl}/api/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,name:n})})}catch(s){throw{code:"TRANSPORT_ERROR",message:`Impossible de joindre le serveur : ${String(s)}`}}if(!r.ok){let s;try{s=await r.json()}catch{s=void 0}throw z2(s,r.status)}this.markPaired()}notifyUnauthorized(){this.forget();for(const t of this.unauthorizedHandlers)t()}onUnauthorized(t){return this.unauthorizedHandlers.add(t),()=>this.unauthorizedHandlers.delete(t)}}let Nu=null;function dw(){return Nu||(Nu=new F2),Nu}let fp=null;function $2(e){fp=e}function Fh(){return fp}function cx(){fp?.disconnect()}class W2{constructor(t){this.http=t}async listDevices(){return(await this.http.request("GET","/api/devices")).devices}createPairingCode(){return this.http.request("POST","/api/pairing-code")}renameDevice(t,n){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/rename`,{name:n})}revokeDevice(t){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/revoke`)}revokeAllDevices(){return this.http.request("POST","/api/devices/revoke-all")}}class H2{constructor(t){this.http=t}listProjects(){return this.http.invoke("list_projects")}createProject(t,n){return this.http.invoke("create_project",{request:{name:t,root:n}})}openProject(t){return this.http.invoke("open_project",{projectId:t})}async closeProject(t){await this.http.invoke("close_project",{projectId:t})}readProjectContext(t){return this.http.invoke("read_project_context",{projectId:t})}async updateProjectContext(t,n){await this.http.invoke("update_project_context",{request:{projectId:t,content:n}})}}class U2{constructor(t){this.http=t}loadLayout(t,n){return this.http.invoke("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return this.http.invoke("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return this.http.invoke("list_layouts",{projectId:t})}createLayout(t,n,r){return this.http.invoke("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return this.http.invoke("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return this.http.invoke("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return this.http.invoke("set_active_layout",{request:{projectId:t,layoutId:n}})}}class q2{constructor(t){this.http=t}status(t){return this.http.invoke("git_status",{projectId:t})}async stage(t,n){await this.http.invoke("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await this.http.invoke("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return this.http.invoke("git_commit",{request:{projectId:t,message:n}})}branches(t){return this.http.invoke("git_branches",{projectId:t})}async checkout(t,n){await this.http.invoke("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return this.http.invoke("git_log",{projectId:t,limit:n})}async init(t){await this.http.invoke("git_init",{projectId:t})}graph(t,n){return this.http.invoke("git_graph",{projectId:t,limit:n})}}class K2{constructor(t){this.http=t}firstRunState(){return this.http.invoke("first_run_state")}referenceProfiles(){return this.http.invoke("reference_profiles")}detectProfiles(t){return this.http.invoke("detect_profiles",{request:{candidates:t}})}listProfiles(){return this.http.invoke("list_profiles")}saveProfile(t){return this.http.invoke("save_profile",{request:{profile:t}})}async deleteProfile(t){await this.http.invoke("delete_profile",{profileId:t})}configureProfiles(t){return this.http.invoke("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return this.http.invoke("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return this.http.invoke("list_opencode_providers")}saveOpenCodeProviderProfile(t){return this.http.invoke("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}listCodexProviders(){return this.http.invoke("list_codex_providers")}saveCodexProviderProfile(t){return this.http.invoke("save_codex_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}listClaudeProviders(){return this.http.invoke("list_claude_providers")}saveClaudeProviderProfile(t){return this.http.invoke("save_claude_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey}})}}class V2{constructor(t){this.http=t}listModelServers(){return this.http.invoke("list_model_servers")}saveModelServer(t){return this.http.invoke("save_model_server",{request:{config:t}})}async deleteModelServer(t){await this.http.invoke("delete_model_server",{serverId:t})}previewModelServerCommand(t){return this.http.invoke("preview_model_server_command",{config:t})}}class G2{constructor(t){this.http=t}listTemplates(){return this.http.invoke("list_templates")}createTemplate(t){return this.http.invoke("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return this.http.invoke("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await this.http.invoke("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return this.http.invoke("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return this.http.invoke("detect_agent_drift",{projectId:t})}syncAgent(t,n){return this.http.invoke("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class Y2{constructor(t){this.http=t}listSkills(t,n){return this.http.invoke("list_skills",{projectId:t,scope:n})}createSkill(t){return this.http.invoke("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,s){return this.http.invoke("update_skill",{request:{projectId:t,scope:n,skillId:r,content:s}})}async deleteSkill(t,n,r){await this.http.invoke("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,s){await this.http.invoke("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:s}})}async unassignSkill(t,n,r){await this.http.invoke("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class X2{constructor(t){this.http=t}listMemories(t){return this.http.invoke("list_memories",{projectId:t})}getMemory(t,n){return this.http.invoke("get_memory",{projectId:t,slug:n})}createMemory(t){return this.http.invoke("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,s,i){return this.http.invoke("update_memory",{request:{projectId:t,slug:n,description:r,type:s,content:i}})}async deleteMemory(t,n){await this.http.invoke("delete_memory",{projectId:t,slug:n})}readIndex(t){return this.http.invoke("read_memory_index",{projectId:t})}resolveLinks(t,n){return this.http.invoke("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return this.http.invoke("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class Q2{constructor(t){this.http=t}listEmbedderProfiles(){return this.http.invoke("list_embedder_profiles")}saveEmbedderProfile(t){return this.http.invoke("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await this.http.invoke("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return this.http.invoke("describe_embedder_engines")}}class J2{constructor(t){this.http=t}getProjectPermissions(t){return this.http.invoke("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return this.http.invoke("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return this.http.invoke("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return this.http.invoke("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getProjectSystemPermissions(t){return this.http.invoke("get_project_system_permissions",{projectId:t})}updateProjectSystemPermissions(t,n){return this.http.invoke("update_project_system_permissions",{request:{projectId:t,permissions:n}})}updateAgentSystemPermissions(t,n,r){return this.http.invoke("update_agent_system_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentSystemPermissions(t,n){return this.http.invoke("resolve_agent_system_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return this.http.invoke("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return this.http.invoke("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return this.http.invoke("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}class Z2{constructor(t){this.http=t}async getProjectWorkState(t){const n=await this.http.invoke("get_project_work_state",{projectId:t});return up(n)}async cancelBackgroundTask(t){await this.http.invoke("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await this.http.invoke("retry_background_task",{taskId:t})}}class eP{constructor(t){this.http=t}async readPage(t,n,r){const s=await this.http.invoke("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return lw(s)}}class tP{constructor(t){this.http=t}async interrupt(t,n){await this.http.invoke("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){await this.http.invoke("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}})}async setFrontAttached(t,n){await this.http.invoke("set_front_attached",{request:{agentId:t,attached:n}})}async cancelResume(t){return this.http.invoke("cancel_resume",{agentId:t})}async setResumeAt(t,n){await this.http.invoke("set_resume_at",{agentId:t,resetsAtMs:n})}}function at(e){throw{code:"UNSUPPORTED_ON_WEB",message:`${e} is not available in the web client (desktop-only).`}}class nP{openViewWindow(){return at("Detaching a panel into an OS window")}closeViewWindow(){return at("Closing a detached OS window")}listOpenViewWindows(){return Promise.resolve([])}onViewWindowClosed(t){return Promise.resolve(()=>{})}}class rP{setFocusedProject(t){return Promise.resolve()}getFocusedProject(){return Promise.resolve(null)}onFocusedProjectChanged(t){return Promise.resolve(()=>{})}}class sP{connect(){return at("Remote (SSH/WSL) connection")}}class iP{async getExposureSettings(){return at("Embedded server settings")}async saveExposureSettings(t){return at("Embedded server settings")}async previewExposure(t){return at("Embedded server settings")}async status(){return at("Embedded server status")}async start(){return at("Starting the embedded server")}async stop(){return at("Stopping the embedded server")}onStatusChanged(t){return Promise.resolve(()=>{})}}class lP{async listPlugins(){return at("Plugin management")}async reviewPackage(t){return at("Plugin management")}async installFromArchive(t){return at("Plugin management")}async installFromDirectory(t){return at("Plugin management")}async setEnabled(t,n){return at("Plugin management")}async uninstall(t){return at("Plugin management")}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){return at("Plugin management")}}function tc(e,t,n){return{sessionId:e,...n?{assignedConversationId:n}:{},async write(r){await t.sendFireAndForget("terminal.input",{sessionId:e,bytesBase64:uw.encodeInput(r)})},async resize(r,s){await t.sendFireAndForget("terminal.resize",{sessionId:e,rows:r,cols:s})},detach(){t.detachTerminal(e)},async close(){await t.closeTerminalSession(e)}}}class oP{constructor(t,n){this.http=t,this.ws=n}health(t){return this.http.invoke("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await this.ws.ensureConnected(),this.ws.setDomainEventHandler(t),()=>this.ws.clearDomainEventHandler()}pickFolder(){return at("Native folder picker")}pickArchiveFile(){return at("Native file picker")}onAppExitWorkGuard(t){return Promise.resolve(()=>{})}confirmAppExit(){return at("Confirming an app exit")}}class aP{constructor(t){this.ws=t}async openTerminal(t,n){const r=await this.ws.openTerminal({cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null,onData:n});return tc(r.sessionId,this.ws)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:tc(r.sessionId,this.ws),scrollback:r.scrollback}}async closeTerminal(t){await this.ws.closeTerminalSession(t)}}class cP{constructor(t,n){this.http=t,this.ws=n}listAgents(t){return this.http.invoke("list_agents",{projectId:t})}listLiveAgents(t){return this.http.invoke("list_live_agents",{projectId:t})}listResumableAgents(t){return this.http.invoke("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return this.http.invoke("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return this.http.invoke("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return this.http.invoke("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,s,i){return this.http.invoke("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:s,cols:i}})}readContext(t,n){return this.http.invoke("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await this.http.invoke("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await this.http.invoke("delete_agent",{projectId:t,agentId:n})}inspectConversation(t,n,r){return this.http.invoke("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}async launchAgent(t,n,r,s){const i=await this.ws.launchAgent({projectId:t,agentId:n,nodeId:r.nodeId??null,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,onData:s});return tc(i.sessionId,this.ws,i.assignedConversationId)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:tc(r.sessionId,this.ws),scrollback:r.scrollback}}}class uP{constructor(t,n){this.http=t,this.ws=n}create(t,n){return this.http.invoke("ticket_create",{request:{projectId:t,...n}})}read(t,n,r=!1){return this.http.invoke("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}list(t,n){const{statuses:r,priorities:s,...i}=n??{};return this.http.invoke("ticket_list",{request:{projectId:t,statuses:r??[],priorities:s??[],...i}})}update(t,n,r){return this.http.invoke("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await this.http.invoke("ticket_delete",{request:{projectId:t,ref:n}})}readCarnet(t,n){return this.http.invoke("ticket_read_carnet",{request:{projectId:t,ref:n}})}updateCarnet(t,n,r,s){return this.http.invoke("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:s}})}link(t,n,r,s,i){return this.http.invoke("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:s,expectedVersion:i}})}unlink(t,n,r,s,i){return this.http.invoke("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:s,kind:i}})}assign(t,n,r,s,i){return this.http.invoke("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:s,expectedVersion:i}})}async listSprints(t){return(await this.http.invoke("sprint_list",{request:{projectId:t}})).items}setTicketSprint(t,n,r,s){return r===null?this.http.invoke("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:s}}):this.http.invoke("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:s}})}createSprint(t,n){return this.http.invoke("sprint_create",{request:{projectId:t,name:n}})}renameSprint(t,n,r,s){return this.http.invoke("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:s}})}async reorderSprints(t,n){return(await this.http.invoke("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await this.http.invoke("sprint_delete",{request:{projectId:t,sprintId:n}})}openTicketChat(t,n,r){return this.http.invoke("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await this.http.invoke("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const i=(await this.ws.send("chat.send",{sessionId:t,prompt:n})).payload;i&&i.chunk&&r(i.chunk)}}function dP(e){const t=typeof window<"u"&&window.location?window.location.origin:"http://localhost",n=e.baseUrl??t,r=e.wsUrl??n.replace(/^http(s?):\/\//,(s,i)=>`ws${i}://`);return{baseUrl:n,wsUrl:r}}function hP(e={}){const{baseUrl:t,wsUrl:n}=dP(e),r=dw();let s;const i=new L2({baseUrl:t,token:e.token,onUnauthorized:()=>{r.notifyUnauthorized(),s?.disconnect()}});return s=new uw({wsUrl:n,token:e.token,onReconnectFailed:()=>{i.invoke("health",{request:null}).catch(()=>{})}}),$2(s),{system:new oP(i,s),agent:new cP(i,s),input:new tP(i),terminal:new aP(s),project:new H2(i),layout:new U2(i),git:new q2(i),remote:new sP,profile:new K2(i),modelServer:new V2(i),desktopServer:new iP,template:new G2(i),skill:new Y2(i),memory:new X2(i),embedder:new Q2(i),device:new W2(i),permission:new J2(i),workState:new Z2(i),conversation:new eP(i),ticket:new uP(i,s),window:new nP,focusedProject:new rP,uiPreferences:new ow,plugin:new lP}}function fP(e){return"http"}const hw=g.createContext(null);function fw(){return fP()}function pP(){switch(fw()){case"mock":return A2();case"http":return hP();case"tauri":return VE()}}function mP({children:e,gateways:t}){const n=g.useMemo(()=>t??pP(),[t]);return o.jsx(hw.Provider,{value:n,children:e})}function ue(){const e=g.useContext(hw);if(!e)throw new Error("useGateways must be used within a ");return e}function pp({cwd:e,open:t,reattach:n,sessionId:r,onSessionId:s,agentMode:i=!1,portal:l,onReady:a,refitSignal:c,systemPermissions:u}){const{terminal:h}=ue(),d=g.useRef(null),[f,p]=g.useState(null),m=g.useRef(t);m.current=t;const x=g.useRef(n);x.current=n;const w=g.useRef(r);w.current=r;const v=g.useRef(s);v.current=s;const y=g.useRef(h);y.current=h;const _=g.useRef(i);_.current=i;const b=g.useRef(l);b.current=l;const j=g.useRef(a);j.current=a;const S=g.useRef(null);g.useEffect(()=>{const A=d.current,k=y.current,R=m.current??k?.openTerminal.bind(k),T=x.current??k?.reattach.bind(k);if(!A||!R)return;p(null);const E=new JN({convertEol:!1,cursorBlink:!0,fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'}),O=new tE;E.loadAddon(O);try{E.open(A)}catch{E.dispose();return}try{O.fit()}catch{}let I=!1,W=null;const G=new TextEncoder;let P="";const z=E.onData($=>{const B=b.current;_.current&&B&&(B.onHumanData($),B.isSuspended())||(W?W.write(G.encode($)):P+=$)});j.current?.({send:$=>{I||E.input($)},focus:()=>{I||E.focus()}});const C=$=>{I||E.write($)},Q=$=>{if(I){$.detach();return}W=$,_.current&&b.current?.bindHandle($),P&&($.write(G.encode(P)),P="")},q=$=>{if(!I){if(gP($)==="AGENT_ALREADY_RUNNING"){E.write(`\r -\x1B[2mCellule disponible — l'agent est en cours dans une autre cellule.\x1B[0m\r -`);return}p(`Échec du lancement de l'agent : ${ux($)}`),E.write(`\r -\x1B[31mfailed to open terminal: ${ux($)}\x1B[0m\r -`)}},L=w.current;L&&T?T(L,C).then(({handle:$,scrollback:B})=>{if(I){$.detach();return}B.length>0&&E.write(B),Q($)}).catch(()=>{I||R({cwd:e,rows:E.rows,cols:E.cols},C).then($=>{v.current?.($.sessionId),Q($)}).catch(q)}):R({cwd:e,rows:E.rows,cols:E.cols},C).then($=>{v.current?.($.sessionId),Q($)}).catch(q);let se=0,te=E.rows,J=E.cols;const K=8;let Y=0;const ae=()=>{if(se=0,!I){if(A.clientWidth===0||A.clientHeight===0){Y{se&&cancelAnimationFrame(se),se=requestAnimationFrame(ae)},Pe=new ResizeObserver(pe);return Pe.observe(A),S.current=pe,()=>{I=!0,S.current=null,se&&cancelAnimationFrame(se),Pe.disconnect(),z.dispose(),b.current?.unbindHandle(),W&&W.detach(),E.dispose()}},[e]),g.useEffect(()=>{c!==void 0&&S.current?.()},[c]);const N=u!=null&&(u.runtimeLock.state==="locked"||u.effective==="deny"),D=u?.runtimeLock.reason??u?.control.reason??"Le réseau est interdit pour cette cellule.";return o.jsxs("div",{"data-testid":"terminal-view",style:{position:"relative",width:"100%",height:"100%",minHeight:"16rem"},children:[o.jsx("div",{ref:d,style:{width:"100%",height:"100%"}}),N&&o.jsxs("div",{role:"status","data-testid":"terminal-network-banner",style:{position:"absolute",top:8,left:8,right:8,padding:"0.5rem 0.75rem",border:"1px solid rgba(245, 158, 11, 0.45)",borderRadius:6,background:"rgba(24, 24, 27, 0.94)",color:"var(--color-warning, #f59e0b)",fontSize:12,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:2},children:[u.runtimeLock.state==="locked"?"Réseau verrouillé par le runtime.":"Réseau interdit pour cet agent."," ",D]}),f&&o.jsx("div",{role:"alert","data-testid":"terminal-error",style:{position:"absolute",top:0,left:0,right:0,padding:"0.5rem 0.75rem",background:"rgba(120, 20, 20, 0.92)",color:"#fff",fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:3},children:f})]})}function ux(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function gP(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function xP({agentWasRunning:e,details:t,onResume:n,onNewConversation:r}){const s=e?"en cours":"clot";return o.jsx("div",{"data-testid":"resume-conversation-popup",role:"dialog","aria-label":"Reprise de conversation",style:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)"},children:o.jsxs("div",{style:{minWidth:260,maxWidth:360,padding:"16px 18px",background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:6,boxShadow:"0 8px 24px rgba(0, 0, 0, 0.5)",fontSize:13},children:[o.jsx("p",{style:{margin:"0 0 8px",fontWeight:600},children:"Reprise de conversation"}),o.jsxs("p",{style:{margin:"0 0 6px"},children:["Statut :"," ",o.jsx("span",{"data-testid":"resume-status",children:s})]}),t?.lastTopic&&o.jsxs("p",{style:{margin:"0 0 6px"},"data-testid":"resume-last-topic",children:["Dernier sujet : ",t.lastTopic]}),t?.tokenCount!==void 0&&o.jsxs("p",{style:{margin:"0 0 10px"},"data-testid":"resume-token-count",children:["Tokens : ",t.tokenCount]}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[o.jsx("button",{type:"button",onClick:n,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Reprendre la dernière conversation"}),o.jsx("button",{type:"button",onClick:r,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Nouvelle conversation"})]})]})})}const Eu="\r",dx=350,vP=2e3,yP=512,_P=8,bP="[write-portal]",Pr=new TextEncoder;function wP(e){if(e.length===0)return!1;for(const t of e){const n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function SP(e,t){const{system:n,input:r}=ue(),[s,i]=g.useState(!1),l=g.useRef(0),a=g.useRef([]),c=g.useRef(null),u=g.useRef(!1),h=g.useRef(!1),d=g.useRef(null),f=g.useRef(null),p=g.useRef(r);p.current=r;const m=g.useRef(t);m.current=t;const x=g.useRef(e);x.current=e;const w=g.useRef(()=>{});w.current=()=>{const _=c.current&&d.current?d.current:null,b=f.current;b!==_&&(b&&(Ze("front-attached:set",{agent:b,attached:!1}),p.current?.setFrontAttached(b,!1).catch(j=>{Ze("front-attached:set-failed",{agent:b,attached:!1,error:Pu(j)})})),_&&(Ze("front-attached:set",{agent:_,attached:!0}),p.current?.setFrontAttached(_,!0).catch(j=>{Ze("front-attached:set-failed",{agent:_,attached:!0,error:Pu(j)})})),f.current=_)};const v=g.useRef(()=>{});return v.current=()=>{if(h.current)return;const _=a.current[0];if(!_||l.current>0)return;const b=c.current;if(!b)return;const j=m.current,S=x.current;if(!j)return;h.current=!0;const N=Date.now();u.current=!0,i(!0),(async()=>{let D=!1;try{Ze("inject:start",{agent:j,ticket:_.ticket,textBytes:Pr.encode(_.text).byteLength,queue:a.current.length,submitSequence:ma(_.submitSequence),submitDelayMs:_.submitDelayMs??dx}),await Promise.resolve();const A=l.current;A>0&&(Ze("inject:erase-human-window",{agent:j,ticket:_.ticket,count:A}),await b.write(Pr.encode("".repeat(A))),l.current=0),await kP(b,_.text,_.ticket);const k=_.submitDelayMs??dx;Ze("inject:before-submit-delay",{agent:j,ticket:_.ticket,delay:k}),await $h(k);const R=CP(_.submitSequence,_.ticket);Ze("inject:submit-write:start",{agent:j,ticket:_.ticket,submitSequence:ma(R),submitBytes:Pr.encode(R).byteLength}),await b.write(Pr.encode(R)),Ze("inject:submit-write:ok",{agent:j,ticket:_.ticket}),a.current.shift(),D=!0;try{Ze("inject:ack:start",{agent:j,ticket:_.ticket}),await p.current.delegationDelivered(S,j,_.ticket),Ze("inject:ack:ok",{agent:j,ticket:_.ticket})}catch{Ze("inject:ack:failed",{agent:j,ticket:_.ticket})}}catch(A){Ze("inject:failed",{agent:j,ticket:_.ticket,error:Pu(A)})}finally{const A=Date.now()-N,k=vP-A;k>0&&await $h(k),u.current=!1,i(!1),h.current=!1,a.current.length>0&&D&&v.current()}})()},g.useEffect(()=>{if(!n||!t){d.current=null,w.current();return}let _,b=!1;const j=t;return n.onDomainEvent(S=>{S.type==="delegationReady"&&S.agentId===j&&(a.current.push({ticket:S.ticket,text:S.text,submitSequence:S.submitSequence,submitDelayMs:S.submitDelayMs}),Ze("event:delegation-ready",{agent:j,ticket:S.ticket,textBytes:Pr.encode(S.text).byteLength,queue:a.current.length,submitSequence:ma(S.submitSequence),submitDelayMs:S.submitDelayMs}),v.current())}).then(S=>{b?S():(_=S,d.current=j,Ze("event:subscribed",{agent:j}),w.current())}),()=>{b=!0,_?.(),d.current===j&&(d.current=null,Ze("event:unsubscribed",{agent:j})),f.current===j?(p.current?.setFrontAttached(j,!1).catch(()=>{}),f.current=null):w.current()}},[n,t]),{portal:g.useMemo(()=>({onHumanData(_){if(_==="\r"||_===` -`||_===""){l.current=0,v.current();return}wP(_)&&(l.current+=1)},isSuspended(){return u.current},bindHandle(_){c.current=_,Ze("handle:bound",{agent:m.current,sessionId:_.sessionId}),w.current(),v.current()},unbindHandle(){Ze("handle:unbound",{agent:m.current,sessionId:c.current?.sessionId}),c.current=null,w.current()}}),[]),overlay:s}}function $h(e){return new Promise(t=>setTimeout(t,e))}async function kP(e,t,n){const r=jP(t,yP);for(let s=0;s0?e:(Ze("inject:empty-submit-sequence-defaulted",{ticket:t,defaultSubmitSequence:ma(Eu)}),Eu)}function jP(e,t){if(e.length===0)return[""];const n=[];let r="",s=0;for(const i of e){const l=Pr.encode(i).byteLength;r.length>0&&s+l>t&&(n.push(r),r="",s=0),r+=i,s+=l}return r.length>0&&n.push(r),n}function ma(e){return e==null?"":e.length===0?"":[...e].map(t=>{switch(t){case"\r":return"\\r";case` -`:return"\\n";case"":return"\\x7f";default:{const n=t.codePointAt(0);return n<32?`\\x${n.toString(16).padStart(2,"0")}`:t}}}).join("")}function Pu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Ze(e,t){console.info(bP,e,t)}function NP(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function eo(e){const{workState:t,system:n}=ue(),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{s(await t.getProjectWorkState(e))}catch(h){l(NP(h))}finally{c(!1)}},[e,t]);return g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let h,d=!1;return n.onDomainEvent(f=>{(f.type==="agentLaunched"||f.type==="agentExited"||f.type==="agentBusyChanged"||f.type==="delegationReady"||f.type==="orchestratorRequestProcessed"||f.type==="backgroundTaskChanged"||f.type==="agentInboxChanged"||f.type==="agentWakeChanged")&&u()}).then(f=>{d?f():h=f}),()=>{d=!0,h?.()}},[u,n]),{state:r,error:i,busy:a,refresh:u}}const EP=50;function pw(){return{byTarget:{},nextSeq:1}}function PP(e,t,n=EP){const{target:r,ticketId:s}=t,i={...t,seq:e.nextSeq},l=e.byTarget[r]??{},c=[...l[s]??[],i],u=c.length>n?c.slice(c.length-n):c;return{byTarget:{...e.byTarget,[r]:{...l,[s]:u}},nextSeq:e.nextSeq+1}}function AP(e,t){if(!(t in e.byTarget))return e;const{[t]:n,...r}=e.byTarget;return{byTarget:r,nextSeq:e.nextSeq}}function mw(e,t){return e.atMs-t.atMs||e.seq-t.seq}function TP(e,t){const n=e.byTarget[t];return n?Object.values(n).flat().sort(mw):[]}function LP(e,t,n){const r=[];for(const s of Object.values(e.byTarget))for(const[i,l]of Object.entries(s))if(!(n!==void 0&&i!==n))for(const a of l)a.requester===t&&r.push(a);return r.sort(mw)}const DP=()=>{},RP=pw(),MP={},IP={index:RP,busy:MP,seedBusy:DP},mp=g.createContext(null);function OP({children:e}){const{system:t}=ue(),[n,r]=g.useState(pw),[s,i]=g.useState({}),l=g.useCallback((c,u)=>{i(h=>c in h?h:{...h,[c]:u})},[]);g.useEffect(()=>{if(!t)return;let c,u=!1;return t.onDomainEvent(h=>{if(h.type==="agentAnnouncement")r(d=>PP(d,{requester:h.requester,target:h.target,ticketId:h.ticketId,text:h.text,atMs:h.atMs}));else if(h.type==="agentBusyChanged"){const{agentId:d,busy:f}=h;i(p=>({...p,[d]:f})),f||r(p=>AP(p,d))}}).then(h=>{u?h():c=h}).catch(()=>{}),()=>{u=!0,c?.()}},[t]);const a=g.useMemo(()=>({index:n,busy:s,seedBusy:l}),[n,s,l]);return o.jsx(mp.Provider,{value:a,children:e})}function gp(){return g.useContext(mp)??IP}function BP(){return g.useContext(mp)!==null}function gw(e){const{index:t,busy:n}=gp();return g.useMemo(()=>({announcements:TP(t,e),active:n[e]===!0}),[t,n,e])}function zP(e,t){const{workState:n}=ue(),{seedBusy:r}=gp(),s=BP();g.useEffect(()=>{if(!s||!n)return;let i=!1;return n.getProjectWorkState(e).then(l=>{if(i)return;const a=l.agents.find(c=>c.agentId===t);a&&r(t,a.busy.state==="busy")}).catch(()=>{}),()=>{i=!0}},[s,n,e,t,r])}function FP(e,t){const{index:n}=gp();return g.useMemo(()=>LP(n,e,t),[n,e,t])}function U(...e){return e.filter(Boolean).join(" ")}function Ie({size:e=16,className:t,label:n="Loading"}){return o.jsx("span",{role:"status","aria-label":n,className:U("inline-block animate-spin rounded-full border-2 border-current border-t-transparent",t),style:{width:e,height:e}})}const $P="inline-flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors select-none disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none",WP={sm:"h-7 px-2.5 text-xs",md:"h-9 px-3.5 text-sm"},HP={primary:"bg-primary text-on-primary hover:bg-primary-hover",secondary:"bg-raised text-content border border-border hover:border-border-strong",ghost:"text-muted hover:text-content hover:bg-raised",danger:"bg-danger text-white hover:brightness-110"},M=g.forwardRef(function({variant:t="secondary",size:n="md",loading:r=!1,disabled:s,className:i,children:l,...a},c){return o.jsxs("button",{ref:c,type:a.type??"button",disabled:s||r,className:U($P,WP[n],HP[t],i),...a,children:[r&&o.jsx(Ie,{size:n==="sm"?12:14}),l]})}),UP={sm:"h-6 w-6 text-xs",md:"h-8 w-8 text-sm"},Hn=g.forwardRef(function({size:t="md",className:n,children:r,...s},i){return o.jsx("button",{ref:i,type:s.type??"button",className:U("inline-flex items-center justify-center rounded-md text-muted transition-colors","hover:bg-raised hover:text-content focus-visible:outline-none","disabled:opacity-50 disabled:cursor-not-allowed",UP[t],n),...s,children:r})}),ie=g.forwardRef(function({invalid:t=!1,className:n,...r},s){return o.jsx("input",{ref:s,"aria-invalid":t||void 0,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border placeholder:text-faint outline-none transition-colors",t?"border-danger":"border-border focus:border-primary","disabled:opacity-50 disabled:cursor-not-allowed",n),...r})});function qt({label:e,hint:t,error:n,hideLabel:r,className:s,children:i}){const l=g.useId(),a=`${l}-msg`,c=n??t;return o.jsxs("div",{className:U("flex flex-col gap-1",s),children:[o.jsx("label",{htmlFor:l,className:U("text-xs font-medium text-muted",r&&"sr-only"),children:e}),i({id:l,describedBy:c?a:void 0}),c&&o.jsx("p",{id:a,role:n?"alert":void 0,className:U("text-xs",n?"text-danger":"text-faint"),children:c})]})}function ke({title:e,actions:t,flush:n,className:r,children:s,...i}){const l=e!=null||t!=null;return o.jsxs("section",{className:U("rounded-lg border border-border bg-surface",r),...i,children:[l&&o.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-2.5",children:[typeof e=="string"?o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}):e,t]}),o.jsx("div",{className:U(!n&&"p-4"),children:s})]})}function qP({items:e,value:t,onSelect:n,onClose:r,className:s}){return o.jsx("div",{role:"tablist",className:U("flex flex-wrap items-stretch gap-1",s),children:e.map(i=>{const l=i.id===t;return o.jsxs("div",{className:U("group flex items-center gap-1 rounded-md border px-1 transition-colors",l?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[o.jsx("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>n(i.id),className:U("px-2 py-1 text-sm focus-visible:outline-none",l?"font-semibold text-content":"text-muted hover:text-content"),children:i.label}),r&&o.jsx(Hn,{size:"sm","aria-label":`close ${i.label}`,onClick:()=>r(i.id),className:"opacity-60 group-hover:opacity-100",children:"×"})]},i.id)})})}const KP={start:"justify-start",between:"justify-between",end:"justify-end"};function xw({justify:e="start",className:t,children:n,...r}){return o.jsx("div",{role:"toolbar",className:U("flex items-center gap-2",KP[e],t),...r,children:n})}const Sn={menuDropdown:40,floatingWindow:50,floatingWindowNested:60,toast:70},VP={sm:"max-w-sm",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"},hx='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',qi=[];function Wh({open:e,title:t,onClose:n,size:r="md",children:s}){return e?o.jsx(GP,{title:t,onClose:n,size:r,children:s}):null}function GP({title:e,onClose:t,size:n,children:r}){const s=g.useRef(null),i=g.useRef(t);return i.current=t,g.useEffect(()=>{const l=document.activeElement,a=s.current,c={};qi.push(c);const u=()=>qi[qi.length-1]===c;(a?.querySelector(hx)??a)?.focus();function d(f){if(!u())return;if(f.key==="Escape"){f.preventDefault(),i.current();return}if(f.key!=="Tab"||!a)return;const p=Array.from(a.querySelectorAll(hx));if(p.length===0){f.preventDefault(),a.focus();return}const m=p[0],x=p[p.length-1],w=document.activeElement;f.shiftKey&&w===m?(f.preventDefault(),x.focus()):!f.shiftKey&&w===x&&(f.preventDefault(),m.focus())}return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d);const f=qi.indexOf(c);f>=0&&qi.splice(f,1),l?.focus?.()}},[]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindow},onMouseDown:l=>{l.target===l.currentTarget&&t()},children:o.jsxs("div",{ref:s,role:"dialog","aria-modal":"true","aria-label":e,tabIndex:-1,className:U("flex max-h-[80vh] w-full flex-col overflow-hidden rounded-lg","border border-border bg-surface shadow-xl outline-none",VP[n??"md"]),children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:e}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`close ${e}`,onClick:t,children:"Close"})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})})}function YP({menus:e,className:t}){const[n,r]=g.useState(null),[s,i]=g.useState(null),l=g.useRef(null);function a(){r(null),i(null)}return g.useEffect(()=>{if(n===null)return;function c(h){l.current?.contains(h.target)||a()}function u(h){h.key==="Escape"&&a()}return document.addEventListener("mousedown",c),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("keydown",u)}},[n]),o.jsx("div",{ref:l,className:U("flex shrink-0 items-center gap-0.5 border-b border-border bg-surface px-2 py-1",t),children:e.map(c=>{const u=n===c.id;return o.jsxs("div",{className:"relative",children:[o.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":u,onClick:()=>{i(null),r(h=>h===c.id?null:c.id)},className:U("rounded px-2.5 py-1 text-sm transition-colors",u?"bg-raised text-content":"text-muted hover:bg-raised hover:text-content"),children:c.label}),u&&o.jsx("div",{role:"menu","aria-label":c.label,style:{zIndex:Sn.menuDropdown},className:U("absolute left-0 top-full mt-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:c.items.map(h=>{const d=(h.submenu?.length??0)>0,f=d&&s===h.id;return o.jsxs("div",{className:"relative",onMouseEnter:()=>i(d?h.id:null),children:[o.jsxs("button",{type:"button",disabled:h.disabled,"aria-haspopup":d?"menu":void 0,"aria-expanded":d?f:void 0,onClick:()=>{if(d){i(p=>p===h.id?null:h.id);return}h.onSelect(),a()},className:U("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[o.jsx("span",{children:h.label}),d?o.jsx("span",{"aria-hidden":!0,className:"text-muted",children:h.active?"● ▸":"▸"}):h.active&&o.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]}),f&&o.jsx("div",{role:"menu","aria-label":h.label,style:{zIndex:Sn.floatingWindowNested},className:U("absolute left-full top-0 ml-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:h.submenu.map(p=>o.jsxs("button",{type:"button",disabled:p.disabled,onClick:()=>{p.onSelect(),a()},className:U("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[o.jsx("span",{children:p.label}),p.active&&o.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]},p.id))})]},h.id)})})]},c.id)})})}const XP=240,QP=720;function fx({side:e,width:t,onResize:n,minWidth:r=XP,maxWidth:s=QP,"aria-label":i,children:l}){const a=g.useRef(null);function c(p){return Math.min(s,Math.max(r,p))}function u(p){p.preventDefault(),p.currentTarget.setPointerCapture?.(p.pointerId),a.current={startX:p.clientX,startWidth:t}}function h(p){const m=a.current;if(!m)return;const x=p.clientX-m.startX,w=e==="left"?x:-x;n(c(m.startWidth+w))}function d(p){if(!a.current)return;const m=p.clientX-a.current.startX,x=e==="left"?m:-m;a.current=null,n(c(t+x))}const f=o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":`resize ${e} dock`,onPointerDown:u,onPointerMove:h,onPointerUp:d,className:"shrink-0 cursor-col-resize bg-border hover:bg-border-strong",style:{flex:"0 0 4px",touchAction:"none"}});return o.jsxs("aside",{"aria-label":i??`${e} dock`,className:U("flex h-full shrink-0 bg-surface",e==="left"?"flex-row border-r border-border":"flex-row-reverse border-l border-border"),style:{width:t},children:[o.jsx("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:l}),f]})}function JP(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleTimeString()}catch{return""}}function ZP({projectId:e,agentId:t}){zP(e,t);const{announcements:n,active:r}=gw(t),s=g.useRef(null);return g.useEffect(()=>{const i=s.current;i&&(i.scrollTop=i.scrollHeight)},[n]),r?o.jsxs("div",{"data-testid":"target-announcements-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-[4] flex flex-col bg-canvas/85 backdrop-blur-sm",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-surface/80 px-4 py-2",children:[o.jsx(Ie,{size:14}),o.jsx("span",{className:"text-sm font-medium text-content",children:"Un agent est en train de lui parler…"})]}),o.jsx("div",{ref:s,className:"flex flex-1 flex-col justify-end gap-1.5 overflow-hidden px-6 py-4",children:n.map(i=>{const l=JP(i.atMs);return o.jsxs("div",{className:"flex items-baseline gap-2 text-sm text-muted",children:[l&&o.jsx("span",{className:"shrink-0 text-xs text-faint",children:l}),o.jsx("span",{className:"whitespace-pre-wrap break-words text-content/90",children:i.text})]},i.seq)})})]}):null}function eA({requester:e,ticketId:t,limit:n=3}){const r=FP(e,t);if(r.length===0)return null;const s=r.slice(Math.max(0,r.length-n));return o.jsxs("div",{"data-testid":"announcements-preview",className:"flex flex-col gap-1 rounded-md border border-primary/25 bg-primary/5 px-2.5 py-1.5",children:[o.jsxs("span",{className:"flex items-center gap-1.5 text-[0.65rem] font-medium uppercase tracking-wide text-primary",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-primary"}),"En attente d'un agent"]}),o.jsx("ul",{className:"flex flex-col gap-0.5",children:s.map(i=>o.jsx("li",{className:"truncate text-xs text-muted",title:i.text,children:i.text},i.seq))})]})}class tA{constructor(t,n){X(this,"handlers",new Map);this.pluginId=t,this.declaredCommandIds=n}register(t,n){if(!this.declaredCommandIds.has(t))throw new Error(`plugin "${this.pluginId}" tried to register command "${t}" which is not declared by any menu item in its manifest`);return this.handlers.set(t,n),{dispose:()=>{this.handlers.get(t)===n&&this.handlers.delete(t)}}}async run(t,...n){const r=this.handlers.get(t);r&&await r(...n)}has(t){return this.handlers.has(t)}}class nA{constructor(t,n){X(this,"components",new Map);this.pluginId=t,this.declaredLayoutTypes=n}register(t){if(!this.declaredLayoutTypes.has(t.type))throw new Error(`plugin "${this.pluginId}" tried to register layout type "${t.type}" which is not declared in its manifest`);return this.components.set(t.type,t.component),{dispose:()=>{this.components.get(t.type)===t.component&&this.components.delete(t.type)}}}get(t){return this.components.get(t)}}class rA{constructor(t){this.pluginId=t}get ownerPluginId(){return this.pluginId}}class xp{constructor(){X(this,"loaded",new Map)}add(t){this.loaded.set(t.pluginId,t)}async remove(t){const n=this.loaded.get(t);if(n)try{await n.dispose()}finally{this.loaded.delete(t)}}get(t){return this.loaded.get(t)}list(){return[...this.loaded.values()]}topLevelMenus(){return this.list().flatMap(t=>t.contributes.menus.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,menu:n})))}menuItems(){return this.list().flatMap(t=>t.contributes.menuItems.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,item:n})))}layoutComponent(t,n){return this.loaded.get(t)?.layouts.get(n)}layoutContributions(){return this.list().flatMap(t=>t.contributes.layouts.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,layout:n})))}async runCommand(t,n,...r){await this.loaded.get(t)?.commands.run(n,...r)}}function sA(e){return typeof e=="object"&&e!==null&&"activate"in e&&typeof e.activate=="function"}async function iA(e,t){try{const n=await import(e.bundleUrl);if(!sA(n))return{failure:{pluginId:e.id,reason:'bundle does not export an "activate(ctx)" function'}};const r=new Set(e.contributes.menuItems.map(d=>d.command)),s=new Set(e.contributes.layouts.map(d=>d.type)),i=new tA(e.id,r),l=new nA(e.id,s),a=new rA(e.id),c={pluginId:e.id,pluginDisplayName:e.displayName,version:e.version,commands:i,layouts:l,menu:a,...t},u=await n.activate(c);return{plugin:{pluginId:e.id,displayName:e.displayName,contributes:e.contributes,commands:i,layouts:l,menu:a,dispose:async()=>{try{await u.dispose?.()}catch{}}}}}catch(n){return{failure:{pluginId:e.id,reason:n instanceof Error?n.message:String(n)}}}}async function lA(e,t){const n=new xp,r=[],s=await Promise.all(e.map(i=>iA(i,t)));for(const i of s)"failure"in i?r.push(i.failure):n.add(i.plugin);return{registry:n,failures:r}}const oA=new Set(["projectOpen","gitRepository","agentSelected","terminalFocused","layoutCellFocused"]);function aA(e){const t=[];let n=0;for(;n=this.tokens.length}}function uA(e,t){if(e===void 0||e.trim()==="")return{ok:!0,value:!0};const n=aA(e);if(!n)return{ok:!1,reason:`invalid "when" expression: ${e}`};try{const r=new cA(n),s=r.parseOr(t);if(!r.finished())throw new Error("unexpected trailing tokens");return{ok:!0,value:s}}catch(r){const s=r instanceof Error?r.message:String(r);return{ok:!1,reason:`invalid "when" expression "${e}": ${s}`}}}const dA={registry:new xp,failures:[],loading:!1},vw=g.createContext(dA);function hA({children:e,value:t}){const n=ue(),[r,s]=g.useState(t??{registry:new xp,failures:[],loading:!0});return g.useEffect(()=>{if(t)return;let i=!1;return n.plugin.listRuntimeContributions().then(l=>lA(l.plugins,{project:n.project,git:n.git,terminal:n.terminal,agents:n.agent,system:n.system})).then(l=>{i||s({registry:l.registry,failures:l.failures,loading:!1})}).catch(()=>{i||s(l=>({...l,loading:!1}))}),()=>{i=!0}},[]),o.jsx(vw.Provider,{value:r,children:e})}function vp(){return g.useContext(vw)}function px({title:e,body:t,confirmLabel:n,danger:r=!1,busy:s=!1,onConfirm:i,onCancel:l}){const a=g.useRef(null);return g.useEffect(()=>{a.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.floatingWindow},onClick:l,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-md flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"whitespace-pre-line text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),o.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:s,onClick:()=>void i(),children:n})]})]})})}function Zr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function fA(){const{plugin:e,system:t}=ue(),[n,r]=g.useState([]),[s,i]=g.useState(null),[l,a]=g.useState(!1),c=g.useCallback(async()=>{a(!0),i(null);try{r(await e.listPlugins())}catch(_){i(Zr(_))}finally{a(!1)}},[e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async _=>{a(!0),i(null);try{return await e.reviewPackage(_)}catch(b){return i(Zr(b)),null}finally{a(!1)}},[e]),h=g.useCallback(_=>u({sourceKind:"archive",path:_}),[u]),d=g.useCallback(_=>u({sourceKind:"directory",path:_}),[u]),f=g.useCallback(async _=>{a(!0),i(null);try{const b=await e.installFromArchive(_);return r(j=>[...j.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return i(Zr(b)),!1}finally{a(!1)}},[e]),p=g.useCallback(async _=>{a(!0),i(null);try{const b=await e.installFromDirectory(_);return r(j=>[...j.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return i(Zr(b)),!1}finally{a(!1)}},[e]),m=g.useCallback(async(_,b)=>{a(!0),i(null);try{const j=await e.setEnabled(_,b);r(S=>S.map(N=>N.id===_?j:N))}catch(j){i(Zr(j))}finally{a(!1)}},[e]),x=g.useCallback(async _=>{a(!0),i(null);try{await e.uninstall(_),r(b=>b.filter(j=>j.id!==_))}catch(b){i(Zr(b))}finally{a(!1)}},[e]),w=g.useCallback(async _=>{try{await e.openPluginsFolder(_)}catch(b){i(Zr(b))}},[e]),v=g.useCallback(()=>t.pickArchiveFile(),[t]),y=g.useCallback(()=>t.pickFolder(),[t]);return{plugins:n,error:s,busy:l,refresh:c,reviewArchive:h,reviewDirectory:d,installFromArchive:f,installFromDirectory:p,setEnabled:m,uninstall:x,openPluginsFolder:w,pickArchiveFile:v,pickDirectory:y}}const pA={enabled:"Activé",disabled:"Désactivé","pending-enable":"Activation en attente","pending-disable":"Désactivation en attente","pending-uninstall":"Désinstallation en attente",invalid:"Invalide"};function mA(){const e=fA(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(null);async function a(){l(null);const d=await e.pickArchiveFile();if(!d)return;const f=await e.reviewArchive(d);if(!f){l("La revue du paquet a échoué.");return}s({sourceKind:"archive",path:d,review:f})}async function c(){l(null);const d=await e.pickDirectory();if(!d)return;const f=await e.reviewDirectory(d);if(!f){l("La revue du paquet a échoué.");return}s({sourceKind:"directory",path:d,review:f})}async function u(){if(!r)return;(r.sourceKind==="archive"?await e.installFromArchive(r.path):await e.installFromDirectory(r.path))&&s(null)}async function h(){t&&(t.kind==="disable"?await e.setEnabled(t.plugin.id,!1):await e.uninstall(t.plugin.id),n(null))}return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:"Plugins"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{size:"sm",onClick:()=>void a(),disabled:e.busy,children:"Installer depuis une archive…"}),o.jsx(M,{size:"sm",variant:"secondary",onClick:()=>void c(),disabled:e.busy,children:"Installer depuis un dossier…"})]})]}),(e.error||i)&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error??i}),e.plugins.length===0?o.jsx(ke,{children:o.jsx("p",{className:"text-sm text-muted",children:"Aucun plugin installé."})}):o.jsx("ul",{className:"flex flex-col gap-2",children:e.plugins.map(d=>o.jsx("li",{children:o.jsxs(ke,{className:"flex items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:d.displayName}),o.jsxs("span",{className:"text-xs text-faint",children:["v",d.version]}),d.publisher&&o.jsxs("span",{className:"text-xs text-faint",children:["· ",d.publisher]}),o.jsx("span",{className:"rounded bg-raised px-1.5 py-0.5 text-[0.65rem] uppercase text-muted",children:"full-trust"})]}),o.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted",children:[o.jsx("span",{"aria-label":"plugin state",className:d.lifecycleState==="invalid"?"text-danger":void 0,children:pA[d.lifecycleState]}),d.restartRequired&&o.jsx("span",{className:"text-warning",children:"Redémarrage requis"}),d.sourceLabel&&o.jsxs("span",{children:["· ",d.sourceLabel]})]}),d.error&&o.jsx("p",{className:"text-xs text-danger",role:"alert",children:d.error})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[d.enabled?o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>n({kind:"disable",plugin:d}),disabled:e.busy,children:"Désactiver"}):o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.setEnabled(d.id,!0),disabled:e.busy,children:"Activer"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.openPluginsFolder(d.id),disabled:e.busy,children:"Ouvrir le dossier"}),o.jsx(M,{size:"sm",variant:"danger",onClick:()=>n({kind:"uninstall",plugin:d}),disabled:e.busy,children:"Désinstaller"})]})]})},d.id))}),r&&o.jsx(px,{title:`Installer "${r.review.displayName}" ?`,body:gA(r.review),confirmLabel:r.review.installable?"Installer":"Corriger avant d'installer",busy:e.busy,danger:!r.review.installable,onConfirm:()=>{r.review.installable?u():s(null)},onCancel:()=>s(null)}),t&&o.jsx(px,{title:t.kind==="disable"?`Désactiver "${t.plugin.displayName}" ?`:`Désinstaller "${t.plugin.displayName}" ?`,body:t.kind==="disable"?"Ses contributions seront masquées immédiatement ; un redémarrage sera peut-être nécessaire pour purger complètement le plugin.":"Le plugin, ses fichiers et ses contributions seront supprimés après redémarrage.",confirmLabel:t.kind==="disable"?"Désactiver":"Désinstaller",danger:t.kind==="uninstall",busy:e.busy,onConfirm:()=>void h(),onCancel:()=>n(null)})]})}function gA(e){const{contributionSummary:t}=e;return[`Éditeur : ${e.publisher??"inconnu"}`,`Version : ${e.version}`,e.description??null,"Confiance : full-trust — ce plugin peut exécuter du code arbitraire dans IdeA.",`Contributions : ${t.topLevelMenus} menu(s), ${t.menuItems} item(s), ${t.layouts} layout(s), ${t.mcpServers} serveur(s) MCP.`,...e.issues.map(r=>`${r.severity==="error"?"Erreur":"Avertissement"} : ${r.message}`)].filter(r=>!!r).join(` -`)}function xA(e){return e.topLevelMenus().map(({pluginId:t,pluginDisplayName:n,menu:r})=>({id:`plugin:${r.id}`,pluginId:t,pluginDisplayName:n,label:r.label,icon:r.icon,order:r.order??0})).sort((t,n)=>t.order-n.order||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.label.localeCompare(n.label))}function vA(e,t,n){return e.menuItems().filter(({item:r})=>r.targetMenuId===t).map(({pluginId:r,pluginDisplayName:s,item:i})=>{const l=uA(i.when,n);return{id:i.id,pluginId:r,pluginDisplayName:s,targetMenuId:i.targetMenuId,label:i.label,command:i.command,enabled:l.ok?l.value:!1,disabledReason:l.ok?void 0:l.reason,groupLabel:s,order:i.order??0,iconUrl:i.icon}}).sort((r,s)=>r.order-s.order||r.pluginDisplayName.localeCompare(s.pluginDisplayName)||r.label.localeCompare(s.label))}function yA(e,t){const n=g.useMemo(()=>(i,l)=>e.runCommand(i,l),[e]),r=g.useMemo(()=>i=>vA(e,i,t).map(l=>({id:l.id,label:`${l.label} · ${l.pluginDisplayName}`,disabled:!l.enabled,onSelect:()=>{n(l.pluginId,l.command)}})),[e,t,n]);return{topLevelMenus:g.useMemo(()=>xA(e).map(i=>({id:i.id,label:i.label,items:r(i.id)})),[e,r]),itemsFor:r,runCommand:n}}function _A(e,t,n){const r=e.get(t.pluginId);if(!r){const l=n?.find(a=>a.id===t.pluginId);return l&&!l.enabled?"plugin-disabled":"plugin-missing"}return!r.contributes.layouts.some(l=>l.type===t.layoutType)||!r.layouts.get(t.layoutType)?"incompatible":"available"}const bA={"plugin-disabled":"Le plugin fournisseur est désactivé.","plugin-missing":"Le plugin fournisseur n'est pas installé.",incompatible:"Le plugin fournisseur ne déclare plus ce type de layout."};function wA({cell:e,availability:t,providerDisplayName:n,onOpenPlugins:r,onChooseAnotherLayout:s}){return o.jsxs(ke,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[o.jsx("p",{className:"text-sm font-semibold text-content",children:"Layout indisponible"}),o.jsx("p",{className:"text-xs text-muted",children:bA[t]}),o.jsxs("p",{className:"text-xs text-faint",children:["Fourni par « ",n??e.pluginId," »"]}),o.jsxs("div",{className:"mt-2 flex gap-2",children:[o.jsx(M,{size:"sm",variant:"secondary",onClick:r,children:"Ouvrir Plugins"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:s,children:"Choisir un autre layout"})]})]})}function SA({projectId:e,cell:t,installedPlugins:n,onStateChange:r,onOpenPlugins:s,onChooseAnotherLayout:i}){const{registry:l}=vp(),a=ue(),c=_A(l,t,n);if(c!=="available"){const h=l.get(t.pluginId)?.displayName??n?.find(d=>d.id===t.pluginId)?.displayName;return o.jsx(wA,{cell:t,availability:c,providerDisplayName:h,onOpenPlugins:s,onChooseAnotherLayout:i})}const u=l.layoutComponent(t.pluginId,t.layoutType);return o.jsx(u,{projectId:e,nodeId:t.id,layoutType:t.layoutType,state:t.state,setState:r,availability:"available",gateways:{project:a.project,git:a.git,terminal:a.terminal,agents:a.agent,system:a.system}})}function kA(e){return e.layoutContributions().map(({pluginId:t,pluginDisplayName:n,layout:r})=>({pluginId:t,pluginDisplayName:n,layout:r})).sort((t,n)=>(t.layout.order??0)-(n.layout.order??0)||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.layout.label.localeCompare(n.layout.label))}function CA({registry:e,onSelect:t}){const n=kA(e);return n.length===0?null:o.jsxs("div",{role:"group","aria-label":"Layouts plugins",children:[o.jsx("p",{className:"px-3 pt-2 text-[0.65rem] font-semibold uppercase tracking-wide text-faint",children:"Layouts plugins"}),n.map(r=>o.jsxs("button",{type:"button",role:"menuitem","aria-label":`create ${r.layout.label} layout`,onClick:()=>t(r),className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm text-content hover:bg-raised",children:[o.jsx("span",{children:r.layout.label}),o.jsx("span",{className:"text-xs text-faint",children:r.pluginDisplayName})]},`${r.pluginId}:${r.layout.type}`))]})}function mx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function jA(e){const{template:t}=ue(),[n,r]=g.useState([]),[s,i]=g.useState(!1),[l,a]=g.useState(null),c=g.useCallback(async()=>{i(!0),a(null);try{const d=await t.detectDrift(e);r(d)}catch(d){a(mx(d))}finally{i(!1)}},[t,e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async(d,f)=>{i(!0),a(null);try{await t.syncAgent(e,d),f&&await f();const p=await t.detectDrift(e);r(p)}catch(p){a(mx(p))}finally{i(!1)}},[t,e]);return{driftByAgentId:new Map(n.map(d=>[d.agentId,d])),driftBusy:s,driftError:l,refreshDrift:c,syncAgent:u}}function Bn(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NA(e){const{agent:t,profile:n,system:r,terminal:s,input:i}=ue(),[l,a]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState([]),[w,v]=g.useState(null),[y,_]=g.useState(!1),[b,j]=g.useState(null),[S,N]=g.useState({}),[D,A]=g.useState({}),[k,R]=g.useState({}),[T,E]=g.useState({}),O=g.useCallback(async()=>{_(!0),v(null);try{const[te,J]=await Promise.all([t.listAgents(e),n.listProfiles()]);a(te),p(J)}catch(te){v(Bn(te))}finally{_(!1)}},[t,n,e]),I=g.useCallback(async()=>{try{x(await t.listLiveAgents(e))}catch{x([])}},[t,e]);g.useEffect(()=>{O()},[O]),g.useEffect(()=>{I()},[I]),g.useEffect(()=>{if(!r)return;let te,J=!1;return r.onDomainEvent(K=>{if((K.type==="agentLaunched"||K.type==="agentExited"||K.type==="agentProfileChanged")&&(O(),I()),K.type==="agentLaunched"&&E(Y=>{if(!(K.agentId in Y))return Y;const{[K.agentId]:ae,...pe}=Y;return pe}),K.type==="orchestratorRequestProcessed"&&K.source!==void 0){const{requesterId:Y,source:ae}=K;N(pe=>pe[Y]===ae?pe:{...pe,[Y]:ae})}switch(K.type){case"agentRateLimited":A(Y=>({...Y,[K.agentId]:{limitedUntil:K.resetsAtMs,resumeFireAt:Y[K.agentId]?.resumeFireAt,suspected:!1}}));break;case"agentResumeScheduled":A(Y=>({...Y,[K.agentId]:{...Y[K.agentId],resumeFireAt:K.fireAtMs}}));break;case"agentResumeCancelled":A(Y=>{const ae=Y[K.agentId];if(!ae)return Y;const{resumeFireAt:pe,...Pe}=ae;return{...Y,[K.agentId]:Pe}});break;case"agentResumed":A(Y=>{if(!(K.agentId in Y))return Y;const{[K.agentId]:ae,...pe}=Y;return pe});break;case"agentRateLimitSuspected":A(Y=>({...Y,[K.agentId]:{...Y[K.agentId],limitedUntil:K.resetsAtMs,suspected:!0}}));break;case"modelServerStatusChanged":R(Y=>({...Y,[K.serverId]:K.status}));break;case"agentLaunchFailed":E(Y=>({...Y,[K.agentId]:{cause:K.cause,code:K.code,message:K.message}}));break}}).then(K=>{J?K():te=K}),()=>{J=!0,te?.()}},[r,O,I]);const W=g.useCallback(async(te,J,K)=>{_(!0),v(null);try{const Y=await t.createAgent(e,{name:te,profileId:J,initialContent:K});a(ae=>[...ae,Y])}catch(Y){v(Bn(Y))}finally{_(!1)}},[t,e]),G=g.useCallback(async te=>{_(!0),v(null);try{const J=await t.readContext(e,te);u(te),d(J)}catch(J){v(Bn(J))}finally{_(!1)}},[t,e]),P=g.useCallback(async te=>{if(c){_(!0),v(null);try{await t.updateContext(e,c,te),d(te)}catch(J){v(Bn(J))}finally{_(!1)}}},[t,e,c]),z=g.useCallback(async(te,J,K,Y)=>{_(!0),v(null);try{const{agent:ae,relaunchedSession:pe}=await t.changeAgentProfile(e,te,J,K,Y);return a(Pe=>Pe.map($=>$.id===ae.id?ae:$)),I(),pe}catch(ae){v(Bn(ae));return}finally{_(!1)}},[t,e,I]),C=g.useCallback(async te=>{_(!0),v(null);try{await t.deleteAgent(e,te),a(J=>J.filter(K=>K.id!==te)),u(J=>J===te?null:J),c===te&&d(""),j(J=>J===te?null:J)}catch(J){v(Bn(J))}finally{_(!1)}},[t,e,c]),Q=g.useCallback(async(te,J,K)=>{v(null);try{const Y=await t.launchAgent(e,te,J,K);return j(te),I(),Y}catch(Y){throw v(Bn(Y)),Y}},[t,e,I]),q=g.useCallback(async te=>{const J=te??b,K=J?m.find(Y=>Y.agentId===J):null;if(j(Y=>Y===J||!J?null:Y),K?.sessionId)try{await s?.closeTerminal(K.sessionId),x(Y=>Y.filter(ae=>ae.agentId!==J))}catch(Y){v(Bn(Y)),await I()}},[m,I,b,s]),L=g.useCallback(async te=>{A(J=>{const K=J[te];if(!K?.resumeFireAt)return J;const{resumeFireAt:Y,...ae}=K;return{...J,[te]:ae}});try{return await i?.cancelResume(te)??!1}catch(J){return v(Bn(J)),!1}},[i]),se=g.useCallback(async(te,J)=>{try{await i?.setResumeAt(te,J)}catch(K){v(Bn(K))}},[i]);return{agents:l,selectedAgentId:c,context:h,profiles:f,liveAgents:m,delegationSourceByRequester:S,limitByAgent:D,modelServerStatusByServer:k,launchFailureByAgent:T,error:w,busy:y,runningAgentId:b,refresh:O,refreshLiveAgents:I,createAgent:W,selectAgent:G,saveContext:P,changeAgentProfile:z,deleteAgent:C,launchAgent:Q,stopAgent:q,cancelResume:L,setResumeAt:se}}function yw(e,t,n){if(!e)return;const r=t.find(s=>s.id===e.profileId)?.opencode?.localModelServerId;return r?n[r]:void 0}function EA(e){if(!e)return null;switch(e.state){case"downloading":return"Téléchargement du modèle…";case"starting":case"probing":return"Chargement du serveur…";default:return null}}function Au(e){if(!Number.isFinite(e)||e<=0)return"0 o";const t=["o","Ko","Mo","Go","To"];let n=e,r=0;for(;n>=1e3&&r{t&&t.listProfiles().then(s).catch(()=>{})},[t]);return g.useEffect(()=>{a()},[a]),g.useEffect(()=>{if(!n)return;let u,h=!1;return n.onDomainEvent(d=>{d.type==="modelServerStatusChanged"?l(f=>({...f,[d.serverId]:d.status})):d.type==="agentProfileChanged"&&a()}).then(d=>{h?d():u=d}),()=>{h=!0,u?.()}},[n,a]),{statusForAgent:g.useCallback(u=>yw(u,r,i),[r,i])}}function TA(e,t){const n=/^(\d{1,2}):(\d{2})$/.exec(e.trim());if(!n)return null;const r=Number(n[1]),s=Number(n[2]);if(r>23||s>59)return null;const i=new Date(t);return i.setHours(r,s,0,0),i.getTime()}function LA(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function DA(e){const t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function RA({state:e,onCancelResume:t,onSetResumeAt:n,busy:r=!1}){const{limitedUntil:s,resumeFireAt:i,suspected:l}=e,[a,c]=g.useState(()=>Date.now());g.useEffect(()=>{if(i===void 0)return;const m=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(m)},[i]);const[u,h]=g.useState(""),d=l===!0&&s===void 0&&i===void 0;function f(m){m.preventDefault();const x=TA(u,Date.now());x!==null&&(n(x),h(""))}const p=s!==void 0?`limité jusqu'à ${LA(s)}`:"limité";return o.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[o.jsx("span",{"aria-label":"session limit",title:l?"Limite de session détectée sans heure fiable":"Limite de session atteinte",className:U("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:p}),d&&o.jsxs("form",{onSubmit:f,className:"flex items-center gap-2","aria-label":"resume time form",children:[o.jsx("span",{className:"text-xs text-muted",role:"note",children:"heure inconnue"}),o.jsx(ie,{type:"time","aria-label":"resume time",value:u,disabled:r,onChange:m=>h(m.target.value),className:"h-8 w-28 text-xs"}),o.jsx(M,{type:"submit",size:"sm",variant:"primary","aria-label":"schedule resume",disabled:r||u.trim()==="",children:"Programmer la reprise"})]}),i!==void 0&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsxs("span",{"aria-label":"resume countdown",className:"text-xs text-muted",children:["reprise dans ",DA(i-a)]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel resume",disabled:r,onClick:t,children:"Annuler la reprise"})]})]})}function MA(e){switch(e.state){case"notConfigured":return null;case"probing":return{label:"vérification du serveur…",tone:"bg-muted/20 text-muted",role:"status"};case"starting":return{label:"démarrage du serveur…",tone:"bg-warning/20 text-warning",role:"status"};case"downloading":return{label:"téléchargement du modèle…",tone:"bg-warning/20 text-warning",role:"status"};case"ready":return e.reused?{label:"serveur prêt (réutilisé)",tone:"bg-success/20 text-success"}:{label:"serveur prêt",tone:"bg-success/20 text-success"};case"failed":return null}}function IA({status:e,failure:t}){const[n,r]=g.useState(!1),s=t||(e?.state==="failed"?{code:e.code,message:e.message}:null);if(s)return o.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[o.jsxs("span",{role:"alert","aria-label":"model server launch failed",className:U("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:["Échec du lancement : ",s.message]}),o.jsx("button",{type:"button","aria-label":"toggle launch failure detail",onClick:()=>r(l=>!l),className:"text-xs text-muted underline hover:text-content",children:"Détails"}),n&&o.jsxs("span",{"aria-label":"launch failure detail",className:"text-xs text-faint",children:["code ",s.code,s.cause?` · cause ${s.cause}`:""]})]});if(!e)return null;const i=MA(e);return i?o.jsx("span",{role:i.role,"aria-label":"model server status",className:U("rounded-full px-2 py-0.5 text-xs font-medium",i.tone),children:i.label}):null}function _w({projectId:e,projectRoot:t=""}){const n=NA(e),r=jA(e),s=ue(),i=s.template??null,l=s.permission??null,[a,c]=g.useState(""),[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState([]),[x,w]=g.useState(!1);!x&&i&&(w(!0),i.listTemplates().then(m).catch(()=>{}));const v=s.skill??null,[y,_]=g.useState([]),[b,j]=g.useState(!1),[S,N]=g.useState("");async function D(){if(v)try{const[$,B]=await Promise.all([v.listSkills(e,"global"),v.listSkills(e,"project")]);_([...B,...$])}catch{}}!b&&v&&(j(!0),D());async function A(){if(!v||!n.selectedAgentId||!S)return;const $=y.find(B=>B.id===S);$&&(await v.assignSkill(e,n.selectedAgentId,$.id,$.scope),N(""),await n.refresh())}async function k($){!v||!n.selectedAgentId||(await v.unassignSkill(e,n.selectedAgentId,$),await n.refresh())}const[R,T]=g.useState(n.context),[E,O]=g.useState(n.context);n.context!==E&&(O(n.context),T(n.context));const[I,W]=g.useState(null),[G,P]=g.useState({}),[z,C]=g.useState({}),[Q,q]=g.useState({});g.useEffect(()=>{if(!l||n.agents.length===0){q({});return}let $=!1;return Promise.all(n.agents.map(async B=>{try{return[B.id,await l.resolveAgentSystemPermissions(e,B.id)]}catch{return[B.id,null]}})).then(B=>{$||q(Object.fromEntries(B.filter(fe=>fe[1]!==null)))}),()=>{$=!0}},[l,e,n.agents]);const[L,se]=g.useState(null);async function te(){if(!L)return;const{agentId:$,profileId:B}=L;se(null);const fe=await n.changeAgentProfile($,B,24,80);fe&&$===I&&C(de=>({...de,[$]:fe.sessionId}))}const J=a.trim().length>0&&!n.busy;async function K($){if($.preventDefault(),!!J){if(d&&i)await i.createAgentFromTemplate(e,d,{name:a.trim(),synchronized:!0}),await n.refresh();else{const B=u.trim()||"";await n.createAgent(a.trim(),B)}c(""),h(""),f("")}}function Y($){P(B=>({...B,[$]:B[$]??crypto.randomUUID()})),W($)}function ae($){n.stopAgent($),W(null)}const pe=n.agents.find($=>$.id===n.selectedAgentId)??null,Pe=d!=="";return o.jsxs(ke,{title:"Agents",className:"flex flex-col gap-0",children:[n.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),o.jsxs("form",{onSubmit:$=>void K($),className:"flex flex-col gap-3 border-b border-border p-4",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"agent-name-input",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ie,{id:"agent-name-input","aria-label":"agent name",placeholder:"My agent",value:a,onChange:$=>c($.target.value),className:"w-full"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"agent-template-select",className:"text-xs font-medium text-muted",children:"Template"}),o.jsxs("select",{id:"agent-template-select","aria-label":"agent template",value:d,onChange:$=>f($.target.value),className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:n.busy,children:[o.jsx("option",{value:"",children:"(none / from scratch)"}),p.map($=>o.jsx("option",{value:$.id,children:$.name},$.id))]})]}),!Pe&&o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("label",{htmlFor:"agent-profile-select",className:"text-xs font-medium text-muted",children:["Profile",n.profiles.length===0&&o.jsx("span",{className:"ml-1 text-faint",children:"(no profiles configured — you can still enter an id)"})]}),n.profiles.length>0?o.jsxs("select",{id:"agent-profile-select","aria-label":"agent profile",value:u,onChange:$=>h($.target.value),className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— select profile —"}),n.profiles.map($=>o.jsx("option",{value:$.id,children:$.name},$.id))]}):o.jsx(ie,{id:"agent-profile-select","aria-label":"agent profile",placeholder:"profile-id (optional)",value:u,onChange:$=>h($.target.value),className:"min-w-32"})]}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"create agent",disabled:!J,loading:n.busy,className:"self-end",children:"Create"})]}),o.jsx("div",{className:"p-4",children:n.agents.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.agents.map($=>{const B=$.id===n.selectedAgentId,fe=$.id===I,de=n.liveAgents.find(ye=>ye.agentId===$.id),Ee=n.profiles.find(ye=>ye.id===$.profileId)?.name??$.profileId,dt=r.driftByAgentId.get($.id),Rn=n.delegationSourceByRequester[$.id],Yr=n.limitByAgent[$.id],Ps=yw($,n.profiles,n.modelServerStatusByServer),oe=n.launchFailureByAgent[$.id],ge=Q[$.id]??null;return o.jsxs("li",{className:U("flex flex-col gap-2 py-3 first:pt-0 last:pb-0",B&&"rounded-md bg-raised px-2"),children:[o.jsxs("button",{type:"button",onClick:()=>void n.selectAgent($.id),className:"flex min-w-0 flex-col items-start gap-0.5 text-left","aria-pressed":B,children:[o.jsxs("span",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:[o.jsx("span",{className:"font-medium text-content",children:$.name}),dt&&o.jsx("span",{"aria-label":"update available",className:"rounded-full bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary",children:"update available"}),Rn&&o.jsx("span",{"aria-label":`delegation source ${Rn}`,title:Rn==="mcp"?"Last delegation arrived via the MCP server":"Last delegation arrived via .ideai/requests",className:"rounded-full bg-raised px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-muted",children:Rn}),ge&&o.jsx(OA,{state:ge})]}),o.jsx("span",{className:"text-xs text-muted",children:Ee}),de&&o.jsxs("span",{className:"block w-full min-w-0 truncate text-xs text-primary",children:["running in IdeA · ",de.sessionId??de.nodeId]})]}),Yr&&o.jsx(RA,{state:Yr,busy:n.busy,onCancelResume:()=>void n.cancelResume($.id),onSetResumeAt:ye=>void n.setResumeAt($.id,ye)}),o.jsx(IA,{status:Ps,failure:oe}),o.jsx(eA,{requester:$.id}),o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.profiles.length>0&&o.jsxs("select",{"aria-label":`profile for ${$.name}`,value:$.profileId,disabled:n.busy,onChange:ye=>{const St=ye.target.value;St&&St!==$.profileId&&se({agentId:$.id,profileId:St})},className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[n.profiles.every(ye=>ye.id!==$.profileId)&&o.jsx("option",{value:$.profileId,children:$.profileId}),n.profiles.map(ye=>o.jsx("option",{value:ye.id,children:ye.name},ye.id))]}),dt&&o.jsx(M,{size:"sm",variant:"primary","aria-label":`sync ${$.name}`,disabled:n.busy||r.driftBusy,onClick:()=>void r.syncAgent($.id,n.refresh),children:"Sync"}),fe||de?o.jsx(M,{size:"sm",variant:"ghost","aria-label":`stop ${$.name}`,onClick:()=>ae($.id),className:"text-danger hover:text-danger",children:"Stop"}):o.jsx(M,{size:"sm",variant:"primary","aria-label":`launch ${$.name}`,disabled:n.busy||I!==null,onClick:()=>Y($.id),children:"Launch"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete ${$.name}`,disabled:n.busy,onClick:()=>void n.deleteAgent($.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},$.id)})})}),I!==null&&o.jsx("div",{className:"border-t border-border p-4",children:o.jsx("div",{className:"h-96 overflow-hidden rounded-lg border border-border bg-surface",children:o.jsx(pp,{cwd:t,open:($,B)=>n.launchAgent(I,{...$,nodeId:G[I]},B),reattach:($,B)=>s.agent.reattach($,B),sessionId:z[I]??null,onSessionId:$=>C(B=>({...B,[I]:$})),systemPermissions:Q[I]??null},I)})}),pe&&v&&o.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Skills — ",pe.name]}),pe.skills.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No skills assigned."}):o.jsx("ul",{className:"flex flex-wrap gap-1.5",children:pe.skills.map($=>{const B=y.find(fe=>fe.id===$.skillId)?.name??$.skillId;return o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[o.jsx("span",{children:B}),o.jsx("button",{type:"button","aria-label":`unassign ${B}`,disabled:n.busy,onClick:()=>void k($.skillId),className:"text-faint hover:text-danger",children:"✕"})]},$.skillId)})}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsxs("select",{"aria-label":"skill to assign",value:S,onChange:$=>N($.target.value),disabled:n.busy,className:U("h-9 min-w-0 flex-1 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— assign a skill —"}),y.filter($=>!pe.skills.some(B=>B.skillId===$.id)).map($=>o.jsxs("option",{value:$.id,children:[$.name," (",$.scope,")"]},$.id))]}),o.jsx(M,{variant:"primary","aria-label":"assign skill",disabled:n.busy||!S,onClick:()=>void A(),children:"Assign"})]})]}),pe&&o.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Context — ",pe.name]}),o.jsx("code",{className:"text-xs text-muted",children:pe.contextPath})]}),o.jsx("textarea",{"aria-label":"agent context",value:R,onChange:$=>T($.target.value),rows:10,className:U("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:n.busy}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.busy&&o.jsx(Ie,{size:14}),o.jsx(M,{variant:"primary",disabled:n.busy,onClick:()=>void n.saveContext(R),children:"Save"})]})]}),L&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm profile change",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Changer le moteur IA"}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Changer le moteur abandonne l'historique de conversation (le contexte et la mémoire sont conservés). Continuer ?"}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.jsx(M,{variant:"ghost","aria-label":"cancel profile change",disabled:n.busy,onClick:()=>se(null),children:"Annuler"}),o.jsx(M,{variant:"primary","aria-label":"confirm profile change",loading:n.busy,disabled:n.busy,onClick:()=>void te(),children:"Continuer"})]})]})})]})}function OA({state:e}){const t=e.runtimeLock.state==="locked",n=t?"Verrouillé":e.effective==="allow"?"Autorisé":e.effective==="deny"?"Interdit":"Demande";return o.jsxs("span",{"aria-label":`network ${n}`,title:t?e.runtimeLock.reason??"Réseau verrouillé par le runtime":`État effectif : ${n}`,className:U("rounded-full px-2 py-0.5 text-xs font-medium",t?"bg-warning/15 text-warning":e.effective==="allow"?"bg-success/15 text-success":e.effective==="deny"?"bg-danger/15 text-danger":"bg-primary/15 text-primary"),children:["Réseau: ",n]})}function Tu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function bw(e,t){const{layout:n,terminal:r}=ue(),[s,i]=g.useState(null),[l,a]=g.useState(0),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=g.useCallback(A=>{i(A),a(k=>k+1)},[]);g.useEffect(()=>{if(!e||!n){i(null);return}let A=!1;return d(!0),n.loadLayout(e,t).then(k=>{A||f(k)}).catch(k=>{A||u(Tu(k))}).finally(()=>{A||d(!1)}),()=>{A=!0}},[n,e,t,f]);const p=g.useCallback(async A=>{if(!(!e||!n)){d(!0),u(null);try{f(await n.mutateLayout(e,A,t))}catch(k){u(Tu(k))}finally{d(!1)}}},[n,e,t,f]),m=g.useCallback(async A=>{if(!(!e||!n||A.length===0)){d(!0),u(null);try{let k=null;for(const R of A)k=await n.mutateLayout(e,R,t);k&&f(k)}catch(k){u(Tu(k))}finally{d(!1)}}},[n,e,t,f]),x=g.useCallback((A,k)=>p(QE(A,k)),[p]),w=g.useCallback(async(A,k)=>{await p({type:"merge",container:A,keepIndex:k})},[p]),v=g.useCallback((A,k)=>p({type:"resize",container:A,weights:k}),[p]),y=g.useCallback((A,k)=>p({type:"move",from:A,to:k}),[p]),_=g.useCallback((A,k)=>p({type:"setSession",target:A,session:k}),[p]),b=g.useCallback(async(A,k)=>{const R=s?Za(s).find(O=>O.id===A):void 0,T=R?.agent??null,E=R?.session??null;if(k!==T&&(await m([{type:"setCellAgent",target:A,agent:k},{type:"setSession",target:A,session:null},{type:"setCellConversation",target:A,conversationId:null}]),E&&!T&&r))try{await r.closeTerminal(E)}catch{}},[s,m,r]),j=g.useCallback(async(A,k,R)=>{const T=s?Za(s).find(W=>W.id===A):void 0,E=T?.agent??null,O=T?.session??null,I=[];if(k!==E&&I.push({type:"setCellAgent",target:A,agent:k},{type:"setCellConversation",target:A,conversationId:null}),R!==O&&I.push({type:"setSession",target:A,session:R}),await m(I),O&&O!==R&&!E&&r)try{await r.closeTerminal(O)}catch{}},[s,m,r]),S=g.useCallback((A,k)=>p({type:"setCellConversation",target:A,conversationId:k}),[p]),N=g.useCallback((A,k)=>{i(R=>R&&YE(R,A,k)),a(R=>R+1)},[]),D=g.useCallback(A=>{i(k=>k&&XE(k,A)),a(k=>k+1)},[]);return{layout:s,layoutVersion:l,error:c,busy:h,split:x,merge:w,resize:v,move:y,setSession:_,setCellAgent:b,attachLiveAgentToCell:j,setCellConversation:S,setPluginLayoutState:N,replacePluginLayoutWithTerminal:D}}function BA(e,t,n){return e&&t&&!n}function zA({projectId:e,cwd:t,layoutId:n,onOpenConversation:r,onOpenPluginsSettings:s}){const i=bw(e,n),l=eo(e);return i.layout?o.jsxs("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%",position:"relative"},children:[i.error&&o.jsx("p",{role:"alert",style:{color:"crimson",margin:0},children:i.error}),o.jsx(yp,{node:i.layout.root,cwd:t,vm:i,parentSplit:null,projectId:e,workState:l.state,refreshWorkState:l.refresh,onOpenConversation:r,onOpenPluginsSettings:s})]}):o.jsx("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%"},children:i.error?o.jsx("p",{role:"alert",style:{color:"crimson"},children:i.error}):o.jsx("p",{children:"Loading layout…"})})}function yp({node:e,cwd:t,vm:n,parentSplit:r,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c}){switch(e.type){case"customPluginLayout":return o.jsx(SA,{projectId:s,cell:e.node,onStateChange:u=>n.setPluginLayoutState(e.node.id,u),onOpenPlugins:()=>c?.(),onChooseAnotherLayout:()=>n.replacePluginLayoutWithTerminal(e.node.id)});case"leaf":return o.jsx($A,{id:e.node.id,session:e.node.session??null,agent:e.node.agent??null,conversationId:e.node.conversationId??null,agentWasRunning:e.node.agentWasRunning??!1,cwd:t,vm:n,parentSplit:r,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a});case"split":return o.jsx(WA,{split:e.node,cwd:t,vm:n,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c});case"grid":return o.jsx(UA,{grid:e.node,cwd:t,vm:n,projectId:s,workState:i,refreshWorkState:l,onOpenConversation:a,onOpenPluginsSettings:c})}}function FA(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}const Ki={banner:3,veil:4,controls:5};function $A({id:e,session:t,agent:n,conversationId:r,agentWasRunning:s,cwd:i,vm:l,parentSplit:a,projectId:c,workState:u,refreshWorkState:h,onOpenConversation:d}){const f=a!==null&&a.siblings===2,p=a&&a.index===0?1:0,{agent:m,input:x,system:w}=ue(),{portal:v,overlay:y}=SP(c,n??null),[_,b]=g.useState([]);g.useEffect(()=>{if(!m)return;let oe=!1;return m.listAgents(c).then(ge=>{oe||b(ge)}).catch(()=>{}),()=>{oe=!0}},[m,c]);const[j,S]=g.useState([]),N=()=>{m?.listLiveAgents&&m.listLiveAgents(c).then(S).catch(()=>{})};g.useEffect(()=>{if(!m?.listLiveAgents)return;let oe=!1;return m.listLiveAgents(c).then(ge=>{oe||S(ge)}).catch(()=>{}),()=>{oe=!0}},[m,c]),g.useEffect(()=>{if(!w)return;let oe,ge=!1;return w.onDomainEvent(ye=>{(ye.type==="agentLaunched"||ye.type==="agentExited")&&N()}).then(ye=>{ge?ye():oe=ye}),()=>{ge=!0,oe?.()}},[w,m,c]);const D=n??null,{active:A}=gw(D??""),{statusForAgent:k}=AA(),R=D?_.find(oe=>oe.id===D):void 0,T=k(R),E=EA(T),O=PA(T),I=D?u?.agents.find(oe=>oe.agentId===D):void 0,W=I?.tickets.find(oe=>oe.status==="inProgress"),G=I?.tickets.filter(oe=>oe.status==="queued")??[],P=Math.max(I?.inboxDepth??0,I?.inbox?.length??0,G.length),z=I?.backgroundTasks?.filter(oe=>oe.status==="completed"||oe.status==="failed"||oe.status==="cancelled")??[],C=I?.busy.state==="busy"||!!W,Q=W?.source.kind==="agent"?W:void 0,q=W?.conversationId??r??null;async function L(){if(!(!D||!x))try{await x.interrupt(c,D),await h()}catch(oe){ae({message:gx(oe)})}}const se=oe=>j.find(ge=>ge.agentId===oe),te=async(oe,ge)=>{const ye=gx(oe);if(!xx(oe))return{message:ye};const Dt=(m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>j):j).find(H=>H.agentId===ge);return{message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:Dt&&Dt.nodeId!==e?Dt.nodeId:void 0}},J=oe=>{if(!l.layout)return;const ge=Za(l.layout).find(ye=>ye.id!==e&&(ye.agent??null)===oe);return ge?{nodeId:ge.id}:void 0},K=oe=>{const ge=se(oe);if(!(!ge||ge.kind!=="pty"||ge.nodeId===e))return J(oe)?void 0:ge},[Y,ae]=g.useState(null),[pe,Pe]=g.useState(null),[$,B]=g.useState(null),[fe,de]=g.useState(0);g.useEffect(()=>{if(!D||!m?.attachLiveAgent||pe)return;const oe=K(D);if(!oe?.sessionId||oe.sessionId===t)return;let ge=!1;return(async()=>{const ye=await m.attachLiveAgent(c,D,e);ge||(await l.attachLiveAgentToCell(e,D,ye.sessionId??oe.sessionId),ge||de(St=>St+1))})().catch(()=>{}),()=>{ge=!0}},[j,D,t]);const Ee=async(oe,ge,ye)=>{const St=K(D);if(St?.sessionId&&m.attachLiveAgent){const ne=(await m.attachLiveAgent(c,D,e)).sessionId??St.sessionId;l.setSession(e,ne);const xe=await m.reattach(ne,ge);return N(),xe.handle}const Dt=await m.launchAgent(c,D,{...oe,conversationId:ye,nodeId:e},ge).catch(async H=>{throw xx(H)&&ae(await te(H,D)),H});return Dt.assignedConversationId&&l.setCellConversation(e,Dt.assignedConversationId),Dt},dt=m&&D?(oe,ge)=>r?(Promise.resolve(m.inspectConversation?.(c,D,r)).then(ye=>B(ye??{})).catch(()=>B({})),new Promise((ye,St)=>{Pe({opts:oe,onData:ge,resolve:ye,reject:St})})):Ee(oe,ge,void 0):void 0,Rn=()=>{const oe=pe;oe&&(Pe(null),B(null),Ee(oe.opts,oe.onData,r??void 0).then(oe.resolve,oe.reject))},Yr=()=>{const oe=pe;oe&&(Pe(null),B(null),l.setCellConversation(e,null),Ee(oe.opts,oe.onData,void 0).then(oe.resolve,oe.reject))},Ps=m&&D?(oe,ge)=>m.reattach(oe,ge):void 0;return o.jsxs("div",{"data-testid":"layout-leaf","data-node-id":e,style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0,border:"1px solid #2a2a2a",boxSizing:"border-box",overflow:"hidden"},children:[o.jsxs("div",{style:{position:"absolute",top:2,right:16,zIndex:Ki.controls,display:"flex",gap:2,alignItems:"center"},children:[o.jsxs("select",{"aria-label":`agent selector ${e}`,value:D??"",onChange:oe=>{const ge=oe.target.value;if(ge===""){ae(null),l.setCellAgent(e,null);return}(async()=>{const ye=m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>j):j;S(ye);const St=J(ge);if(St){ae({message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:St.nodeId});return}const Dt=ye.find(ne=>ne.agentId===ge);if(Dt&&Dt.kind==="pty"&&Dt.nodeId!==e){if(!m?.attachLiveAgent||!Dt.sessionId){ae({message:"Session active introuvable pour cet agent."});return}ae(null);const ne=await m.attachLiveAgent(c,ge,e);await l.attachLiveAgentToCell(e,ge,ne.sessionId??Dt.sessionId),N();return}ae(null),await l.setCellAgent(e,ge)})().catch(async ye=>ae(await te(ye,ge)))},style:{fontSize:11,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,padding:"1px 2px",maxWidth:100},children:[o.jsx("option",{value:"",children:"Plain"}),_.map(oe=>{const ge=J(oe.id),ye=K(oe.id);return o.jsxs("option",{value:oe.id,disabled:!!ge,children:[oe.name,ge?" (visible ailleurs)":ye?" (arrière-plan)":""]},oe.id)})]}),o.jsx("button",{type:"button",title:"Split into columns","aria-label":`split ${e} columns`,onClick:()=>void l.split(e,"row"),children:"⬌"}),o.jsx("button",{type:"button",title:"Split into rows","aria-label":`split ${e} rows`,onClick:()=>void l.split(e,"column"),children:"⬍"}),f&&o.jsx("button",{type:"button",title:"Close this terminal","aria-label":`close ${e}`,onClick:()=>void l.merge(a.container,p),children:"✕"})]}),D&&(C||P>0||z.length>0||q)&&o.jsxs("div",{role:"status","aria-live":"polite",style:{position:"absolute",top:30,left:4,zIndex:Ki.banner,display:"flex",maxWidth:"calc(100% - 8px)",alignItems:"center",gap:4,overflow:"hidden"},children:[C&&o.jsx("span",{title:Q?.requesterLabel??W?.taskPreview,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-warning, #d49b3a)",borderRadius:3,background:"rgba(212, 155, 58, 0.16)",color:"var(--color-warning, #d49b3a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:Q?`Busy · ${Q.requesterLabel}`:"Busy"}),!C&&P>0&&o.jsxs("span",{title:`${P} pending message${P===1?"":"s"}`,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued · ",P]}),C&&P>0&&o.jsxs("span",{title:`${P} queued message${P===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued ",P]}),z.length>0&&o.jsxs("span",{title:`${z.length} background task result${z.length===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-success, #57b36a)",borderRadius:3,background:"rgba(87, 179, 106, 0.14)",color:"var(--color-success, #57b36a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Task done ",z.length]}),C&&o.jsx("button",{type:"button","aria-label":`cancel current turn ${e}`,title:"Cancel current turn",onClick:()=>void L(),disabled:!x,style:{flexShrink:0,border:"1px solid var(--color-danger, #d45a5a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-danger, #d45a5a)",cursor:x?"pointer":"default",fontSize:11,padding:"1px 6px"},children:"Cancel"}),q&&d&&o.jsx("button",{type:"button","aria-label":`open cell conversation ${e}`,title:"Open conversation history",onClick:()=>d(q),style:{flexShrink:0,border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",cursor:"pointer",fontSize:11,padding:"1px 6px"},children:"History"})]}),o.jsxs("div",{style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0},children:[o.jsx(pp,{cwd:i,open:dt,reattach:Ps,sessionId:t,onSessionId:oe=>void l.setSession(e,oe),agentMode:D!=null,portal:D!=null?v:void 0,refitSignal:l.layoutVersion},`${e}-${D??"plain"}-${fe}`),!E&&BA(D!=null,!!y,A)&&o.jsx("div",{"data-testid":"write-portal-overlay",role:"status","aria-live":"polite",style:{position:"absolute",inset:0,zIndex:Ki.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.45)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:o.jsx("span",{style:{background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"6px 12px"},children:"Un agent est en train de parler…"})}),!E&&D!=null&&o.jsx(ZP,{projectId:c,agentId:D}),E&&o.jsx("div",{"data-testid":"model-server-overlay",role:"status","aria-live":"polite","aria-label":"model server launch",style:{position:"absolute",inset:0,zIndex:Ki.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0,maxWidth:"80%",background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"8px 14px"},children:[o.jsx("span",{children:E}),O&&o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"model-server-progress",role:"progressbar","aria-label":"progression du téléchargement","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":O.percent!=null?Math.round(O.percent):void 0,style:{position:"relative",width:220,maxWidth:"100%",height:6,borderRadius:3,overflow:"hidden",background:"var(--color-raised, #2a2a2a)"},children:o.jsx("div",{style:O.percent!=null?{height:"100%",width:`${O.percent}%`,background:"var(--color-primary, #5b9bd5)",transition:"width 120ms linear"}:{position:"absolute",top:0,bottom:0,width:"40%",background:"var(--color-primary, #5b9bd5)",animation:"model-server-indeterminate 1.1s ease-in-out infinite"}})}),(O.percent!=null||O.bytesLabel)&&o.jsxs("span",{"data-testid":"model-server-progress-label",style:{fontSize:12,color:"var(--color-content-muted, #9a9a9a)"},children:[O.percent!=null?`${Math.round(O.percent)} %`:"",O.percent!=null&&O.bytesLabel?" · ":"",O.bytesLabel??""]}),O.source&&o.jsx("span",{"data-testid":"model-server-source",style:{fontSize:11,color:"var(--color-content-muted, #9a9a9a)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:O.source,children:O.source})]})]})})]}),Y&&o.jsxs("div",{role:"status",style:{position:"absolute",bottom:4,left:4,right:4,margin:0,fontSize:11,color:"var(--color-content-muted, #9a9a9a)",background:"var(--color-surface, #1e1e1e)",padding:"2px 6px",borderRadius:3,zIndex:Ki.banner,display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[o.jsx("span",{style:{minWidth:0},children:Y.message}),Y.goToNodeId&&o.jsx("button",{type:"button","aria-label":"aller à la cellule",onClick:()=>{FA(Y.goToNodeId),ae(null)},style:{flexShrink:0,fontSize:11,cursor:"pointer",background:"transparent",color:"var(--color-primary, #5b9bd5)",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,padding:"1px 6px"},children:"Aller à la cellule"})]}),pe&&o.jsx(xP,{agentWasRunning:s,details:$,onResume:Rn,onNewConversation:Yr})]})}function WA({split:e,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a}){const c=e.direction==="row",u=e.children.map(m=>m.weight),h=g.useRef(null),[d,f]=g.useState(null),p=Bh(d??u);return o.jsx("div",{ref:h,"data-testid":"layout-split","data-direction":e.direction,style:{display:"flex",flexDirection:c?"row":"column",width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.children.map((m,x)=>o.jsxs("div",{style:{display:"contents"},children:[o.jsx("div",{style:{flexBasis:`${p[x]}%`,flexGrow:0,flexShrink:0,minHeight:0,minWidth:0,overflow:"hidden"},children:o.jsx(yp,{node:m.node,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a,parentSplit:{container:e.id,index:x,siblings:e.children.length}})}),xf(tx(u,x,w)),onDragEnd:w=>{const v=tx(u,x,w);f(null),n.resize(e.id,v)}})]},ww(m.node,x)))})}function HA({isRow:e,container:t,onDragMove:n,onDragEnd:r}){const s=g.useRef(null);function i(u){if(s.current===null)return null;const h=t.current?.getBoundingClientRect(),d=h?e?h.width:h.height:0;return d<=0?null:(u-s.current)/d}function l(u){u.preventDefault(),u.currentTarget.setPointerCapture(u.pointerId),s.current=e?u.clientX:u.clientY}function a(u){if(s.current===null)return;const h=i(e?u.clientX:u.clientY);h!==null&&n(h)}function c(u){const h=i(e?u.clientX:u.clientY);s.current=null,h!==null&&r(h)}return o.jsx("div",{role:"separator","aria-orientation":e?"vertical":"horizontal",onPointerDown:l,onPointerMove:a,onPointerUp:c,style:{flex:"0 0 6px",cursor:e?"col-resize":"row-resize",background:"#3a3a3a",touchAction:"none"}})}function UA({grid:e,cwd:t,vm:n,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a}){const c=Bh(e.colWeights).map(h=>`${h}fr`).join(" "),u=Bh(e.rowWeights).map(h=>`${h}fr`).join(" ");return o.jsx("div",{"data-testid":"layout-grid-container",style:{display:"grid",gridTemplateColumns:c,gridTemplateRows:u,width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.cells.map((h,d)=>o.jsx("div",{style:{gridColumn:`${h.col+1} / span ${h.colSpan}`,gridRow:`${h.row+1} / span ${h.rowSpan}`,minHeight:0,minWidth:0,overflow:"hidden"},children:o.jsx(yp,{node:h.node,cwd:t,vm:n,parentSplit:null,projectId:r,workState:s,refreshWorkState:i,onOpenConversation:l,onOpenPluginsSettings:a})},ww(h.node,d)))})}function ww(e,t){return e.node.id??String(t)}function gx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function xx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="AGENT_ALREADY_RUNNING"}function Is(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function vx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="NOT_FOUND"}function qA(e){const{layout:t,system:n}=ue(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{if(!(!e||!t))try{const{layouts:w,activeId:v}=await t.listLayouts(e);s(w),l(y=>y&&w.some(_=>_.id===y)?y:v)}catch(w){h(Is(w))}},[t,e]);g.useEffect(()=>{if(!e||!t){s([]),l(null);return}let w=!1;return c(!0),t.listLayouts(e).then(({layouts:v,activeId:y})=>{w||(s(v),l(y))}).catch(v=>{w||h(Is(v))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[t,e]),g.useEffect(()=>{if(!e||!n)return;let w=!1,v;return n.onDomainEvent(y=>{y.type==="layoutChanged"&&y.projectId===e&&d()}).then(y=>{w?y():v=y}),()=>{w=!0,v?.()}},[n,e,d]);const f=g.useCallback(async w=>{if(!(!e||!t)){c(!0),h(null);try{const v=await t.setActiveLayout(e,w);l(v?.activeId??w)}catch(v){h(Is(v))}finally{c(!1)}}},[t,e]),p=g.useCallback(async(w,v)=>{if(!e||!t)return null;c(!0),h(null);try{const{layoutId:y}=await t.createLayout(e,w,v),_=await t.listLayouts(e);return s(_.layouts),y}catch(y){return h(Is(y)),null}finally{c(!1)}},[t,e]),m=g.useCallback(async(w,v)=>{if(!(!e||!t)){c(!0),h(null);try{await t.renameLayout(e,w,v),s(y=>y.map(_=>_.id===w?{..._,name:v}:_))}catch(y){vx(y)?await d():h(Is(y))}finally{c(!1)}}},[t,e,d]),x=g.useCallback(async w=>{if(!(!e||!t)){if(r.length<=1){h("Cannot delete the last layout.");return}c(!0),h(null);try{const{activeId:v}=await t.deleteLayout(e,w);s(y=>y.filter(_=>_.id!==w)),l(v)}catch(v){vx(v)?await d():h(Is(v))}finally{c(!1)}}},[t,e,r.length,d]);return{layouts:r,activeId:i,busy:a,error:u,setActive:f,create:p,rename:m,deleteLayout:x}}function KA({projectId:e,onActiveLayoutChange:t}){const n=qA(e);g.useEffect(()=>{const y=n.layouts.find(_=>_.id===n.activeId);y&&t(y)},[n.activeId,n.layouts,t]);const[r,s]=g.useState(null),[i,l]=g.useState(""),a=g.useRef(null),[c,u]=g.useState(!1),{registry:h}=vp(),[d,f]=g.useState(null);async function p(y){await n.setActive(y)}async function m(y){n.layouts.length<=1||await n.deleteLayout(y)}function x(y,_){s(y),l(_),setTimeout(()=>a.current?.focus(),0)}async function w(){if(!r)return;const y=i.trim();y&&await n.rename(r,y),s(null),l("")}async function v(y){u(!1);const _=y==="gitGraph"?"Git Graph":"Layout",b=window.prompt("New layout name:",_);if(!b?.trim())return;const j=await n.create(b.trim(),y);j&&await n.setActive(j)}return n.layouts.length===0?null:o.jsxs("div",{"data-testid":"layout-tabs",className:"flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",children:[n.layouts.map(y=>{const _=y.id===n.activeId,b=y.id===r;return o.jsxs("div",{className:U("group flex items-center gap-1 rounded-md border px-1 transition-colors",_?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[b?o.jsx("input",{ref:a,value:i,onChange:j=>l(j.target.value),onBlur:()=>void w(),onKeyDown:j=>{j.key==="Enter"&&w(),j.key==="Escape"&&(s(null),l(""))},"aria-label":`rename layout ${y.name}`,className:"w-24 rounded border border-border bg-base px-1 py-0.5 text-sm text-content focus:outline-none focus:ring-1 focus:ring-primary"}):o.jsxs("button",{type:"button",role:"tab","aria-selected":_,onClick:()=>void p(y.id),onDoubleClick:()=>x(y.id,y.name),className:U("flex items-center gap-1 px-2 py-1 text-sm focus-visible:outline-none",_?"font-semibold text-content":"text-muted hover:text-content"),children:[y.kind==="gitGraph"&&o.jsx("span",{"aria-label":"git graph layout",className:"text-xs text-primary",title:"Git Graph",children:"⎇"}),y.name]}),o.jsx("button",{type:"button","aria-label":`delete layout ${y.name}`,disabled:n.layouts.length<=1,onClick:()=>void m(y.id),className:U("flex h-4 w-4 items-center justify-center rounded text-xs transition-opacity",n.layouts.length<=1?"cursor-not-allowed opacity-20":"opacity-60 hover:opacity-100 group-hover:opacity-100"),children:"×"})]},y.id)}),o.jsxs("div",{className:"relative",children:[o.jsx("button",{type:"button","aria-label":"create layout",onClick:()=>u(y=>!y),className:"flex h-6 w-6 items-center justify-center rounded border border-transparent text-sm text-muted transition-colors hover:border-border hover:text-content",children:"+"}),c&&o.jsxs("div",{role:"menu",className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col rounded-md border border-border bg-surface shadow-lg",children:[o.jsx("button",{type:"button",role:"menuitem","aria-label":"create terminal layout",onClick:()=>void v("terminal"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"Terminal"}),o.jsx("button",{type:"button",role:"menuitem","aria-label":"create git graph layout",onClick:()=>void v("gitGraph"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"⎇ Git graph"}),o.jsx(CA,{registry:h,onSelect:y=>{u(!1),f(`« ${y.layout.label} » (${y.pluginDisplayName}) : la création de layouts plugins nécessite une extension backend pas encore livrée.`)}})]})]}),(n.error||d)&&o.jsx("span",{className:"ml-2 text-xs text-danger",role:"alert",children:n.error??d})]})}class VA extends g.Component{constructor(){super(...arguments);X(this,"state",{error:null,retryKey:0});X(this,"retry",()=>{this.setState(({retryKey:n})=>({error:null,retryKey:n+1}))})}static getDerivedStateFromError(n){return{error:n}}render(){return this.state.error?o.jsx(ke,{title:"Work",children:o.jsxs("div",{role:"alert",className:"rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[o.jsx("p",{className:"font-medium",children:"Work panel failed to render."}),o.jsx("p",{className:"mt-1 text-xs text-danger/80",children:this.state.error.message}),o.jsx(M,{size:"sm",variant:"ghost",className:"mt-2",onClick:this.retry,children:"Retry"})]})}):o.jsx("div",{children:this.props.children},this.state.retryKey)}}function cr(e){return e.length<=8?e:e.slice(0,8)}function GA(e){return e==="inProgress"?"In progress":"Queued"}function YA(e){switch(e){case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed";case"cancelled":return"Cancelled";case"delivered":return"Delivered";case"pending":return"Pending"}}function XA(e){return e==="completed"||e==="failed"||e==="cancelled"}function QA(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function JA(e){if(e.source.kind==="human")return"Human";const t=cr(e.source.agentId);return e.requesterLabel.trim()?`${e.requesterLabel} (${t})`:`Agent ${t}`}function ZA(e){switch(e){case"ready":return"Summary";case"missing":return"No summary";case"partial":return"Partial";case"unavailable":return"Unavailable"}}function eT(e){if(e.objectivePreview)return`Goal: ${e.objectivePreview}`;if(e.summaryPreview)return e.summaryPreview;const t=(e.recentTurns??[]).at(-1);return t?`Last: ${t.textPreview}`:null}function yx(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}async function tT(e){if(typeof navigator<"u"&&navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}throw new Error("Clipboard unavailable")}function nT({summary:e,onOpenConversation:t}){const n=eT(e),[r,s]=g.useState(!1),[i,l]=g.useState(!1);return n?o.jsxs("div",{className:"mt-1 min-w-0 pl-1 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="ready"?"bg-success/10 text-success":"bg-raised text-muted"),children:ZA(e.status)}),t?o.jsx("button",{type:"button","aria-label":`open conversation ${e.conversationId}`,className:"min-w-0 flex-1 break-words text-left hover:text-content hover:underline",onClick:()=>t(e.conversationId),children:n}):o.jsx("span",{className:"min-w-0 flex-1 break-words",children:n}),o.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content",onClick:()=>s(a=>!a),children:r?"Hide":"View"}),o.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content disabled:opacity-50",disabled:!n,onClick:()=>{tT(n).then(()=>{l(!0),window.setTimeout(()=>l(!1),1e3)})},children:i?"Copied":"Copy"})]}),r&&o.jsxs("div",{"aria-label":`conversation ${e.conversationId} details`,className:"mt-1 space-y-1 border-l border-border pl-2",children:[e.objectivePreview&&o.jsxs("p",{children:[o.jsx("span",{className:"font-medium text-content",children:"Goal:"})," ",e.objectivePreview]}),e.summaryPreview&&o.jsxs("p",{children:[o.jsx("span",{className:"font-medium text-content",children:"Summary:"})," ",e.summaryPreview]}),(e.recentTurns??[]).length>0&&o.jsx("ul",{className:"space-y-0.5",children:(e.recentTurns??[]).map(a=>o.jsxs("li",{children:[o.jsxs("span",{className:"font-medium text-content",children:[a.role,":"]})," ",a.textPreview]},`${a.atMs}-${a.role}-${a.textPreview}`))})]})]}):null}function rT({ticket:e,summary:t,onOpenConversation:n}){const r=e.taskLen>e.taskPreview.length;return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsxs("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="inProgress"?"bg-warning/15 text-warning":"bg-raised text-muted"),children:["#",e.position+1," ",GA(e.status)]}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"font-medium text-content",children:JA(e)}),o.jsx("span",{className:"text-muted",children:" · "}),o.jsx("span",{className:"break-words",children:e.taskPreview}),r&&o.jsxs("span",{"aria-label":`${e.taskLen-e.taskPreview.length} more characters`,className:"text-muted",children:[" ","+",e.taskLen-e.taskPreview.length]})]}),o.jsx("code",{"aria-label":`ticket ${cr(e.ticketId)}`,title:e.ticketId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.ticketId)})]}),t&&o.jsx(nT,{summary:t,onOpenConversation:n})]})}function sT({item:e}){return o.jsx("li",{className:"min-w-0 text-xs text-muted",children:o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium text-muted",children:e.kind}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:e.body}),o.jsx("code",{title:e.id,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.id)})]})})}function iT({task:e,onRefresh:t}){const{workState:n}=ue(),[r,s]=g.useState(!1),[i,l]=g.useState(!1),[a,c]=g.useState(null),u=!!(e.stdoutTail||e.stderrTail),h=e.status==="running"||e.status==="pending",d=e.status==="failed"||e.status==="cancelled";async function f(p){l(!0),c(null);try{await p(e.taskId),await t()}catch(m){c(m instanceof Error?m.message:String(m))}finally{l(!1)}}return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[o.jsx("span",{className:U("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",QA(e.status)),children:YA(e.status)}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"font-medium text-content",children:e.kind}),e.exitCode!==null&&o.jsxs("span",{className:"text-muted",children:[" · exit ",e.exitCode]})]}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!h||i,loading:i,onClick:()=>void f(p=>n.cancelBackgroundTask(p)),children:"Cancel"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!u,onClick:()=>s(p=>!p),children:"Output"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!d||i,loading:i,onClick:()=>void f(p=>n.retryBackgroundTask(p)),children:"Retry"}),o.jsx("code",{title:e.taskId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.taskId)})]}),e.summary&&XA(e.status)&&o.jsx("p",{"aria-label":`task ${cr(e.taskId)} summary`,title:e.summary,className:"mt-1 truncate pl-1 text-[11px] text-muted",children:e.summary}),a&&o.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:a}),r&&u&&o.jsxs("pre",{"aria-label":`task ${cr(e.taskId)} output`,className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-canvas p-2 text-[11px] text-muted",children:[e.stdoutTail?`stdout -${e.stdoutTail}`:"",e.stdoutTail&&e.stderrTail?` - -`:"",e.stderrTail?`stderr -${e.stderrTail}`:""]})]})}function lT({agent:e,conversations:t,visibleLeaves:n,layout:r,projectId:s,onRefresh:i,onOpenConversation:l}){const{agent:a}=ue(),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=e.live!==void 0,p=e.busy??{state:"idle"},m=p.state==="busy",x=[...e.tickets??[]].sort((k,R)=>k.position-R.position),w=[...e.inbox??[]].sort((k,R)=>k.createdAtMs-R.createdAtMs),v=[...e.backgroundTasks??[]].sort((k,R)=>R.updatedAtMs-k.updatedAtMs||k.taskId.localeCompare(R.taskId)),y=Math.max(e.inboxDepth??0,w.length,x.length),_=new Set(n.map(k=>k.id)),b=f&&_.has(e.live.nodeId),j=n.find(k=>!k.session&&!k.agent),S=m||x.some(k=>k.status==="inProgress");async function N(){await i()}async function D(){if(!(!e.live||!j||!a?.attachLiveAgent)){d(!0),u(null);try{const k=await a.attachLiveAgent(s,e.agentId,j.id);await r.attachLiveAgentToCell(j.id,e.agentId,k.sessionId),await N(),yx(j.id)}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!1)}}}async function A(){if(!e.live||!a?.stopLiveAgent)return;const k=S?" The current turn will be interrupted.":"";if(window.confirm(`Stop ${e.name}?${k}`)){d(!0),u(null);try{const R=await a.stopLiveAgent(s,e.agentId);if(_.has(e.live.nodeId)){const T=n.find(E=>E.id===e.live?.nodeId);(!T?.session||T.session===R.sessionId)&&await r.setSession(e.live.nodeId,null)}await N()}catch(R){u(R instanceof Error?R.message:String(R))}finally{d(!1)}}}return o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),o.jsx("code",{className:"truncate text-xs text-muted",children:e.profileId})]}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx("span",{className:U("rounded-full px-2 py-0.5 text-xs font-medium",f?"bg-success/15 text-success":"bg-raised text-muted"),children:f?"Live":"Offline"}),o.jsx("span",{className:U("rounded-full px-2 py-0.5 text-xs font-medium",m?"bg-warning/15 text-warning":"bg-raised text-muted"),children:m?"Busy":"Idle"}),y>0&&o.jsxs("span",{"aria-label":`${e.name} queue depth ${y}`,className:"rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary",children:["Queue ",y]}),p.state==="busy"&&o.jsx("code",{"aria-label":`busy ticket ${cr(p.ticket)}`,title:p.ticket,className:"rounded bg-raised px-1.5 py-0.5 text-xs text-muted",children:cr(p.ticket)}),e.live&&b&&o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>yx(e.live.nodeId),children:"Open"}),e.live&&!b&&o.jsx(M,{size:"sm",variant:"ghost",disabled:!j||!a?.attachLiveAgent,loading:h,title:j?void 0:"No empty visible cell available",onClick:()=>void D(),children:"Attach"}),e.live&&o.jsx(M,{size:"sm",variant:"danger",loading:h,disabled:!a?.stopLiveAgent,onClick:()=>void A(),children:"Stop"})]})]}),e.live&&!b&&!j&&o.jsx("p",{className:"mt-1 text-xs text-muted",children:"No empty visible cell."}),c&&o.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:c}),x.length>0&&o.jsx("ul",{"aria-label":`${e.name} tickets`,className:"mt-2 flex flex-col gap-1",children:x.map(k=>o.jsx(rT,{ticket:k,summary:t.get(k.conversationId),onOpenConversation:l},k.ticketId))}),w.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),o.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:w.map(k=>o.jsx(sT,{item:k},k.id))})]}),v.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Background tasks"}),o.jsx("ul",{"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:v.map(k=>o.jsx(iT,{task:k,onRefresh:N},k.taskId))})]})]})}function oT({projectId:e,onOpenConversation:t}){const n=eo(e),r=bw(e),s=n.state?.agents??[],i=r.layout?Za(r.layout):[],l=new Map((n.state?.conversations??[]).map(a=>[a.conversationId,a]));return o.jsxs(ke,{title:"Work",actions:o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),n.busy&&n.state===null?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Loading work state…"})]}):s.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agent work state."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:s.map(a=>o.jsx(lT,{agent:a,conversations:l,visibleLeaves:i,layout:r,projectId:e,onRefresh:n.refresh,onOpenConversation:t},a.agentId))})]})}function aT(e){return o.jsx(VA,{children:o.jsx(oT,{...e})})}function Lu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Du(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function cT(e,t){const{conversation:n}=ue(),[r,s]=g.useState([]),[i,l]=g.useState(!1),[a,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useRef([]),f=g.useRef(!1),p=g.useCallback(v=>{d.current=v,s(v)},[]),m=g.useCallback(async()=>{if(!f.current){f.current=!0,l(!0),c(null);try{const v=await n.readPage(e,t,{direction:"backward"});p(Du(v.turns)),h(v.hasMore)}catch(v){c(Lu(v))}finally{l(!1),f.current=!1}}},[n,e,t,p]),x=g.useCallback(async()=>{if(f.current)return;const v=d.current[0];if(!v){await m();return}f.current=!0,l(!0),c(null);try{const y=await n.readPage(e,t,{direction:"backward",anchor:v.id});y.turns.length>0&&p(Du([...y.turns,...d.current])),h(y.hasMore)}catch(y){c(Lu(y))}finally{l(!1),f.current=!1}},[n,e,t,m,p]),w=g.useCallback(async()=>{if(!f.current){if(d.current.length===0){await m();return}f.current=!0,l(!0),c(null);try{for(;;){const v=d.current.at(-1);if(!v)break;const y=await n.readPage(e,t,{direction:"forward",anchor:v.id});if(y.turns.length===0||(p(Du([...d.current,...y.turns])),!y.hasMore))break}}catch(v){c(Lu(v))}finally{l(!1),f.current=!1}}},[n,e,t,m,p]);return g.useEffect(()=>{p([]),h(!1),m()},[m,p]),{turns:r,busy:i,error:a,hasMore:u,loadOlder:x,refreshTail:w}}function _x(e){return e.length<=8?e:e.slice(0,8)}function Ru(e){return e.kind==="human"?"human":`agent:${e.agentId}`}function uT(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleString()}catch{return""}}function dT(e){switch(e){case"prompt":return"Prompt";case"response":return"Response";case"toolActivity":return"Tool"}}function hT({turn:e,sideClass:t}){const[n,r]=g.useState(!1);return o.jsx("div",{className:U("flex flex-col",t),children:o.jsxs("div",{className:"max-w-[80%] rounded-md border border-border bg-surface/60 px-3 py-1.5 text-xs text-muted",children:[o.jsxs("button",{type:"button",className:"flex items-center gap-1.5 font-medium hover:text-content",onClick:()=>r(s=>!s),"aria-expanded":n,children:[o.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),"Tool activity",o.jsxs("span",{className:"text-faint",children:["· ",e.textLen," chars"]})]}),n&&o.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted",children:e.text})]})})}function fT({projectId:e,conversationId:t,onClose:n}){const r=cT(e,t),s=eo(e),i=g.useMemo(()=>{const u=new Map;for(const h of s.state?.agents??[])h.name.trim()&&u.set(h.agentId,h.name.trim());return u},[s.state]),l=g.useMemo(()=>{const u=[],h=new Map;for(const d of r.turns){const f=Ru(d.source);if(h.has(f))continue;const p=u.length===0?"left":"right",m=d.source.kind==="human"?"User":i.get(d.source.agentId)??`Agent ${_x(d.source.agentId)}`;h.set(f,{label:m,side:p}),u.push(f)}return{order:u,meta:h}},[r.turns,i]),a=g.useMemo(()=>{const u=l.order.map(h=>l.meta.get(h)?.label??"?");return u.length>=2?`${u[0]} ↔ ${u[1]}`:u.length===1?u[0]:"Conversation"},[l]);function c(u){return l.meta.get(Ru(u))?.side??"left"}return o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border bg-surface px-4 py-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:a}),o.jsx("code",{className:"truncate text-xs text-muted",title:t,children:_x(t)})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.refreshTail(),loading:r.busy,children:"Refresh"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"← Retour aux terminaux"})]})]}),r.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),o.jsxs("div",{className:"flex flex-1 flex-col gap-2 overflow-auto px-4 py-3",children:[r.hasMore&&o.jsx("div",{className:"flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.loadOlder(),loading:r.busy,children:"Charger les tours précédents"})}),r.busy&&r.turns.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Chargement du fil…"})]}):r.turns.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun tour pour le moment."}):r.turns.map(u=>{const h=c(u.source),d=h==="right"?"items-end":"items-start";if(u.role==="toolActivity")return o.jsx(hT,{turn:u,sideClass:d},u.id);const f=l.meta.get(Ru(u.source)),p=uT(u.atMs);return o.jsx("div",{className:U("flex flex-col",d),children:o.jsxs("div",{className:U("max-w-[80%] rounded-lg border px-3 py-2 text-sm",h==="right"?"border-primary/20 bg-primary/10 text-content":"border-border bg-raised text-content"),children:[o.jsxs("div",{className:"mb-1 flex items-baseline gap-2 text-xs text-muted",children:[o.jsx("span",{className:"font-medium text-content",children:f?.label??"?"}),o.jsxs("span",{children:["· ",dT(u.role)]}),p&&o.jsxs("span",{className:"text-faint",children:["· ",p]})]}),o.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.text})]})},u.id)})]})]})}function Mu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function pT(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function mT(){const{modelServer:e}=ue(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{l(!0),s(null);try{n(await e.listModelServers())}catch(f){s(Mu(f))}finally{l(!1)}},[e]);g.useEffect(()=>{a()},[a]);const c=g.useCallback(async f=>{l(!0),s(null);try{const p=await e.saveModelServer(f);return n(m=>{const x=m.findIndex(w=>w.id===p.id);if(x>=0){const w=m.slice();return w[x]=p,w}return[...m,p]}),p}catch(p){return s(Mu(p)),null}finally{l(!1)}},[e]),u=g.useCallback(async f=>{l(!0),s(null);try{return await e.deleteModelServer(f),n(p=>p.filter(m=>m.id!==f)),!0}catch(p){return pT(p)==="model_server_in_use"?s("Ce serveur est encore utilisé par un profil : détache-le d'abord (choisis « aucun » ou un autre serveur) avant de le supprimer."):s(Mu(p)),!1}finally{l(!1)}},[e]),h=g.useCallback(async f=>{try{return await e.previewModelServerCommand(f)}catch{return null}},[e]),d=g.useCallback(()=>s(null),[]);return{servers:t,error:r,busy:i,reload:a,save:c,remove:u,preview:h,clearError:d}}function gT(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function xT(e){return e.startsWith("/")||e.startsWith("\\")?!0:/^[a-zA-Z]:[/\\]/.test(e)}function vT(e){if(/\s/.test(e)||e.startsWith("http://")||e.startsWith("https://")||(e.match(/:/g)??[]).length>1)return!1;const[t,n]=e.includes(":")?[e.slice(0,e.indexOf(":")),e.slice(e.indexOf(":")+1)]:[e,void 0];if(n!==void 0&&n.length===0)return!1;const r=t.split("/");return r.length===2&&r[0].length>0&&r[1].length>0}function yT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),gT(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&(t.port="Port must be an integer between 1 and 65535."),e.servedModelName.trim().length===0&&(t.servedModelName="Le nom du modèle est requis."),(e.host.trim().length===0||/\s/.test(e.host))&&(t.host="L'adresse d'écoute est requise et ne doit pas contenir d'espace.");const n=e.modelSource;return n&&(n.type==="localPath"?n.path.trim().length===0?t.modelSource="Le chemin du fichier .gguf est requis.":xT(n.path.trim())||(t.modelSource="Le chemin du fichier doit être absolu."):n.repo.trim().length===0?t.modelSource="Le modèle Hugging Face est requis.":vT(n.repo.trim())||(t.modelSource="Format attendu : auteur/modèle ou auteur/modèle:quant (ex. unsloth/Qwen3.5-9B-GGUF:Q4_K_M).")),e.autoStart&&!n&&(t.modelSource="Le démarrage automatique nécessite une source de modèle."),t}function _T(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`srv-${Math.random().toString(36).slice(2,10)}`}function bT(){return{id:_T(),kind:"llamaCpp",name:"",baseURL:"http://localhost:8080/v1",port:8080,servedModelName:"",host:"127.0.0.1",jinja:!1,args:[],autoStart:!1,stopPolicy:"stopOnAppExit"}}function wT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function ST(e){if(!e)return"";if(e.type==="localPath"){const r=e.path.trim();return r.length===0?"":(r.split(/[/\\]/).pop()??"").replace(/\.gguf$/i,"")}const t=e.repo.trim();return t.length===0?"":(t.includes(":")?t.slice(0,t.indexOf(":")):t).split("/").pop()??""}const kT=["--model","-m","-hf","--port","--host","-ngl","--gpu-layers","-c","--ctx-size","--jinja"];function CT(e){const t=new Set(kT),n=new Set;for(const r of e){const s=r.includes("=")?r.slice(0,r.indexOf("=")):r;t.has(s)&&n.add(s)}return[...n]}function Et({children:e}){return o.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function Os({children:e}){return o.jsx("small",{className:"text-xs text-muted",children:e})}const jT=[{value:"stopOnAppExit",label:"Stop on app exit"},{value:"keepAlive",label:"Keep alive"},{value:"stopWhenUnused",label:"Stop when unused"}];function NT({vm:e}){const[t,n]=g.useState(null);function r(){e.clearError(),n(bT())}function s(l){e.clearError(),n({...l})}async function i(){if(!t)return;await e.save(t)&&n(null)}return o.jsx(ke,{"aria-label":"local model servers",title:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:"Local model servers"}),o.jsx(M,{size:"sm","aria-label":"add model server",onClick:r,className:"ml-auto",children:"Add server"})]}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[e.error&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error}),e.servers.length===0&&!t&&o.jsx("p",{className:"text-xs text-muted",children:"No local server declared yet. Add one to auto-manage a `llama-server`, or keep using an external endpoint."}),o.jsx("ul",{className:"flex list-none flex-col gap-2 p-0",children:e.servers.map(l=>o.jsxs("li",{className:"flex items-center gap-2 rounded-md border border-border bg-raised p-2",children:[o.jsxs("span",{className:"flex min-w-0 flex-col",children:[o.jsx("strong",{className:"truncate text-sm text-content",children:l.name}),o.jsxs("span",{className:"truncate text-xs text-muted",children:[l.baseURL," · ",l.servedModelName,l.autoStart?" · auto-start":""]})]}),o.jsxs("span",{className:"ml-auto flex items-center gap-1",children:[o.jsx(M,{size:"sm","aria-label":`edit ${l.name}`,onClick:()=>s(l),disabled:e.busy,children:"Edit"}),o.jsx(Hn,{size:"sm","aria-label":`delete ${l.name}`,onClick:()=>void e.remove(l.id),disabled:e.busy,children:"×"})]})]},l.id))}),t&&o.jsx(AT,{draft:t,busy:e.busy,preview:e.preview,onChange:n,onCancel:()=>{e.clearError(),n(null)},onSubmit:()=>void i()})]})})}function ET({kind:e,onSelect:t}){const n=(r,s)=>{const i=e===r;return o.jsx("button",{type:"button","aria-pressed":i,onClick:()=>t(r),className:U("h-8 flex-1 rounded-md px-3 text-xs font-medium transition-colors",i?"bg-primary text-white":"bg-raised text-muted hover:text-content"),children:s})};return o.jsxs("div",{role:"group","aria-label":"source du modèle",className:"flex gap-1 rounded-md border border-border p-1",children:[n("huggingFace","Télécharger depuis Hugging Face"),n("localPath","Fichier .gguf local")]})}function PT({preview:e,autoStart:t}){const[n,r]=g.useState(!1),s=t?"Commande générée":"Commande à lancer manuellement";async function i(){if(e)try{await navigator.clipboard.writeText(e.display),r(!0),setTimeout(()=>r(!1),1500)}catch{}}return o.jsxs("section",{"aria-label":"command preview",className:"flex flex-col gap-1 rounded-md border border-border bg-raised p-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Et,{children:s}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"copier la commande",onClick:()=>void i(),disabled:!e,className:"ml-auto",children:n?"Copié":"Copier"})]}),e?o.jsx("code",{"aria-label":"preview command line",className:"whitespace-pre-wrap break-all font-mono text-xs text-content",children:e.display}):o.jsx("span",{className:"text-xs text-muted",children:"Renseigne une source de modèle pour voir la commande."})]})}function AT({draft:e,busy:t,preview:n,onChange:r,onCancel:s,onSubmit:i}){const l=yT(e),a=Object.keys(l).length===0,c=b=>r({...e,...b}),[u,h]=g.useState(e.modelSource?.type??"huggingFace"),d=e.modelSource?.type==="huggingFace"?e.modelSource.repo:"",f=e.modelSource?.type==="localPath"?e.modelSource.path:"";function p(b){const j={modelSource:b};if(e.servedModelName.trim().length===0){const S=ST(b);S.length>0&&(j.servedModelName=S)}c(j)}function m(b){b!==u&&(h(b),c({modelSource:void 0}))}const[x,w]=g.useState(null),v=JSON.stringify({modelSource:e.modelSource,port:e.port,host:e.host,gpuLayers:e.gpuLayers,contextSize:e.contextSize,jinja:e.jinja,binaryPath:e.binaryPath,args:e.args}),y=g.useRef(e);y.current=e,g.useEffect(()=>{if(!e.modelSource){w(null);return}let b=!1;const j=setTimeout(()=>{n(y.current).then(S=>{b||w(S)})},250);return()=>{b=!0,clearTimeout(j)}},[v,n]);const _=CT(e.args);return o.jsxs("fieldset",{"aria-label":"model server editor",className:"flex flex-col gap-3 rounded-md border border-primary/40 p-3",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:e.name.trim().length>0?e.name:"New server"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Nom"}),o.jsx(ie,{"aria-label":"server name",value:e.name,invalid:!!l.name,onChange:b=>c({name:b.target.value})}),l.name&&o.jsx("small",{className:"text-xs text-danger",children:l.name})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Source du modèle"}),o.jsx(ET,{kind:u,onSelect:m})]}),u==="huggingFace"?o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Modèle Hugging Face"}),o.jsx(ie,{"aria-label":"hugging face model",value:d,placeholder:"unsloth/Qwen3.5-9B-GGUF:Q4_K_M",invalid:!!l.modelSource,onChange:b=>{const j=b.target.value;p(j.trim().length===0?void 0:{type:"huggingFace",repo:j})}}),o.jsx(Os,{children:"llama.cpp téléchargera/cache le fichier automatiquement."}),l.modelSource&&o.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}):o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Fichier .gguf"}),o.jsx(ie,{"aria-label":"local gguf file",value:f,placeholder:"/home/me/models/qwen.gguf",invalid:!!l.modelSource,onChange:b=>{const j=b.target.value;p(j.trim().length===0?void 0:{type:"localPath",path:j})}}),o.jsx(Os,{children:"Chemin absolu vers un .gguf déjà présent."}),l.modelSource&&o.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Nom du modèle dans IdeA"}),o.jsx(ie,{"aria-label":"server served model name",value:e.servedModelName,placeholder:"qwen3-coder-30b",invalid:!!l.servedModelName,onChange:b=>c({servedModelName:b.target.value})}),o.jsx(Os,{children:"Nom envoyé aux clients OpenAI-compatible."}),l.servedModelName&&o.jsx("small",{className:"text-xs text-danger",children:l.servedModelName})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[12rem] flex-1 flex-col gap-1",children:[o.jsx(Et,{children:"Commande serveur"}),o.jsx(ie,{"aria-label":"server binary path",value:e.binaryPath??"",placeholder:"llama-server",onChange:b=>{const j=b.target.value;c({binaryPath:j.length===0?void 0:j})}}),o.jsx(Os,{children:"Laisse vide pour résoudre `llama-server` via le PATH."})]}),o.jsxs("label",{className:"flex min-w-[6rem] flex-col gap-1",children:[o.jsx(Et,{children:"Port"}),o.jsx(ie,{"aria-label":"server port",value:Number.isNaN(e.port)?"":e.port.toString(),inputMode:"numeric",invalid:!!l.port,onChange:b=>c({port:Number.parseInt(b.target.value,10)})}),l.port&&o.jsx("small",{className:"text-xs text-danger",children:l.port})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Base URL (OpenAI-compatible)"}),o.jsx(ie,{"aria-label":"server base url",value:e.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!l.baseURL,onChange:b=>c({baseURL:b.target.value})}),l.baseURL&&o.jsx("small",{className:"text-xs text-danger",children:l.baseURL})]}),o.jsxs("label",{className:"flex items-start gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":"server auto start",checked:e.autoStart,disabled:!e.modelSource,onChange:b=>c({autoStart:b.target.checked}),className:"mt-1 accent-primary disabled:opacity-50"}),o.jsxs("span",{className:"flex flex-col",children:[o.jsx(Et,{children:"Démarrer automatiquement"}),!e.modelSource&&o.jsx(Os,{children:"Renseigne d'abord une source de modèle pour l'activer."})]})]}),o.jsxs("details",{className:"rounded-md border border-border p-2",children:[o.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted",children:"Réglages llama.cpp"}),o.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsxs(Et,{children:["Couches GPU ",o.jsx("span",{className:"text-muted",children:"(-ngl)"})]}),o.jsx(ie,{"aria-label":"gpu layers",value:e.gpuLayers===void 0?"":String(e.gpuLayers),inputMode:"numeric",placeholder:"99",onChange:b=>{const j=b.target.value.trim();c({gpuLayers:j.length===0?void 0:Number.parseInt(j,10)})}}),o.jsx(Os,{children:"0 = CPU seul."})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsxs(Et,{children:["Taille de contexte ",o.jsx("span",{className:"text-muted",children:"(-c)"})]}),o.jsx(ie,{"aria-label":"context size",value:e.contextSize===void 0?"":String(e.contextSize),inputMode:"numeric",placeholder:"16384",onChange:b=>{const j=b.target.value.trim();c({contextSize:j.length===0?void 0:Number.parseInt(j,10)})}})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsxs(Et,{children:["Adresse d'écoute ",o.jsx("span",{className:"text-muted",children:"(--host)"})]}),o.jsx(ie,{"aria-label":"listen host",value:e.host,placeholder:"127.0.0.1",invalid:!!l.host,onChange:b=>c({host:b.target.value})}),l.host&&o.jsx("small",{className:"text-xs text-danger",children:l.host})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":"jinja template",checked:e.jinja,onChange:b=>c({jinja:b.target.checked}),className:"accent-primary"}),o.jsxs(Et,{children:["Template chat Jinja ",o.jsx("span",{className:"text-muted",children:"(--jinja)"})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Et,{children:"Arguments supplémentaires"}),o.jsx(ie,{"aria-label":"extra arguments",value:e.args.join(" "),placeholder:"--flash-attn --parallel 2",onChange:b=>c({args:wT(b.target.value)})}),_.length>0&&o.jsxs("small",{className:"text-xs text-warning",role:"status",children:[_.join(", ")," : cette option est déjà pilotée par un champ ci-dessus."]})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx(Et,{children:"Stop policy"}),o.jsx("select",{"aria-label":"server stop policy",value:e.stopPolicy,onChange:b=>c({stopPolicy:b.target.value}),className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:jT.map(b=>o.jsx("option",{value:b.value,children:b.label},b.value))})]})]})]}),o.jsx(PT,{preview:x,autoStart:e.autoStart}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{variant:"primary",size:"sm","aria-label":"save model server",onClick:i,disabled:t||!a,children:"Save server"}),o.jsx(M,{variant:"ghost",size:"sm","aria-label":"cancel model server",onClick:s,disabled:t,children:"Cancel"})]})]})}const Iu="";function TT({servers:e,value:t,onChange:n,ariaLabel:r="local model server"}){const s=t!==void 0&&!e.some(i=>i.id===t);return o.jsxs("select",{"aria-label":r,value:t??Iu,onChange:i=>n(i.target.value===Iu?void 0:i.target.value),className:U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:[o.jsx("option",{value:Iu,children:"None (external endpoint)"}),e.map(i=>o.jsxs("option",{value:i.id,children:[i.name," — ",i.servedModelName]},i.id)),s&&o.jsxs("option",{value:t,children:[t," (unknown / removed)"]})]})}function LT({mode:e,configured:t,references:n}){if(e==="firstRun")return n.map(l=>({profile:l,selected:!1,available:null}));const r=new Set(t.map(l=>l.id)),s=t.map(l=>({profile:l,selected:!0,available:null})),i=n.filter(l=>!r.has(l.id)).map(l=>({profile:l,selected:!1,available:null}));return[...s,...i]}const DT=3e3;function Mo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function RT(e="firstRun"){const{profile:t}=ue(),[n,r]=g.useState(null),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),f=g.useRef(0),p=g.useRef(null);g.useEffect(()=>()=>{f.current+=1,p.current!==null&&clearTimeout(p.current)},[]);const m=g.useCallback(async(S,N)=>{const D=f.current+1;f.current=D;const A=()=>f.current!==D;d(!0),p.current!==null&&clearTimeout(p.current),p.current=setTimeout(()=>{A()||d(!1)},DT);try{const k=await t.detectProfiles(S);if(A())return;const R=new Map(k.map(T=>[T.profile.id,T.available]));i(T=>T.map(E=>{const O=R.get(E.profile.id)??E.available;return{...E,available:O,selected:N.preselect?O===!0:E.selected}}))}catch(k){if(A())return;N.reportError&&a(Mo(k))}finally{A()||(p.current!==null&&clearTimeout(p.current),p.current=null,d(!1))}},[t]),x=g.useCallback(async()=>{u(!0),a(null);let S=null;try{const[N,D]=await Promise.all([t.firstRunState(),e==="edit"?t.listProfiles():Promise.resolve([])]);r(N.isFirstRun);const A=LT({mode:e,configured:D,references:N.referenceProfiles});S=A.map(k=>k.profile),i(A)}catch(N){a(Mo(N)),r(!1)}finally{u(!1)}S!==null&&m(S,{preselect:e==="firstRun",reportError:!1})},[t,m,e]);g.useEffect(()=>{x()},[x]);const w=g.useCallback(S=>{i(N=>N.map(D=>D.profile.id===S?{...D,selected:!D.selected}:D))},[]),v=g.useCallback((S,N)=>{i(D=>D.map(A=>A.profile.id===S?{...A,profile:N}:A))},[]),y=g.useCallback(async S=>{a(null);try{const N=await t.cloneOpenCodeProfileFromSeed(S);i(D=>[...D,{profile:N,selected:!0,available:null}])}catch(N){a(Mo(N))}},[t]),_=g.useCallback(S=>{i(N=>N.filter(D=>D.profile.id!==S))},[]),b=g.useCallback(async()=>{a(null),await m(s.map(S=>S.profile),{preselect:!1,reportError:!0})},[m,s]),j=g.useCallback(async()=>{u(!0),a(null);try{const S=s.filter(N=>N.selected).map(N=>N.profile);await t.configureProfiles(S),r(!1)}catch(S){a(Mo(S))}finally{u(!1)}},[t,s]);return{isFirstRun:n,entries:s,error:l,busy:c,detecting:h,toggle:w,updateProfile:v,addOpenCodeProfile:y,remove:_,detect:b,finish:j,reload:x}}function MT(e){return e.length===0||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:/.test(e)?!1:!e.split(/[/\\]/).includes("..")}function Sw(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function kw(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function Ou(e,t){return e===void 0?!0:Number.isInteger(e)&&e>0&&e<=t}const bx=4294967295,IT=65535;function OT(e){const t={};return kw(e.endpoint)||(t.endpoint="Endpoint must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),e.apiKeyEnv!==void 0&&e.apiKeyEnv.length>0&&!Sw(e.apiKeyEnv)&&(t.apiKeyEnv="Must be a valid env var name (not the key itself)."),Ou(e.requestTimeoutMs,bx)||(t.requestTimeoutMs="Must be a positive integer (ms)."),Ou(e.connectTimeoutMs,bx)||(t.connectTimeoutMs="Must be a positive integer (ms)."),Ou(e.maxToolIterations,IT)||(t.maxToolIterations="Must be a positive integer."),t}function BT(e){const t={};return kw(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),t}function zT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),e.command.trim().length===0&&(t.command="Command is required.");const n=e.contextInjection;return n.strategy==="conventionFile"?MT(n.target)||(t.target="Target must be a relative file name (no .. or absolute)."):n.strategy==="flag"?n.flag.trim().length===0&&(t.flag="Flag is required."):n.strategy==="env"&&(Sw(n.var)||(t.var="Must be a valid env var identifier.")),e.structuredAdapter==="openAiCompatible"&&(e.chatHttp?Object.assign(t,OT(e.chatHttp)):(t.endpoint="Endpoint must start with http:// or https://.",t.model="Model is required.")),e.structuredAdapter==="openCode"&&!e.opencodeProvider&&(e.opencode?Object.assign(t,BT(e.opencode)):(t.baseURL="Base URL must start with http:// or https://.",t.model="Model is required.")),t}function FT(){return{endpoint:"http://localhost:11434/v1",model:"qwen2.5-coder",requestTimeoutMs:12e4,connectTimeoutMs:5e3,maxToolIterations:16}}function $T(){return{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}function WT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function Ae({children:e}){return o.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function to(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function HT(){const{profile:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useCallback(async()=>{s(!0),l(null);try{n(await e.listOpenCodeProviders())}catch(c){n(null),l(to(c))}finally{s(!1)}},[e]);return g.useEffect(()=>{a()},[a]),{providers:t,loading:r,error:i,reload:()=>void a()}}function UT(){const{profile:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useCallback(async()=>{s(!0),l(null);try{n(await e.listCodexProviders())}catch(c){n(null),l(to(c))}finally{s(!1)}},[e]);return g.useEffect(()=>{a()},[a]),{providers:t,loading:r,error:i,reload:()=>void a()}}function qT(){const{profile:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useCallback(async()=>{s(!0),l(null);try{n(await e.listClaudeProviders())}catch(c){n(null),l(to(c))}finally{s(!1)}},[e]);return g.useEffect(()=>{a()},[a]),{providers:t,loading:r,error:i,reload:()=>void a()}}function Cw({onDone:e,forceOpen:t=!1}){const n=RT(t?"edit":"firstRun"),r=mT(),s=HT(),i=UT(),l=qT();if(n.isFirstRun===null||!t&&n.isFirstRun===!1)return null;async function a(){await n.finish(),e?.()}return o.jsx(ke,{"aria-label":"first run setup",className:"border-primary/40",title:o.jsxs("div",{className:"flex flex-col",children:[o.jsx("h2",{className:"text-base font-semibold text-content",children:"Welcome to IdeA"}),o.jsx("p",{className:"text-sm text-muted",children:"Choose which AI CLIs to configure. Commands are pre-filled and editable."})]}),children:o.jsxs("div",{className:"flex flex-col gap-4",children:[n.error&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),o.jsxs(xw,{children:[o.jsx(M,{onClick:()=>void n.detect(),disabled:n.busy,className:"whitespace-nowrap",children:"Detect installed CLIs"}),n.detecting&&o.jsx("span",{role:"status",className:"text-xs text-muted",children:"Detecting…"}),o.jsx(M,{onClick:()=>void n.addOpenCodeProfile(),disabled:n.busy,className:"whitespace-nowrap",children:"Add OpenCode profile"})]}),o.jsx(NT,{vm:r}),o.jsx("ul",{className:"flex list-none flex-col gap-3 p-0",children:n.entries.map(c=>o.jsx(KT,{entry:c,servers:r.servers,providerCatalog:s,codexProviderCatalog:i,claudeProviderCatalog:l,onToggle:()=>n.toggle(c.profile.id),onChange:u=>n.updateProfile(c.profile.id,u),onRemove:()=>n.remove(c.profile.id),onDuplicate:c.profile.structuredAdapter==="openCode"?()=>n.addOpenCodeProfile({name:`${c.profile.name} (copy)`,opencode:c.profile.opencode}):void 0},c.profile.id))}),o.jsx("footer",{className:"flex gap-2",children:o.jsx(M,{variant:"primary",onClick:()=>void a(),disabled:n.busy,children:"Save and continue"})})]})})}function KT({entry:e,servers:t,providerCatalog:n,codexProviderCatalog:r,claudeProviderCatalog:s,onToggle:i,onChange:l,onRemove:a,onDuplicate:c}){const{profile:u,selected:h,available:d}=e,f=zT(u),p=u.structuredAdapter==="openCode";return o.jsxs("li",{className:"flex flex-col gap-2 rounded-md border border-border bg-raised p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",checked:h,onChange:i,"aria-label":`use ${u.name}`,className:"accent-primary"}),o.jsx("strong",{className:"text-sm text-content",children:u.name})]}),o.jsx("span",{"aria-label":`${u.name} availability`,className:U("text-xs",d===null?"text-faint":d?"text-success":"text-danger"),children:d===null?"—":d?"✓ installed":"✗ not found"}),o.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[c&&o.jsx(M,{size:"sm","aria-label":`duplicate ${u.name}`,onClick:c,children:"Duplicate"}),o.jsx(Hn,{size:"sm","aria-label":`remove ${u.name}`,onClick:a,children:"×"})]})]}),p&&o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Name"}),o.jsx(ie,{"aria-label":`${u.name} name`,value:u.name,invalid:!!f.name,onChange:m=>l({...u,name:m.target.value})}),f.name&&o.jsx("small",{className:"text-xs text-danger",children:f.name})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Command"}),o.jsx(ie,{"aria-label":`${u.name} command`,value:u.command,invalid:!!f.command,onChange:m=>l({...u,command:m.target.value})}),f.command&&o.jsx("small",{className:"text-xs text-danger",children:f.command})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Arguments"}),o.jsx(ie,{"aria-label":`${u.name} args`,value:u.args.join(" "),onChange:m=>l({...u,args:WT(m.target.value)})})]}),u.structuredAdapter==="openAiCompatible"&&o.jsx(JT,{profile:u,errors:f,onChange:l}),u.structuredAdapter==="openCode"&&o.jsx(VT,{profile:u,errors:f,servers:t,providerCatalog:n,onChange:l}),u.structuredAdapter==="codex"&&(h||u.codexProvider)&&o.jsx(YT,{profile:u,catalog:r,onChange:l}),u.structuredAdapter==="claude"&&(h||u.claudeProvider)&&o.jsx(XT,{profile:u,catalog:s,onChange:l})]})}function VT({profile:e,errors:t,servers:n,providerCatalog:r,onChange:s}){const[i,l]=g.useState(e.opencodeProvider?"cloud":"local");return o.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[o.jsx("div",{role:"radiogroup","aria-label":"mode du profil OpenCode",className:"flex w-fit gap-1 rounded-md border border-border bg-raised p-0.5",children:[{id:"local",label:"Local (llama.cpp)"},{id:"cloud",label:"Provider cloud"}].map(a=>{const c=i===a.id;return o.jsx("button",{type:"button",role:"radio","aria-checked":c,onClick:()=>l(a.id),className:U("rounded px-2.5 py-1 text-xs font-medium transition-colors",c?"bg-primary text-on-primary":"text-muted hover:text-content"),children:a.label},a.id)})}),i==="local"&&o.jsx(QT,{profile:e,errors:t,servers:n,onChange:s}),i==="cloud"&&o.jsx(GT,{profile:e,catalog:r,onChange:s})]})}const nc="__custom__",wx="@ai-sdk/openai-compatible";function GT({profile:e,catalog:t,onChange:n}){const{profile:r}=ue(),s=e.opencodeProvider,[i,l]=g.useState(s?.custom?"custom":"catalog"),[a,c]=g.useState(s?.providerId??""),[u,h]=g.useState(s?.model??""),[d,f]=g.useState(""),[p,m]=g.useState(s?.custom?.npm??wx),[x,w]=g.useState(s?.custom?.baseUrl??""),[v,y]=g.useState(s?.custom?.displayName??""),[_,b]=g.useState(""),[j,S]=g.useState(!1),[N,D]=g.useState(!1),[A,k]=g.useState(null),[R,T]=g.useState({}),E=s!==void 0,O=t.providers?.find(z=>z.providerId===a)?.models??[],I=t.providers!==null&&!t.loading,W=(t.providers??[]).filter(z=>{if(z.providerId===a)return!0;const C=d.trim().toLowerCase();return C.length===0?!0:z.displayName.toLowerCase().includes(C)||z.providerId.toLowerCase().includes(C)}),G=N||_.length===0||i==="catalog"&&(!I||!!t.error);async function P(){const z={};if(a.trim().length===0&&(z.providerId="Le provider est obligatoire."),u.trim().length===0&&(z.model="Le modèle est obligatoire."),i==="custom"&&(p.trim().length===0&&(z.npm="Le paquet npm est obligatoire."),x.trim().length===0&&(z.baseUrl="L'URL de base est obligatoire.")),_.length===0&&(z.apiKey="La clé API est obligatoire."),T(z),!(Object.keys(z).length>0)){D(!0),k(null);try{const C=await r.saveOpenCodeProviderProfile({profile:e,providerId:a.trim(),model:u.trim(),apiKey:_,...i==="custom"?{custom:{npm:p.trim(),baseUrl:x.trim(),displayName:v.trim().length>0?v.trim():void 0}}:{}});n(C),b("")}catch(C){k(to(C))}finally{D(!1)}}}return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider cloud (OpenCode)"}),A&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:A}),t.loading&&o.jsx("p",{className:"text-xs text-faint",children:"Chargement des providers…"}),t.error&&o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"Impossible de charger la liste des providers cloud."}),o.jsx(M,{size:"sm",onClick:()=>t.reload(),className:"w-fit",children:"Réessayer"})]}),i==="catalog"&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Provider"}),I&&o.jsx("input",{type:"text","aria-label":`${e.name} provider search`,placeholder:"Rechercher un provider…",value:d,onChange:z=>f(z.target.value),className:"h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"}),o.jsxs("select",{"aria-label":`${e.name} provider`,value:a,disabled:!I,onChange:z=>{const C=z.target.value;C===nc?(l("custom"),c(""),h("")):(c(C),h("")),T(Q=>({...Q,providerId:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",R.providerId?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:t.loading?"Chargement des providers…":"Choisir un provider…"}),W.map(z=>o.jsx("option",{value:z.providerId,children:z.displayName},z.providerId)),o.jsx("option",{value:nc,children:"Autre / personnalisé…"})]}),R.providerId&&o.jsx("small",{className:"text-xs text-danger",children:R.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Modèle"}),o.jsxs("select",{"aria-label":`${e.name} model`,value:u,disabled:a.length===0,onChange:z=>{h(z.target.value),T(C=>({...C,model:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",R.model?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:a.length===0?"—":"Choisir un modèle…"}),O.map(z=>o.jsx("option",{value:z,children:z},z))]}),R.model&&o.jsx("small",{className:"text-xs text-danger",children:R.model})]})]}),i==="custom"&&o.jsxs("fieldset",{className:"flex flex-col gap-2 rounded-md border border-border/50 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider personnalisé"}),o.jsx(M,{variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{l("catalog"),c(""),h(""),T({})},children:"← Choisir un provider du catalogue"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Identifiant du provider"}),o.jsx(ie,{"aria-label":`${e.name} custom provider id`,value:a,placeholder:"ex. mon-provider",invalid:!!R.providerId,onChange:z=>{c(z.target.value),T(C=>({...C,providerId:void 0}))}}),R.providerId&&o.jsx("small",{className:"text-xs text-danger",children:R.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Paquet npm"}),o.jsx(ie,{"aria-label":`${e.name} custom npm package`,value:p,placeholder:wx,invalid:!!R.npm,onChange:z=>{m(z.target.value),T(C=>({...C,npm:void 0}))}}),R.npm&&o.jsx("small",{className:"text-xs text-danger",children:R.npm})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"URL de base"}),o.jsx(ie,{"aria-label":`${e.name} custom base url`,value:x,placeholder:"https://api.mon-provider.example/v1",invalid:!!R.baseUrl,onChange:z=>{w(z.target.value),T(C=>({...C,baseUrl:void 0}))}}),R.baseUrl&&o.jsx("small",{className:"text-xs text-danger",children:R.baseUrl})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Modèle"}),o.jsx(ie,{"aria-label":`${e.name} model`,value:u,placeholder:"ex. mon-modele-1",invalid:!!R.model,onChange:z=>{h(z.target.value),T(C=>({...C,model:void 0}))}}),R.model&&o.jsx("small",{className:"text-xs text-danger",children:R.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Libellé du modèle (optionnel)"}),o.jsx(ie,{"aria-label":`${e.name} custom display name`,value:v,placeholder:"ex. Mon modèle",onChange:z=>y(z.target.value)})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Clé API"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ie,{"aria-label":`${e.name} api key`,type:j?"text":"password",value:_,placeholder:E?"Ressaisissez la clé API pour confirmer l'enregistrement":"ex. sk-ant-…",invalid:!!R.apiKey,onChange:z=>{b(z.target.value),T(C=>({...C,apiKey:void 0}))}}),o.jsx(Hn,{size:"sm","aria-label":"afficher/masquer la clé API",onClick:()=>S(z=>!z),children:j?"🙈":"👁"})]}),R.apiKey&&o.jsx("small",{className:"text-xs text-danger",children:R.apiKey}),o.jsx("small",{className:"text-xs text-faint",children:"Jamais affichée ni renvoyée par IdeA une fois enregistrée ; stockée chiffrée localement."}),E&&o.jsx("small",{className:"text-xs text-muted",children:"Pour des raisons de sécurité, la clé n'est jamais réaffichée : ressaisissez-la à chaque modification de ce profil."})]}),o.jsx(M,{variant:"primary",size:"sm",loading:N,disabled:G,onClick:()=>void P(),className:"w-fit",children:"Enregistrer"})]})}function jw({engine:e,profile:t,catalog:n,existing:r,customSupported:s,saveProfile:i,onChange:l}){const[a,c]=g.useState(r&&"custom"in r&&r.custom?"custom":"catalog"),[u,h]=g.useState(r?.providerId??""),[d,f]=g.useState(r?.model??""),[p,m]=g.useState(""),x=r&&"custom"in r?r.custom:void 0,[w,v]=g.useState(x?.baseUrl??""),[y,_]=g.useState(x?.displayName??""),[b,j]=g.useState(""),[S,N]=g.useState(!1),[D,A]=g.useState(!1),[k,R]=g.useState(null),[T,E]=g.useState({}),O=r!==void 0,I=n.providers!==null&&!n.loading,W=n.providers?.find(C=>C.providerId===u)?.models??[],G=(n.providers??[]).filter(C=>{if(C.providerId===u)return!0;const Q=p.trim().toLowerCase();return Q.length===0?!0:C.displayName.toLowerCase().includes(Q)||C.providerId.toLowerCase().includes(Q)}),P=D||b.length===0||a==="catalog"&&(!I||!!n.error);async function z(){const C={};if(u.trim().length===0&&(C.providerId="Le provider est obligatoire."),d.trim().length===0&&(C.model="Le modèle est obligatoire."),a==="custom"&&w.trim().length===0&&(C.baseUrl="L'URL de base est obligatoire."),b.length===0&&(C.apiKey="La clé API est obligatoire."),E(C),!(Object.keys(C).length>0)){A(!0),R(null);try{const Q=await i({providerId:u.trim(),model:d.trim(),apiKey:b,...a==="custom"?{custom:{baseUrl:w.trim(),displayName:y.trim().length>0?y.trim():void 0}}:{}});l(Q),j("")}catch(Q){R(to(Q))}finally{A(!1)}}}return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsxs("legend",{className:"px-1 text-xs font-medium text-muted",children:["Provider cloud (",e,")"]}),k&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:k}),n.loading&&o.jsx("p",{className:"text-xs text-faint",children:"Chargement des providers…"}),n.error&&o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"Impossible de charger la liste des providers cloud."}),o.jsx(M,{size:"sm",onClick:()=>n.reload(),className:"w-fit",children:"Réessayer"})]}),a==="catalog"&&o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Provider"}),I&&o.jsx("input",{type:"text","aria-label":`${t.name} provider search`,placeholder:"Rechercher un provider…",value:p,onChange:C=>m(C.target.value),className:"h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"}),o.jsxs("select",{"aria-label":`${t.name} provider`,value:u,disabled:!I,onChange:C=>{const Q=C.target.value;Q===nc?(c("custom"),h("")):h(Q),f(""),E(q=>({...q,providerId:void 0,model:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",T.providerId?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:n.loading?"Chargement des providers…":"Choisir un provider…"}),G.map(C=>o.jsx("option",{value:C.providerId,children:C.displayName},C.providerId)),s&&o.jsx("option",{value:nc,children:"Autre / personnalisé…"})]}),T.providerId&&o.jsx("small",{className:"text-xs text-danger",children:T.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Modèle"}),o.jsxs("select",{"aria-label":`${t.name} model`,value:d,disabled:u.length===0,onChange:C=>{f(C.target.value),E(Q=>({...Q,model:void 0}))},className:U("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",T.model?"border-danger":"border-border"),children:[o.jsx("option",{value:"",disabled:!0,children:u.length===0?"—":"Choisir un modèle…"}),W.map(C=>o.jsx("option",{value:C,children:C},C))]}),T.model&&o.jsx("small",{className:"text-xs text-danger",children:T.model})]})]}),a==="custom"&&s&&o.jsxs("fieldset",{className:"flex flex-col gap-2 rounded-md border border-border/50 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider personnalisé"}),o.jsx(M,{variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{c("catalog"),h(""),f(""),E({})},children:"← Choisir un provider du catalogue"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Identifiant du provider"}),o.jsx(ie,{"aria-label":`${t.name} custom provider id`,value:u,placeholder:"ex. mon-provider",invalid:!!T.providerId,onChange:C=>{h(C.target.value),E(Q=>({...Q,providerId:void 0}))}}),T.providerId&&o.jsx("small",{className:"text-xs text-danger",children:T.providerId})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"URL de base"}),o.jsx(ie,{"aria-label":`${t.name} custom base url`,value:w,placeholder:"https://api.mon-provider.example/v1",invalid:!!T.baseUrl,onChange:C=>{v(C.target.value),E(Q=>({...Q,baseUrl:void 0}))}}),T.baseUrl&&o.jsx("small",{className:"text-xs text-danger",children:T.baseUrl})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Modèle"}),o.jsx(ie,{"aria-label":`${t.name} model`,value:d,placeholder:"ex. mon-modele-1",invalid:!!T.model,onChange:C=>{f(C.target.value),E(Q=>({...Q,model:void 0}))}}),T.model&&o.jsx("small",{className:"text-xs text-danger",children:T.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Libellé du provider (optionnel)"}),o.jsx(ie,{"aria-label":`${t.name} custom display name`,value:y,placeholder:"ex. Mon provider",onChange:C=>_(C.target.value)})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Clé API"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ie,{"aria-label":`${t.name} api key`,type:S?"text":"password",value:b,placeholder:O?"Ressaisissez la clé API pour confirmer l'enregistrement":"ex. sk-…",invalid:!!T.apiKey,onChange:C=>{j(C.target.value),E(Q=>({...Q,apiKey:void 0}))}}),o.jsx(Hn,{size:"sm","aria-label":"afficher/masquer la clé API",onClick:()=>N(C=>!C),children:S?"🙈":"👁"})]}),T.apiKey&&o.jsx("small",{className:"text-xs text-danger",children:T.apiKey}),o.jsx("small",{className:"text-xs text-faint",children:"Jamais affichée ni renvoyée par IdeA une fois enregistrée ; stockée chiffrée localement."}),O&&o.jsx("small",{className:"text-xs text-muted",children:"Le profil conserve sa référence de secret existante ; la clé n'est jamais réaffichée côté UI."})]}),o.jsx(M,{variant:"primary",size:"sm","aria-label":`Enregistrer ${e}`,loading:D,disabled:P,onClick:()=>void z(),className:"w-fit",children:"Enregistrer"})]})}function YT({profile:e,catalog:t,onChange:n}){const{profile:r}=ue();return o.jsx(jw,{engine:"Codex",profile:e,catalog:t,existing:e.codexProvider,customSupported:t.providers?.some(s=>s.customSupported)??!1,saveProfile:s=>r.saveCodexProviderProfile({profile:e,providerId:s.providerId,model:s.model,apiKey:s.apiKey,custom:s.custom}),onChange:n})}function XT({profile:e,catalog:t,onChange:n}){const{profile:r}=ue();return o.jsx(jw,{engine:"Claude",profile:e,catalog:t,existing:e.claudeProvider,customSupported:!1,saveProfile:s=>r.saveClaudeProviderProfile({profile:e,providerId:s.providerId,model:s.model,apiKey:s.apiKey}),onChange:n})}function QT({profile:e,errors:t,servers:n,onChange:r}){const s=e.opencode??$T(),i=l=>r({...e,opencode:{...s,...l}});return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local model (OpenCode + llama.cpp)"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Base URL"}),o.jsx(ie,{"aria-label":`${e.name} base url`,value:s.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!t.baseURL,onChange:l=>i({baseURL:l.target.value})}),t.baseURL&&o.jsx("small",{className:"text-xs text-danger",children:t.baseURL})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Model"}),o.jsx(ie,{"aria-label":`${e.name} model`,value:s.model,placeholder:"qwen3-coder-30b",invalid:!!t.model,onChange:l=>i({model:l.target.value})}),t.model&&o.jsx("small",{className:"text-xs text-danger",children:t.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"API key (optional — a local llama.cpp needs none)"}),o.jsx(ie,{"aria-label":`${e.name} api key`,value:s.apiKey??"",placeholder:"e.g. sk-no-key",onChange:l=>{const a=l.target.value;i({apiKey:a.length===0?void 0:a})}})]}),o.jsxs("div",{className:"flex flex-wrap gap-4",children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":`${e.name} reasoning`,checked:s.reasoning??!0,onChange:l=>i({reasoning:l.target.checked}),className:"accent-primary"}),o.jsx(Ae,{children:"Reasoning"})]}),o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox","aria-label":`${e.name} attachment`,checked:s.attachment??!1,onChange:l=>i({attachment:l.target.checked}),className:"accent-primary"}),o.jsx(Ae,{children:"Attachments"})]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Local model server (bind to a managed llama.cpp server, or none)"}),o.jsx(TT,{ariaLabel:`${e.name} local model server`,servers:n,value:s.localModelServerId,onChange:l=>i({localModelServerId:l})})]})]})}function Bu(e){const t=e.trim();if(t.length===0)return;const n=Number(t);return Number.isFinite(n)?n:NaN}function JT({profile:e,errors:t,onChange:n}){const r=e.chatHttp??FT(),s=i=>n({...e,chatHttp:{...r,...i}});return o.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[o.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local / LAN model (OpenAI-compatible)"}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Endpoint"}),o.jsx(ie,{"aria-label":`${e.name} endpoint`,value:r.endpoint,placeholder:"http://localhost:11434/v1",invalid:!!t.endpoint,onChange:i=>s({endpoint:i.target.value})}),t.endpoint&&o.jsx("small",{className:"text-xs text-danger",children:t.endpoint})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"Model"}),o.jsx(ie,{"aria-label":`${e.name} model`,value:r.model,placeholder:"qwen2.5-coder",invalid:!!t.model,onChange:i=>s({model:i.target.value})}),t.model&&o.jsx("small",{className:"text-xs text-danger",children:t.model})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx(Ae,{children:"API key — environment variable name (never the key itself)"}),o.jsx(ie,{"aria-label":`${e.name} api key env`,value:r.apiKeyEnv??"",placeholder:"e.g. OPENAI_API_KEY (variable name, not the secret)",invalid:!!t.apiKeyEnv,onChange:i=>{const l=i.target.value.trim();s({apiKeyEnv:l.length===0?void 0:l})}}),t.apiKeyEnv&&o.jsx("small",{className:"text-xs text-danger",children:t.apiKeyEnv})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(Ae,{children:"Request timeout (ms)"}),o.jsx(ie,{"aria-label":`${e.name} request timeout`,value:r.requestTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.requestTimeoutMs,onChange:i=>s({requestTimeoutMs:Bu(i.target.value)})}),t.requestTimeoutMs&&o.jsx("small",{className:"text-xs text-danger",children:t.requestTimeoutMs})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(Ae,{children:"Connect timeout (ms)"}),o.jsx(ie,{"aria-label":`${e.name} connect timeout`,value:r.connectTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.connectTimeoutMs,onChange:i=>s({connectTimeoutMs:Bu(i.target.value)})}),t.connectTimeoutMs&&o.jsx("small",{className:"text-xs text-danger",children:t.connectTimeoutMs})]}),o.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[o.jsx(Ae,{children:"Max tool iterations"}),o.jsx(ie,{"aria-label":`${e.name} max tool iterations`,value:r.maxToolIterations?.toString()??"",inputMode:"numeric",invalid:!!t.maxToolIterations,onChange:i=>s({maxToolIterations:Bu(i.target.value)})}),t.maxToolIterations&&o.jsx("small",{className:"text-xs text-danger",children:t.maxToolIterations})]})]})]})}function Nw(){const{profile:e}=ue(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{s(null);try{n(await e.listProfiles())}catch(u){s(u&&typeof u=="object"&&"message"in u?String(u.message):String(u))}},[e]);g.useEffect(()=>{a()},[a]);async function c(u){await e.deleteProfile(u),await a()}return i?o.jsx(Cw,{forceOpen:!0,onDone:()=>{l(!1),a()}}):o.jsx(ke,{"aria-label":"ai profiles settings",title:"Profils IA",actions:o.jsx(M,{size:"sm",onClick:()=>l(!0),children:"Configurer les profils"}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[r&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:r}),t.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun profil configuré."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(u=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex items-baseline gap-2",children:[o.jsx("strong",{className:"text-sm text-content",children:u.name}),o.jsx("code",{className:"text-xs text-muted",children:u.command})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`supprimer ${u.name}`,onClick:()=>void c(u.id),children:"Supprimer"})]},u.id))})]})})}const ZT=3e3,eL=2500;function Sx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function tL(){const{device:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(!1),[a,c]=g.useState(!1),[u,h]=g.useState(null),[d,f]=g.useState([]),[p,m]=g.useState(!1),x=g.useRef(null),w=g.useCallback(async()=>{try{const D=await e.listDevices();return n(D),s(null),D}catch(D){return s(Sx(D)),null}},[e]),v=g.useCallback(async()=>{const D=await w();D&&(x.current=new Set(D.map(A=>A.deviceId)))},[w]);g.useEffect(()=>{v()},[v]),g.useEffect(()=>{if(!u)return;const D=setInterval(()=>{(async()=>{const A=await w();if(!A)return;const k=x.current;if(x.current=new Set(A.map(T=>T.deviceId)),!k)return;const R=A.filter(T=>!k.has(T.deviceId)).map(T=>T.deviceId);R.length>0&&f(R)})()},ZT);return()=>clearInterval(D)},[u,w]),g.useEffect(()=>{if(d.length===0)return;const D=setTimeout(()=>f([]),eL);return()=>clearTimeout(D)},[d]);const y=g.useCallback(async D=>{l(!0),s(null);try{return await D(),!0}catch(A){return s(Sx(A)),!1}finally{l(!1)}},[]),_=g.useCallback(async()=>{c(!0);try{await y(async()=>{h(await e.createPairingCode())})}finally{c(!1)}},[e,y]),b=g.useCallback(()=>h(null),[]),j=g.useCallback(async(D,A)=>{await y(()=>e.renameDevice(D,A))&&await v()},[e,y,v]),S=g.useCallback(async D=>{const A=D.isCurrentDevice;await y(()=>e.revokeDevice(D.deviceId))&&(A?m(!0):await v())},[e,y,v]),N=g.useCallback(async()=>{const D=t?.some(A=>A.isCurrentDevice)??!1;await y(()=>e.revokeAllDevices())&&(D?m(!0):await v())},[t,e,y,v]);return{devices:t,error:r,busy:i,generating:a,code:u,freshDeviceIds:d,sessionEnded:p,refresh:v,generateCode:_,dismissCode:b,rename:j,revoke:S,revokeAll:N}}const nL=2*60*1e3;function kx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function rL(e){return e.toLocaleTimeString("fr-FR",{hour:"2-digit",minute:"2-digit"})}function Ew(e,t=new Date){const n=new Date(e),r=n.getFullYear()===t.getFullYear();return n.toLocaleDateString("fr-FR",{day:"numeric",month:"short",...r?{}:{year:"numeric"}})}function sL(e,t=new Date){if(t.getTime()-ezu(e.expiresAtMs)),[i,l]=g.useState(!1);g.useEffect(()=>{s(zu(e.expiresAtMs));const c=setInterval(()=>s(zu(e.expiresAtMs)),1e3);return()=>clearInterval(c)},[e.expiresAtMs]),g.useEffect(()=>{l(!1)},[e.code]),g.useEffect(()=>{if(!i)return;const c=setTimeout(()=>l(!1),2e3);return()=>clearTimeout(c)},[i]);const a=r===null;return o.jsx(ke,{"data-testid":"pairing-code-panel",className:"flex flex-col gap-3",children:a?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm text-muted",children:"Ce code a expiré."}),o.jsx("div",{children:o.jsx(M,{size:"sm",onClick:t,children:"Générer un nouveau code"})})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm text-muted",children:"Saisissez ce code sur le nouvel appareil."}),o.jsx("p",{"data-testid":"pairing-code-value","aria-label":e.code,className:"flex gap-3 font-mono text-2xl font-semibold tracking-[0.2em] text-content sm:text-3xl",children:lL(e.code).map((c,u)=>o.jsx("span",{"aria-hidden":"true",children:c},u))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void oL(e.code).then(c=>l(c)),children:i?"Copié":"Copier"}),o.jsx("span",{className:"text-xs text-faint","data-testid":"pairing-code-countdown",children:r}),o.jsx(M,{size:"sm",variant:"ghost",className:"ml-auto",onClick:n,children:"Fermer"})]})]})})}function Cx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:s=!1,onConfirm:i,onCancel:l}){const a=g.useRef(null);return g.useEffect(()=>{a.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.floatingWindow},onClick:l,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),o.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:s,onClick:()=>void i(),children:n})]})]})})}const _p=40,Pw="Cet appareil",cL=[[/\bEdg(?:e|A|iOS)?\//,"Edge"],[/\bOPR\/|\bOpera\//,"Opera"],[/\bFirefox\/|\bFxiOS\//,"Firefox"],[/\bChrome\/|\bCriOS\//,"Chrome"],[/\bSafari\//,"Safari"]],uL=[[/\bWindows\b/,"Windows"],[/\bMac OS X\b|\bMacintosh\b/,"Mac"],[/\bCrOS\b/,"ChromeOS"],[/\bLinux\b|\bX11\b/,"Linux"]];function dL(e){const t=e??"";if(/\biPhone\b/.test(t))return"iPhone";if(/\biPad\b/.test(t))return"iPad";if(/\bAndroid\b/.test(t))return"Android";const n=cL.find(([s])=>s.test(t))?.[1],r=uL.find(([s])=>s.test(t))?.[1];return n&&r?`${n} sur ${r}`:n??r??Pw}function jx(e){return Array.from(e.trim()).slice(0,_p).join("")}function hL(){return typeof navigator>"u"||!navigator.userAgent?Pw:dL(navigator.userAgent)}function Aw({onSessionEnded:e}){const t=tL(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[l,a]=g.useState(null);g.useEffect(()=>{t.sessionEnded&&e?.()},[t.sessionEnded,e]);const c=t.devices;return o.jsxs("section",{"data-testid":"devices-screen",className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Appareils"}),o.jsx("p",{className:"text-sm text-muted",children:"Les appareils autorisés à accéder à cette instance IdeA."})]}),o.jsx(M,{onClick:()=>void t.generateCode(),loading:t.generating,children:"Appairer"})]}),t.code&&o.jsx(aL,{code:t.code,onRegenerate:()=>void t.generateCode(),onDismiss:t.dismissCode}),t.error&&o.jsx(ke,{className:"border-danger/40",children:o.jsx("p",{role:"alert",className:"text-sm text-danger",children:t.error})}),c===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Ie,{size:12})," Chargement des appareils…"]}):c.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun appareil appairé."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"device-list",children:c.map(u=>o.jsx(fL,{device:u,fresh:t.freshDeviceIds.includes(u.deviceId),renaming:l===u.deviceId,onStartRename:()=>a(u.deviceId),onCancelRename:()=>a(null),onRename:async h=>{await t.rename(u.deviceId,h),a(null)},onRevoke:()=>r(u)},u.deviceId))}),c!==null&&c.length>0&&o.jsx("div",{className:"pt-1",children:o.jsx(M,{variant:"ghost",size:"sm",onClick:()=>i(!0),children:"Révoquer tous les appareils"})}),n&&o.jsx(Cx,{title:"Révoquer cet appareil ?",body:n.isCurrentDevice?"Il devra être appairé à nouveau pour accéder à IdeA. Vous serez déconnecté immédiatement.":"Il devra être appairé à nouveau pour accéder à IdeA.",confirmLabel:"Révoquer",busy:t.busy,onConfirm:async()=>{const u=n;r(null),await t.revoke(u)},onCancel:()=>r(null)}),s&&o.jsx(Cx,{title:"Révoquer tous les appareils ?",body:"Tous les appareils, y compris celui-ci, devront être appairés à nouveau. Vous serez déconnecté immédiatement.",confirmLabel:"Tout révoquer",danger:!0,busy:t.busy,onConfirm:async()=>{i(!1),await t.revokeAll()},onCancel:()=>i(!1)})]})}function fL({device:e,fresh:t,renaming:n,onStartRename:r,onCancelRename:s,onRename:i,onRevoke:l}){return o.jsx("li",{"data-testid":"device-row","data-fresh":t||void 0,className:U("py-3 transition-colors first:pt-0 last:pb-0",t&&"bg-success/10"),children:n?o.jsx(pL,{device:e,onSubmit:i,onCancel:s}):o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),e.isCurrentDevice&&o.jsx("span",{className:"shrink-0 rounded-full bg-primary/15 px-2 py-0.5 text-[0.65rem] font-medium text-primary",children:"Cet appareil"})]}),o.jsx("span",{className:"text-xs text-muted",children:sL(e.lastSeenAtMs)}),o.jsx("span",{className:"text-[0.7rem] text-faint",children:iL(e.pairedAtMs)})]}),o.jsx(mL,{deviceName:e.name,onRename:r,onRevoke:l})]})})}function pL({device:e,onSubmit:t,onCancel:n}){const[r,s]=g.useState(e.name),i=r.trim();return o.jsxs("form",{className:"flex flex-col gap-2",onSubmit:l=>{l.preventDefault(),i.length>0&&t(i)},children:[o.jsx(qt,{label:"Nom de l'appareil",hideLabel:!0,children:({id:l})=>o.jsx(ie,{id:l,value:r,autoFocus:!0,maxLength:_p,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Escape"&&n()}})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{type:"submit",size:"sm",disabled:i.length===0,children:"Renommer"}),o.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Annuler"})]})]})}function mL({deviceName:e,onRename:t,onRevoke:n}){const[r,s]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const i=()=>s(!1);return window.addEventListener("click",i),()=>window.removeEventListener("click",i)},[r]),o.jsxs("div",{className:"relative shrink-0",onClick:i=>i.stopPropagation(),children:[o.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":r,"aria-label":`Actions pour ${e}`,onClick:()=>s(i=>!i),className:"rounded-md px-2 py-1 text-sm text-muted transition-colors hover:bg-raised hover:text-content",children:"⋯"}),r&&o.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-10 mt-1 flex min-w-36 flex-col rounded-md border border-border bg-raised py-1 shadow-lg",children:[o.jsx("button",{type:"button",role:"menuitem",onClick:()=>{s(!1),t()},className:"px-3 py-1.5 text-left text-sm text-content transition-colors hover:bg-canvas",children:"Renommer"}),o.jsx("button",{type:"button",role:"menuitem",onClick:()=>{s(!1),n()},className:"px-3 py-1.5 text-left text-sm text-danger transition-colors hover:bg-canvas",children:"Révoquer"})]})]})}const gL=250;function Vi(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function xL(){const{desktopServer:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState({state:"stopped"}),[i,l]=g.useState([]),[a,c]=g.useState(),[u,h]=g.useState([]),[d,f]=g.useState(null),[p,m]=g.useState(null),[x,w]=g.useState(!1),[v,y]=g.useState(!1),_=g.useRef(0);g.useEffect(()=>{let E=!0;return(async()=>{try{const[O,I]=await Promise.all([e.getExposureSettings(),e.status()]);if(!E)return;n(O),s(I)}catch(O){E&&m(Vi(O))}})(),()=>{E=!1}},[e]),g.useEffect(()=>{let E=!0;return(async()=>{try{const O=await e.previewExposure({mode:"localOnly",autoStart:!1,port:0,trustedProxies:[]});E&&l(O.candidateLanAddresses)}catch{}})(),()=>{E=!1}},[e]),g.useEffect(()=>{let E,O=!1;return e.onStatusChanged(s).then(I=>{O?I():E=I}),()=>{O=!0,E?.()}},[e]),g.useEffect(()=>{if(!t)return;const E=++_.current,O=setTimeout(()=>{e.previewExposure(t).then(I=>{E===_.current&&(c(I.upstreamUrl),h(I.warnings),f(null))},I=>{E===_.current&&(c(void 0),h([]),f(Vi(I)))})},gL);return()=>clearTimeout(O)},[e,t]);const b=g.useCallback(E=>{m(null),n(O=>O&&{...O,...E})},[]),j=g.useCallback(E=>{b(E==="localOnly"?{mode:E,publicOrigin:void 0,lanBindAddress:void 0,trustedProxies:[]}:E==="remoteProxyLocal"?{mode:E,lanBindAddress:void 0,trustedProxies:[]}:{mode:E})},[b]),S=g.useCallback(E=>b({publicOrigin:E.trim()||void 0}),[b]),N=g.useCallback(E=>b({lanBindAddress:E||void 0}),[b]),D=g.useCallback(E=>b({trustedProxies:E.split(/[\s,]+/).map(O=>O.trim()).filter(Boolean)}),[b]),A=g.useCallback(E=>b({port:E}),[b]),k=g.useCallback(async E=>{if(!t)return;const O={...t,autoStart:E};y(!0),m(null);try{await e.saveExposureSettings(O),n(O)}catch(I){m(Vi(I))}finally{y(!1)}},[e,t]),R=g.useCallback(async()=>{if(t){w(!0),m(null);try{await e.saveExposureSettings(t),s(await e.start())}catch(E){m(Vi(E))}finally{w(!1)}}},[e,t]),T=g.useCallback(async()=>{w(!0),m(null);try{s(await e.stop())}catch(E){m(Vi(E))}finally{w(!1)}},[e]);return{ready:t!==null,settings:t,status:r,candidateLanAddresses:i,upstreamUrl:a,warnings:u,validationError:d,actionError:p,busy:x,autoStartBusy:v,setMode:j,setPublicOrigin:S,setLanBindAddress:N,setTrustedProxies:D,setPort:A,setAutoStart:k,start:R,stop:T}}const vL=[{mode:"localOnly",title:"Cet ordinateur uniquement",description:"Pour utiliser IdeA uniquement sur cet ordinateur. Les appareils distants ne peuvent pas se connecter."},{mode:"remoteProxyLocal",title:"Accès distant, proxy sur cet ordinateur",description:"À utiliser quand le proxy HTTPS tourne sur la même machine qu'IdeA Desktop."},{mode:"remoteProxyOtherMachine",title:"Accès distant, proxy sur une autre machine",description:"À utiliser quand le proxy HTTPS tourne sur une autre machine. IdeA n'acceptera que le trafic provenant de ce proxy."}],yL={stopped:"Arrêté",starting:"Démarrage…",running:"En cours d'exécution",stopping:"Arrêt…",failed:"Échec"};function _L({value:e,label:t}){const[n,r]=g.useState(!1),s=typeof navigator<"u"&&!!navigator.clipboard;return o.jsx(M,{size:"sm",variant:"ghost","aria-label":t,disabled:!s,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),window.setTimeout(()=>r(!1),1500)},()=>r(!1))},children:n?"Copié":"Copier"})}function bL({value:e,copyLabel:t}){return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"flex-1 truncate rounded-md border border-border bg-raised px-2 py-1.5 font-mono text-xs text-content",children:e}),o.jsx(_L,{value:e,label:t})]})}function wL(){const e=xL(),t=g.useRef(null);if(!e.ready||!e.settings)return o.jsx(ke,{"aria-label":"deployment settings",title:"Déploiement",children:o.jsx("p",{className:"text-sm text-muted",children:"Chargement…"})});const{settings:n,status:r}=e,s=r.state==="running",i=n.mode!=="localOnly",l=n.mode==="remoteProxyOtherMachine",a=r.state==="starting"||r.state==="stopping";return o.jsxs("div",{"aria-label":"deployment settings",className:"flex flex-col gap-4",children:[o.jsx(ke,{title:"Serveur",actions:s||r.state==="stopping"?o.jsx(M,{size:"sm",onClick:()=>void e.stop(),disabled:e.busy||a,children:"Arrêter"}):o.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy||a,children:"Démarrer"}),children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{"aria-hidden":!0,className:U("size-2 rounded-full",s&&"bg-success",r.state==="failed"&&"bg-danger",(r.state==="stopped"||a)&&"bg-faint")}),o.jsx("span",{className:"text-content",children:yL[r.state]})]}),r.localUrl&&o.jsxs("p",{className:"text-xs text-muted",children:["URL locale : ",o.jsx("code",{className:"font-mono text-content",children:r.localUrl})]}),r.publicUrl&&o.jsxs("p",{className:"text-xs text-muted",children:["URL publique : ",o.jsx("code",{className:"font-mono text-content",children:r.publicUrl})]}),r.state==="failed"&&r.error&&(r.error.code==="PORT_IN_USE"?o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("p",{role:"alert",className:"text-sm text-danger",children:["Le serveur n'a pas démarré automatiquement. ",r.error.message]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>{t.current?.scrollIntoView?.({behavior:"smooth",block:"center"}),t.current?.focus()},children:"Modifier le port"}),o.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy,children:"Réessayer"})]})]}):o.jsx("p",{role:"alert",className:"text-sm text-danger",children:r.error.message})),e.actionError&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.actionError}),o.jsxs("label",{className:"flex cursor-pointer items-start gap-2 pt-2",children:[o.jsx("input",{type:"checkbox",className:"mt-0.5","aria-label":"Démarrer le serveur au lancement d'IdeA",checked:n.autoStart,disabled:e.autoStartBusy,onChange:c=>void e.setAutoStart(c.target.checked)}),o.jsxs("span",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-sm text-content",children:"Démarrer le serveur au lancement d'IdeA"}),o.jsx("span",{className:"text-xs text-muted",children:"IdeA utilisera les réglages réseau enregistrés ci-dessous au prochain démarrage de l'application desktop."})]})]})]})}),o.jsx(ke,{title:"Accès réseau",children:o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx("div",{role:"radiogroup","aria-label":"mode d'accès réseau",className:"flex flex-col gap-2",children:vL.map(c=>{const u=n.mode===c.mode;return o.jsxs("label",{className:U("flex cursor-pointer gap-3 rounded-lg border p-3 transition-colors",u?"border-border-strong bg-raised":"border-border hover:bg-raised"),children:[o.jsx("input",{type:"radio",name:"exposure-mode",className:"mt-1",checked:u,onChange:()=>e.setMode(c.mode)}),o.jsxs("span",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),o.jsx("span",{className:"text-xs text-muted",children:c.description})]})]},c.mode)})}),o.jsx(qt,{label:"Port",children:({id:c})=>o.jsx(ie,{ref:t,id:c,type:"number",value:String(n.port),onChange:u=>e.setPort(Number(u.target.value))})}),i&&o.jsx(qt,{label:"Origine publique",hint:"Exemple : https://idea.example.com",children:({id:c,describedBy:u})=>o.jsx(ie,{id:c,"aria-describedby":u,placeholder:"https://idea.example.com",value:n.publicOrigin??"",onChange:h=>e.setPublicOrigin(h.target.value)})}),l&&o.jsxs(o.Fragment,{children:[o.jsx(qt,{label:"Adresse LAN d'écoute",hint:"L'adresse de cette machine à laquelle le proxy se connectera.",children:({id:c,describedBy:u})=>e.candidateLanAddresses.length>0?o.jsxs("select",{id:c,"aria-describedby":u,className:"rounded-md border border-border bg-surface px-2 py-1.5 text-sm text-content",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value),children:[o.jsx("option",{value:"",children:"Sélectionner une adresse…"}),e.candidateLanAddresses.map(h=>o.jsx("option",{value:h,children:h},h))]}):o.jsx(ie,{id:c,"aria-describedby":u,placeholder:"192.168.1.42",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value)})}),o.jsx(qt,{label:"IP/CIDR du proxy autorisé",hint:"Ce n'est pas l'adresse d'écoute d'IdeA. C'est la machine autorisée à contacter IdeA.",children:({id:c,describedBy:u})=>o.jsx(ie,{id:c,"aria-describedby":u,placeholder:"203.0.113.7 or 203.0.113.0/24",value:n.trustedProxies.join(", "),onChange:h=>e.setTrustedProxies(h.target.value)})}),o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Si votre proxy n'est pas sur cet ordinateur, choisissez ce mode. Sinon, le proxy peut expirer sans erreur IdeA."})]}),e.warnings.map(c=>o.jsx("p",{className:"text-xs text-warning",children:c.message},c.code)),e.validationError&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.validationError})]})}),i&&o.jsx(ke,{title:"Configuration du proxy",children:o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("p",{className:"text-xs text-muted",children:"Faites pointer votre proxy inverse HTTPS vers cet upstream."}),e.upstreamUrl?o.jsx(bL,{value:e.upstreamUrl,copyLabel:"copier l'URL upstream"}):o.jsx("p",{className:"text-xs text-faint",children:"Complétez les paramètres ci-dessus pour obtenir l'URL upstream."})]})}),o.jsx(ke,{title:"Appairage",children:o.jsxs("p",{className:"text-sm text-muted",children:["L'appairage est géré dans"," ",o.jsx("span",{className:"text-content",children:"Paramètres → Appareils"}),", où vous pouvez générer un code et révoquer des appareils."]})})]})}const Tw={aiProfiles:"Profils IA",deployment:"Déploiement",devices:"Appareils",plugins:"Plugins"},Lw=["aiProfiles","deployment","devices","plugins"];function SL({section:e,onSectionChange:t,onClose:n}){return o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsxs("nav",{"aria-label":"settings sections",className:"flex w-52 shrink-0 flex-col gap-1 border-r border-border p-3",children:[Lw.map(r=>{const s=r===e;return o.jsx("button",{type:"button","aria-current":s?"page":void 0,onClick:()=>t(r),className:U("rounded-md px-3 py-2 text-left text-sm transition-colors",s?"bg-raised font-semibold text-content":"text-muted hover:bg-raised hover:text-content"),children:Tw[r]},r)}),o.jsx("div",{className:"mt-auto pt-2",children:o.jsx(M,{size:"sm",variant:"ghost",className:"w-full",onClick:n,children:"Fermer les paramètres"})})]}),o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-2xl",children:e==="aiProfiles"?o.jsx(Nw,{}):e==="deployment"?o.jsx(wL,{}):e==="plugins"?o.jsx(mA,{}):o.jsx(Aw,{})})})]})}function Gi(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const kL={branches:[],current:null},Nx=20;function CL(e){const{git:t}=ue(),[n,r]=g.useState([]),[s,i]=g.useState(kL),[l,a]=g.useState([]),[c,u]=g.useState(!1),[h,d]=g.useState(null),f=g.useCallback(async()=>{u(!0),d(null);try{const[v,y,_]=await Promise.all([t.status(e),t.branches(e),t.log(e,Nx)]);r(v),i(y),a(_)}catch(v){d(Gi(v))}finally{u(!1)}},[t,e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async v=>{u(!0),d(null);try{await t.stage(e,v),r(y=>y.map(_=>_.path===v?{..._,staged:!0}:_))}catch(y){d(Gi(y))}finally{u(!1)}},[t,e]),m=g.useCallback(async v=>{u(!0),d(null);try{await t.unstage(e,v),r(y=>y.map(_=>_.path===v?{..._,staged:!1}:_))}catch(y){d(Gi(y))}finally{u(!1)}},[t,e]),x=g.useCallback(async v=>{u(!0),d(null);try{const y=await t.commit(e,v);r(_=>_.filter(b=>!b.staged)),a(_=>[y,..._].slice(0,Nx))}catch(y){d(Gi(y))}finally{u(!1)}},[t,e]),w=g.useCallback(async v=>{u(!0),d(null);try{await t.checkout(e,v),i(y=>({branches:y.branches.includes(v)?y.branches:[...y.branches,v],current:v}))}catch(y){d(Gi(y))}finally{u(!1)}},[t,e]);return{files:n,branches:s,log:l,busy:c,error:h,refresh:f,stage:p,unstage:m,commit:x,checkout:w}}function Ex(e){const t={children:[]};for(const n of e){const r=n.path.split("/").filter(Boolean);let s=t;r.forEach((i,l)=>{const a=l===r.length-1,c=r.slice(0,l+1).join("/");let u=s.children.find(h=>h.name===i&&h.isDir===!a);u||(u={name:i,path:c,isDir:!a,staged:n.staged,children:[]},s.children.push(u)),s=u})}return Dw(t),t.children}function Dw(e){e.children.sort((t,n)=>t.isDir!==n.isDir?t.isDir?-1:1:t.name.localeCompare(n.name)),e.children.forEach(Dw)}function Hh({nodes:e,depth:t,action:n,onAction:r,busy:s}){return o.jsx("ul",{className:"flex flex-col gap-0.5",children:e.map(i=>i.isDir?o.jsxs("li",{children:[o.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-xs text-muted",style:{paddingLeft:`${t*14+8}px`},children:[o.jsx("span",{"aria-hidden":!0,className:"text-faint",children:"▸"}),o.jsx("span",{className:"truncate",children:i.name})]}),o.jsx(Hh,{nodes:i.children,depth:t+1,action:n,onAction:r,busy:s})]},i.path):o.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:bg-raised",style:{paddingLeft:`${t*14+8}px`},children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{"aria-hidden":!0,className:U("size-1.5 shrink-0 rounded-full",n==="unstage"?"bg-success":"bg-warning")}),o.jsx("code",{className:"min-w-0 truncate text-xs text-content",children:i.name})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`${n} ${i.path}`,disabled:s,onClick:()=>r(i.path),className:"shrink-0 text-muted hover:text-content",children:n==="unstage"?"Unstage":"Stage"})]},i.path))})}function Rw({projectId:e}){const t=CL(e),[n,r]=g.useState(""),[s,i]=g.useState(""),l=t.files.filter(f=>f.staged),a=t.files.filter(f=>!f.staged),c=n.trim().length>0&&l.length>0&&!t.busy;async function u(f){f.preventDefault(),c&&(await t.commit(n.trim()),r(""))}async function h(f){await t.checkout(f)}async function d(f){f.preventDefault();const p=s.trim();!p||t.busy||(await t.checkout(p),i(""))}return o.jsxs(ke,{title:"Git",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("section",{"aria-label":"Changes",className:"border-b border-border p-4",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Changes"}),t.busy&&o.jsx(Ie,{size:12})]}),t.files.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No changes."}):o.jsxs("div",{className:"flex flex-col gap-3",children:[l.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Staged"}),o.jsx(Hh,{nodes:Ex(l),depth:0,action:"unstage",onAction:f=>void t.unstage(f),busy:t.busy})]}),a.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Unstaged"}),o.jsx(Hh,{nodes:Ex(a),depth:0,action:"stage",onAction:f=>void t.stage(f),busy:t.busy})]})]})]}),o.jsxs("section",{"aria-label":"Commit",className:"border-b border-border p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Commit"}),o.jsxs("form",{onSubmit:u,className:"flex flex-col gap-2",children:[o.jsx(ie,{"aria-label":"commit message",placeholder:"Commit message",value:n,onChange:f=>r(f.target.value)}),o.jsx(M,{type:"submit",variant:"primary",disabled:!c,loading:t.busy,className:"self-end",children:"Commit"})]})]}),o.jsxs("section",{"aria-label":"Branches",className:"border-b border-border p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Branches"}),o.jsxs("p",{className:"mb-2 text-sm text-content",children:["Current:"," ",o.jsx("span",{className:"font-medium",children:t.branches.current??"(none)"})]}),t.branches.branches.length>0&&o.jsx("ul",{className:"mb-3 flex flex-col gap-0.5",children:t.branches.branches.map(f=>{const p=f===t.branches.current;return o.jsxs("li",{className:U("flex items-center justify-between gap-2 rounded-md px-2 py-1",p&&"bg-raised"),children:[o.jsx("span",{className:U("text-sm",p?"font-semibold text-primary":"text-content"),children:f}),!p&&o.jsx(M,{size:"sm",variant:"ghost","aria-label":`checkout ${f}`,disabled:t.busy,onClick:()=>void h(f),className:"shrink-0 text-muted hover:text-content",children:"Checkout"})]},f)})}),o.jsxs("form",{onSubmit:d,className:"flex items-center gap-2",children:[o.jsx(ie,{"aria-label":"new branch name",placeholder:"New branch",value:s,onChange:f=>i(f.target.value),className:"flex-1"}),o.jsx(M,{type:"submit",variant:"ghost",disabled:!s.trim()||t.busy,children:"Create & checkout"})]})]}),o.jsxs("section",{"aria-label":"Log",className:"p-4",children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Log"}),t.log.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No commits yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.log.map(f=>o.jsxs("li",{className:"flex items-baseline gap-2 py-1.5",children:[o.jsx("code",{className:"shrink-0 text-xs text-faint",children:f.hash.slice(0,7)}),o.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:f.summary})]},f.hash))})]})]})}const Px=["#4f9cf9","#a78bfa","#34d399","#fbbf24","#f87171","#38bdf8","#fb923c","#c084fc","#f472b6","#2dd4bf"];function Yi(e){return Px[e%Px.length]}function jL(e){return e.indexOf(null)}function Ax(e,t){const n=jL(e);return n!==-1?(e[n]=t,n):(e.push(t),e.length-1)}function NL(e){const t=[],n=[];for(const r of e){const{hash:s,parents:i}=r,l=t.slice();let a=t.indexOf(s);a===-1&&(a=Ax(t,s));for(let f=0;f{a(!0),u(null);try{const d=await t.graph(e,EL);r(d),i(NL(d))}catch(d){u(d&&typeof d=="object"&&"message"in d?String(d.message):String(d))}finally{a(!1)}},[t,e]);return g.useEffect(()=>{h()},[h]),{commits:n,rows:s,busy:l,error:c,refresh:h}}const rc=16,ga=36,Tx=4.5,Uh=e=>e*rc+rc/2;function Lx(e,t,n){const r=Uh(e.fromLane),s=Uh(e.toLane);if(r===s)return`M ${r} ${t} L ${s} ${n}`;const i=(t+n)/2;return`M ${r} ${t} C ${r} ${i} ${s} ${i} ${s} ${n}`}function AL({row:e,laneCount:t}){const n=t*rc+rc/2,r=ga/2,s=Uh(e.lane);return o.jsxs("svg",{width:n,height:ga,"aria-hidden":!0,className:"shrink-0 overflow-visible",children:[e.incoming.map((i,l)=>o.jsx("path",{d:Lx(i,0,r),fill:"none",stroke:i.color,strokeWidth:2},`in-${l}`)),e.outgoing.map((i,l)=>o.jsx("path",{d:Lx(i,r,ga),fill:"none",stroke:i.color,strokeWidth:2},`out-${l}`)),o.jsx("circle",{cx:s,cy:r,r:Tx+1.5,className:"fill-canvas"}),o.jsx("circle",{cx:s,cy:r,r:Tx,fill:e.color,stroke:"var(--color-canvas)",strokeWidth:1})]})}function TL(e){const t=Math.floor(Date.now()/1e3)-e;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:t<31536e3?`${Math.floor(t/2592e3)}mo ago`:`${Math.floor(t/31536e3)}y ago`}function LL({commit:e,onClose:t}){const n=r=>r.startsWith("tag:");return o.jsxs("aside",{"aria-label":"commit detail",className:"flex w-80 shrink-0 flex-col gap-3 overflow-y-auto border-l border-border bg-surface p-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e.summary}),o.jsx("button",{type:"button","aria-label":"close commit detail",onClick:t,className:"shrink-0 text-muted hover:text-content",children:"×"})]}),o.jsxs("dl",{className:"flex flex-col gap-2 text-xs",children:[o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Hash"}),o.jsx("dd",{children:o.jsx("code",{className:"text-content break-all",children:e.hash})})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Author"}),o.jsx("dd",{className:"text-content",children:e.author})]}),o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Date"}),o.jsx("dd",{className:"text-content",children:new Date(e.timestamp*1e3).toLocaleString()})]}),e.parents.length>0&&o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Parents"}),o.jsx("dd",{className:"flex flex-col gap-0.5",children:e.parents.map(r=>o.jsx("code",{className:"text-content",children:r.slice(0,8)},r))})]}),e.refs.length>0&&o.jsxs("div",{children:[o.jsx("dt",{className:"font-medium text-faint",children:"Refs"}),o.jsx("dd",{className:"flex flex-wrap gap-1",children:e.refs.map(r=>o.jsx("span",{className:U("rounded px-1 py-0.5 text-xs font-medium text-base",n(r)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:r},r))})]})]})]})}function DL({projectId:e}){const t=PL(e),[n,r]=g.useState(null),s=n!=null?t.commits.find(a=>a.hash===n)??null:null,i=t.rows.reduce((a,c)=>Math.max(a,c.laneCount),1),l=a=>a.startsWith("tag:");return o.jsxs("div",{className:"flex flex-1 overflow-hidden","aria-label":"git graph",children:[o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:"Git Graph"}),t.busy&&o.jsx(Ie,{size:14}),o.jsx("button",{type:"button","aria-label":"refresh git graph",onClick:()=>void t.refresh(),disabled:t.busy,className:"ml-auto text-xs text-muted hover:text-content disabled:opacity-40",children:"Refresh"})]}),t.error&&o.jsx("p",{role:"alert",className:"mx-3 mt-2 shrink-0 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger",children:t.error}),o.jsxs("div",{className:"flex-1 overflow-y-auto",role:"list","aria-label":"commits",children:[t.rows.length===0&&!t.busy&&o.jsx("p",{className:"p-4 text-sm text-muted",children:"No commits found."}),t.rows.map(a=>{const c=a.commit.hash===n;return o.jsxs("div",{role:"listitem","aria-label":`commit ${a.commit.hash.slice(0,8)}: ${a.commit.summary}`,onClick:()=>r(c?null:a.commit.hash),className:U("flex cursor-pointer items-center gap-2 border-b border-border/50 px-2 hover:bg-raised",c&&"bg-raised"),style:{height:ga},children:[o.jsx(AL,{row:a,laneCount:i}),a.commit.refs.length>0&&o.jsx("div",{className:"flex shrink-0 flex-wrap gap-1",children:a.commit.refs.map(u=>o.jsx("span",{className:U("rounded px-1 py-0.5 text-xs font-medium",l(u)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:u},u))}),o.jsx("code",{className:"shrink-0 text-xs text-faint",children:a.commit.hash.slice(0,8)}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:a.commit.summary}),o.jsx("span",{className:"shrink-0 text-xs text-muted",children:a.commit.author}),o.jsx("span",{className:"shrink-0 text-xs text-faint",children:TL(a.commit.timestamp)})]},a.commit.hash)})]})]}),s&&o.jsx(LL,{commit:s,onClose:()=>r(null)})]})}function Io(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function RL(){const{project:e}=ue(),[t,n]=g.useState([]),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useCallback(async()=>{h(!0),c(null);try{n(await e.listProjects())}catch(v){c(Io(v))}finally{h(!1)}},[e]);g.useEffect(()=>{d()},[d]);const f=g.useCallback(v=>{s(y=>y.some(_=>_.id===v.id)?y:[...y,v]),l(v.id)},[]),p=g.useCallback(async v=>{h(!0),c(null);try{const y=await e.openProject(v);f(y)}catch(y){c(Io(y))}finally{h(!1)}},[e,f]),m=g.useCallback(async(v,y)=>{h(!0),c(null);try{const _=await e.createProject(v,y);n(b=>[...b,_]),f(_)}catch(_){c(Io(_))}finally{h(!1)}},[e,f]),x=g.useCallback(async v=>{c(null);try{await e.closeProject(v)}catch(y){c(Io(y))}s(y=>{const _=y.filter(b=>b.id!==v);return l(b=>b===v?_.at(-1)?.id??null:b),_})},[e]),w=g.useCallback(v=>{l(v)},[]);return{projects:t,openTabs:r,activeTabId:i,error:a,busy:u,refresh:d,createProject:m,openProject:p,closeTab:x,activateTab:w}}function ML({items:e,activeTabId:t,onSelect:n,onClose:r,projectsPanelOpen:s,onOpenProjectsPanel:i,className:l}){return o.jsxs("div",{className:U("flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",l),children:[e.length===0?o.jsx("p",{className:"px-2 text-sm text-muted",children:"No open tabs."}):o.jsx(qP,{items:e,value:t,onSelect:n,onClose:r}),o.jsx(M,{size:"sm",variant:"secondary",onClick:i,"aria-label":"open projects panel","aria-pressed":s,title:"Ajouter un projet",className:U("shrink-0",s&&"ring-1 ring-border-strong"),children:"+"})]})}function IL(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const OL=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,BL=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,zL={};function Dx(e,t){return(zL.jsx?BL:OL).test(e)}const FL=/[ \t\n\f\r]/g;function $L(e){return typeof e=="object"?e.type==="text"?Rx(e.value):!1:Rx(e)}function Rx(e){return e.replace(FL,"")===""}class no{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}no.prototype.normal={};no.prototype.property={};no.prototype.space=void 0;function Mw(e,t){const n={},r={};for(const s of e)Object.assign(n,s.property),Object.assign(r,s.normal);return new no(n,r,t)}function qh(e){return e.toLowerCase()}class Qt{constructor(t,n){this.attribute=n,this.property=t}}Qt.prototype.attribute="";Qt.prototype.booleanish=!1;Qt.prototype.boolean=!1;Qt.prototype.commaOrSpaceSeparated=!1;Qt.prototype.commaSeparated=!1;Qt.prototype.defined=!1;Qt.prototype.mustUseProperty=!1;Qt.prototype.number=!1;Qt.prototype.overloadedBoolean=!1;Qt.prototype.property="";Qt.prototype.spaceSeparated=!1;Qt.prototype.space=void 0;let WL=0;const ve=Es(),tt=Es(),Kh=Es(),ee=Es(),Re=Es(),gs=Es(),tn=Es();function Es(){return 2**++WL}const Vh=Object.freeze(Object.defineProperty({__proto__:null,boolean:ve,booleanish:tt,commaOrSpaceSeparated:tn,commaSeparated:gs,number:ee,overloadedBoolean:Kh,spaceSeparated:Re},Symbol.toStringTag,{value:"Module"})),Fu=Object.keys(Vh);class bp extends Qt{constructor(t,n,r,s){let i=-1;if(super(t,n),Mx(this,"space",s),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&VL.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Ix,XL);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Ix.test(i)){let l=i.replace(KL,YL);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}s=bp}return new s(r,t)}function YL(e){return"-"+e.toLowerCase()}function XL(e){return e.charAt(1).toUpperCase()}const QL=Mw([Iw,HL,zw,Fw,$w],"html"),wp=Mw([Iw,UL,zw,Fw,$w],"svg");function JL(e){return e.join(" ").trim()}var Sp={},Ox=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,ZL=/\n/g,eD=/^\s*/,tD=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,nD=/^:\s*/,rD=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,sD=/^[;\s]*/,iD=/^\s+|\s+$/g,lD=` -`,Bx="/",zx="*",os="",oD="comment",aD="declaration";function cD(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function s(m){var x=m.match(ZL);x&&(n+=x.length);var w=m.lastIndexOf(lD);r=~w?m.length-w:r+m.length}function i(){var m={line:n,column:r};return function(x){return x.position=new l(m),u(),x}}function l(m){this.start=m,this.end={line:n,column:r},this.source=t.source}l.prototype.content=e;function a(m){var x=new Error(t.source+":"+n+":"+r+": "+m);if(x.reason=m,x.filename=t.source,x.line=n,x.column=r,x.source=e,!t.silent)throw x}function c(m){var x=m.exec(e);if(x){var w=x[0];return s(w),e=e.slice(w.length),x}}function u(){c(eD)}function h(m){var x;for(m=m||[];x=d();)x!==!1&&m.push(x);return m}function d(){var m=i();if(!(Bx!=e.charAt(0)||zx!=e.charAt(1))){for(var x=2;os!=e.charAt(x)&&(zx!=e.charAt(x)||Bx!=e.charAt(x+1));)++x;if(x+=2,os===e.charAt(x-1))return a("End of comment missing");var w=e.slice(2,x-2);return r+=2,s(w),e=e.slice(x),r+=2,m({type:oD,comment:w})}}function f(){var m=i(),x=c(tD);if(x){if(d(),!c(nD))return a("property missing ':'");var w=c(rD),v=m({type:aD,property:Fx(x[0].replace(Ox,os)),value:w?Fx(w[0].replace(Ox,os)):os});return c(sD),v}}function p(){var m=[];h(m);for(var x;x=f();)x!==!1&&(m.push(x),h(m));return m}return u(),p()}function Fx(e){return e?e.replace(iD,os):os}var uD=cD,dD=_a&&_a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Sp,"__esModule",{value:!0});Sp.default=fD;const hD=dD(uD);function fD(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,hD.default)(e),s=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:l,value:a}=i;s?t(l,a,i):a&&(n=n||{},n[l]=a)}),n}var Ec={};Object.defineProperty(Ec,"__esModule",{value:!0});Ec.camelCase=void 0;var pD=/^--[a-zA-Z0-9_-]+$/,mD=/-([a-z])/g,gD=/^[^-]+$/,xD=/^-(webkit|moz|ms|o|khtml)-/,vD=/^-(ms)-/,yD=function(e){return!e||gD.test(e)||pD.test(e)},_D=function(e,t){return t.toUpperCase()},$x=function(e,t){return"".concat(t,"-")},bD=function(e,t){return t===void 0&&(t={}),yD(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(vD,$x):e=e.replace(xD,$x),e.replace(mD,_D))};Ec.camelCase=bD;var wD=_a&&_a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},SD=wD(Sp),kD=Ec;function Gh(e,t){var n={};return!e||typeof e!="string"||(0,SD.default)(e,function(r,s){r&&s&&(n[(0,kD.camelCase)(r,t)]=s)}),n}Gh.default=Gh;var CD=Gh;const jD=sf(CD),Ww=Hw("end"),kp=Hw("start");function Hw(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function ND(e){const t=kp(e),n=Ww(e);if(t&&n)return{start:t,end:n}}function yl(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Wx(e.position):"start"in e||"end"in e?Wx(e):"line"in e||"column"in e?Yh(e):""}function Yh(e){return Hx(e&&e.line)+":"+Hx(e&&e.column)}function Wx(e){return Yh(e&&e.start)+"-"+Yh(e&&e.end)}function Hx(e){return e&&typeof e=="number"?e:1}class Lt extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let s="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?s=t:!i.cause&&t&&(l=!0,s=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const a=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=s,this.line=a?a.line:void 0,this.name=yl(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=l&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Lt.prototype.file="";Lt.prototype.name="";Lt.prototype.reason="";Lt.prototype.message="";Lt.prototype.stack="";Lt.prototype.column=void 0;Lt.prototype.line=void 0;Lt.prototype.ancestors=void 0;Lt.prototype.cause=void 0;Lt.prototype.fatal=void 0;Lt.prototype.place=void 0;Lt.prototype.ruleId=void 0;Lt.prototype.source=void 0;const Cp={}.hasOwnProperty,ED=new Map,PD=/[A-Z]/g,AD=new Set(["table","tbody","thead","tfoot","tr"]),TD=new Set(["td","th"]),Uw="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function LD(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=FD(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=zD(n,t.jsx,t.jsxs)}const s={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?wp:QL,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=qw(s,e,void 0);return i&&typeof i!="string"?i:s.create(e,s.Fragment,{children:i||void 0},void 0)}function qw(e,t,n){if(t.type==="element")return DD(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return RD(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return ID(e,t,n);if(t.type==="mdxjsEsm")return MD(e,t);if(t.type==="root")return OD(e,t,n);if(t.type==="text")return BD(e,t)}function DD(e,t,n){const r=e.schema;let s=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(s=wp,e.schema=s),e.ancestors.push(t);const i=Vw(e,t.tagName,!1),l=$D(e,t);let a=Np(e,t);return AD.has(t.tagName)&&(a=a.filter(function(c){return typeof c=="string"?!$L(c):!0})),Kw(e,l,i,t),jp(l,a),e.ancestors.pop(),e.schema=r,e.create(t,i,l,n)}function RD(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Hl(e,t.position)}function MD(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Hl(e,t.position)}function ID(e,t,n){const r=e.schema;let s=r;t.name==="svg"&&r.space==="html"&&(s=wp,e.schema=s),e.ancestors.push(t);const i=t.name===null?e.Fragment:Vw(e,t.name,!0),l=WD(e,t),a=Np(e,t);return Kw(e,l,i,t),jp(l,a),e.ancestors.pop(),e.schema=r,e.create(t,i,l,n)}function OD(e,t,n){const r={};return jp(r,Np(e,t)),e.create(t,e.Fragment,r,n)}function BD(e,t){return t.value}function Kw(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function jp(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function zD(e,t,n){return r;function r(s,i,l,a){const u=Array.isArray(l.children)?n:t;return a?u(i,l,a):u(i,l)}}function FD(e,t){return n;function n(r,s,i,l){const a=Array.isArray(i.children),c=kp(r);return t(s,i,l,a,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function $D(e,t){const n={};let r,s;for(s in t.properties)if(s!=="children"&&Cp.call(t.properties,s)){const i=HD(e,s,t.properties[s]);if(i){const[l,a]=i;e.tableCellAlignToStyle&&l==="align"&&typeof a=="string"&&TD.has(t.tagName)?r=a:n[l]=a}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function WD(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const a=l.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Hl(e,t.position);else{const s=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const a=r.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else Hl(e,t.position);else i=r.value===null?!0:r.value;n[s]=i}return n}function Np(e,t){const n=[];let r=-1;const s=e.passKeys?new Map:ED;for(;++rs?0:s+t:t=t>s?s:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),e.splice(...l);else for(n&&e.splice(t,n);i0?(on(e,e.length,0,t),e):t}const Kx={}.hasOwnProperty;function Yw(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Ln(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const It=Gr(/[A-Za-z]/),At=Gr(/[\dA-Za-z]/),JD=Gr(/[#-'*+\--9=?A-Z^-~]/);function sc(e){return e!==null&&(e<32||e===127)}const Xh=Gr(/\d/),ZD=Gr(/[\dA-Fa-f]/),eR=Gr(/[!-/:-@[-`{-~]/);function he(e){return e!==null&&e<-2}function Me(e){return e!==null&&(e<0||e===32)}function we(e){return e===-2||e===-1||e===32}const Pc=Gr(/\p{P}|\p{S}/u),ks=Gr(/\s/);function Gr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ji(e){const t=[];let n=-1,r=0,s=0;for(;++n55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(l=String.fromCharCode(i,a),s=1):l="�"}else l=String.fromCharCode(i);l&&(t.push(e.slice(r,n),encodeURIComponent(l)),r=n+s+1,l=""),s&&(n+=s,s=0)}return t.join("")+e.slice(r)}function je(e,t,n,r){const s=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return we(c)?(e.enter(n),a(c)):t(c)}function a(c){return we(c)&&i++l))return;const N=t.events.length;let D=N,A,k;for(;D--;)if(t.events[D][0]==="exit"&&t.events[D][1].type==="chunkFlow"){if(A){k=t.events[D][1].end;break}A=!0}for(v(r),S=N;S_;){const j=n[b];t.containerState=j[1],j[0].exit.call(t,e)}n.length=_}function y(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}function iR(e,t,n){return je(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function vi(e){if(e===null||Me(e)||ks(e))return 1;if(Pc(e))return 2}function Ac(e,t,n){const r=[];let s=-1;for(;++s1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},f={...e[n][1].start};Gx(d,-c),Gx(f,c),l={type:c>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},a={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},i={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},s={type:c>1?"strong":"emphasis",start:{...l.start},end:{...a.end}},e[r][1].end={...l.start},e[n][1].start={...a.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=xn(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=xn(u,[["enter",s,t],["enter",l,t],["exit",l,t],["enter",i,t]]),u=xn(u,Ac(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=xn(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",s,t]]),e[n][1].end.offset-e[n][1].start.offset?(h=2,u=xn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):h=0,on(e,r-1,n-r+3,u),n=r+u.length-h-2;break}}for(n=-1;++n0&&we(S)?je(e,y,"linePrefix",i+1)(S):y(S)}function y(S){return S===null||he(S)?e.check(Yx,x,b)(S):(e.enter("codeFlowValue"),_(S))}function _(S){return S===null||he(S)?(e.exit("codeFlowValue"),y(S)):(e.consume(S),_)}function b(S){return e.exit("codeFenced"),t(S)}function j(S,N,D){let A=0;return k;function k(I){return S.enter("lineEnding"),S.consume(I),S.exit("lineEnding"),R}function R(I){return S.enter("codeFencedFence"),we(I)?je(S,T,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):T(I)}function T(I){return I===a?(S.enter("codeFencedFenceSequence"),E(I)):D(I)}function E(I){return I===a?(A++,S.consume(I),E):A>=l?(S.exit("codeFencedFenceSequence"),we(I)?je(S,O,"whitespace")(I):O(I)):D(I)}function O(I){return I===null||he(I)?(S.exit("codeFencedFence"),N(I)):D(I)}}}function xR(e,t,n){const r=this;return s;function s(l){return l===null?n(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const Wu={name:"codeIndented",tokenize:yR},vR={partial:!0,tokenize:_R};function yR(e,t,n){const r=this;return s;function s(u){return e.enter("codeIndented"),je(e,i,"linePrefix",5)(u)}function i(u){const h=r.events[r.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(u):n(u)}function l(u){return u===null?c(u):he(u)?e.attempt(vR,l,c)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||he(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),a)}function c(u){return e.exit("codeIndented"),t(u)}}function _R(e,t,n){const r=this;return s;function s(l){return r.parser.lazy[r.now().line]?n(l):he(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s):je(e,i,"linePrefix",5)(l)}function i(l){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(l):he(l)?s(l):n(l)}}const bR={name:"codeText",previous:SR,resolve:wR,tokenize:kR};function wR(e){let t=e.length-4,n=3,r,s;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const s=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return r&&Xi(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Xi(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Xi(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):e.interrupt(r.parser.constructs.flow,n,t)(l)}}function tS(e,t,n,r,s,i,l,a,c){const u=c||Number.POSITIVE_INFINITY;let h=0;return d;function d(v){return v===60?(e.enter(r),e.enter(s),e.enter(i),e.consume(v),e.exit(i),f):v===null||v===32||v===41||sc(v)?n(v):(e.enter(r),e.enter(l),e.enter(a),e.enter("chunkString",{contentType:"string"}),x(v))}function f(v){return v===62?(e.enter(i),e.consume(v),e.exit(i),e.exit(s),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(a),f(v)):v===null||v===60||he(v)?n(v):(e.consume(v),v===92?m:p)}function m(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function x(v){return!h&&(v===null||v===41||Me(v))?(e.exit("chunkString"),e.exit(a),e.exit(l),e.exit(r),t(v)):h999||p===null||p===91||p===93&&!c||p===94&&!a&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(e.exit(i),e.enter(s),e.consume(p),e.exit(s),e.exit(r),t):he(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||he(p)||a++>999?(e.exit("chunkString"),h(p)):(e.consume(p),c||(c=!we(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),a++,d):d(p)}}function rS(e,t,n,r,s,i){let l;return a;function a(f){return f===34||f===39||f===40?(e.enter(r),e.enter(s),e.consume(f),e.exit(s),l=f===40?41:f,c):n(f)}function c(f){return f===l?(e.enter(s),e.consume(f),e.exit(s),e.exit(r),t):(e.enter(i),u(f))}function u(f){return f===l?(e.exit(i),c(l)):f===null?n(f):he(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),je(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===l||f===null||he(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:h)}function d(f){return f===l||f===92?(e.consume(f),h):h(f)}}function _l(e,t){let n;return r;function r(s){return he(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),n=!0,r):we(s)?je(e,r,n?"linePrefix":"lineSuffix")(s):t(s)}}const LR={name:"definition",tokenize:RR},DR={partial:!0,tokenize:MR};function RR(e,t,n){const r=this;let s;return i;function i(p){return e.enter("definition"),l(p)}function l(p){return nS.call(r,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return s=Ln(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),c):n(p)}function c(p){return Me(p)?_l(e,u)(p):u(p)}function u(p){return tS(e,h,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(DR,d,d)(p)}function d(p){return we(p)?je(e,f,"whitespace")(p):f(p)}function f(p){return p===null||he(p)?(e.exit("definition"),r.parser.defined.push(s),t(p)):n(p)}}function MR(e,t,n){return r;function r(a){return Me(a)?_l(e,s)(a):n(a)}function s(a){return rS(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return we(a)?je(e,l,"whitespace")(a):l(a)}function l(a){return a===null||he(a)?t(a):n(a)}}const IR={name:"hardBreakEscape",tokenize:OR};function OR(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),s}function s(i){return he(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const BR={name:"headingAtx",resolve:zR,tokenize:FR};function zR(e,t){let n=e.length-2,r=3,s,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(s={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},on(e,r,n-r+1,[["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t]])),e}function FR(e,t,n){let r=0;return s;function s(h){return e.enter("atxHeading"),i(h)}function i(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&r++<6?(e.consume(h),l):h===null||Me(h)?(e.exit("atxHeadingSequence"),a(h)):n(h)}function a(h){return h===35?(e.enter("atxHeadingSequence"),c(h)):h===null||he(h)?(e.exit("atxHeading"),t(h)):we(h)?je(e,a,"whitespace")(h):(e.enter("atxHeadingText"),u(h))}function c(h){return h===35?(e.consume(h),c):(e.exit("atxHeadingSequence"),a(h))}function u(h){return h===null||h===35||Me(h)?(e.exit("atxHeadingText"),a(h)):(e.consume(h),u)}}const $R=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Qx=["pre","script","style","textarea"],WR={concrete:!0,name:"htmlFlow",resolveTo:qR,tokenize:KR},HR={partial:!0,tokenize:GR},UR={partial:!0,tokenize:VR};function qR(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function KR(e,t,n){const r=this;let s,i,l,a,c;return u;function u(L){return h(L)}function h(L){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(L),d}function d(L){return L===33?(e.consume(L),f):L===47?(e.consume(L),i=!0,x):L===63?(e.consume(L),s=3,r.interrupt?t:C):It(L)?(e.consume(L),l=String.fromCharCode(L),w):n(L)}function f(L){return L===45?(e.consume(L),s=2,p):L===91?(e.consume(L),s=5,a=0,m):It(L)?(e.consume(L),s=4,r.interrupt?t:C):n(L)}function p(L){return L===45?(e.consume(L),r.interrupt?t:C):n(L)}function m(L){const se="CDATA[";return L===se.charCodeAt(a++)?(e.consume(L),a===se.length?r.interrupt?t:T:m):n(L)}function x(L){return It(L)?(e.consume(L),l=String.fromCharCode(L),w):n(L)}function w(L){if(L===null||L===47||L===62||Me(L)){const se=L===47,te=l.toLowerCase();return!se&&!i&&Qx.includes(te)?(s=1,r.interrupt?t(L):T(L)):$R.includes(l.toLowerCase())?(s=6,se?(e.consume(L),v):r.interrupt?t(L):T(L)):(s=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(L):i?y(L):_(L))}return L===45||At(L)?(e.consume(L),l+=String.fromCharCode(L),w):n(L)}function v(L){return L===62?(e.consume(L),r.interrupt?t:T):n(L)}function y(L){return we(L)?(e.consume(L),y):k(L)}function _(L){return L===47?(e.consume(L),k):L===58||L===95||It(L)?(e.consume(L),b):we(L)?(e.consume(L),_):k(L)}function b(L){return L===45||L===46||L===58||L===95||At(L)?(e.consume(L),b):j(L)}function j(L){return L===61?(e.consume(L),S):we(L)?(e.consume(L),j):_(L)}function S(L){return L===null||L===60||L===61||L===62||L===96?n(L):L===34||L===39?(e.consume(L),c=L,N):we(L)?(e.consume(L),S):D(L)}function N(L){return L===c?(e.consume(L),c=null,A):L===null||he(L)?n(L):(e.consume(L),N)}function D(L){return L===null||L===34||L===39||L===47||L===60||L===61||L===62||L===96||Me(L)?j(L):(e.consume(L),D)}function A(L){return L===47||L===62||we(L)?_(L):n(L)}function k(L){return L===62?(e.consume(L),R):n(L)}function R(L){return L===null||he(L)?T(L):we(L)?(e.consume(L),R):n(L)}function T(L){return L===45&&s===2?(e.consume(L),W):L===60&&s===1?(e.consume(L),G):L===62&&s===4?(e.consume(L),Q):L===63&&s===3?(e.consume(L),C):L===93&&s===5?(e.consume(L),z):he(L)&&(s===6||s===7)?(e.exit("htmlFlowData"),e.check(HR,q,E)(L)):L===null||he(L)?(e.exit("htmlFlowData"),E(L)):(e.consume(L),T)}function E(L){return e.check(UR,O,q)(L)}function O(L){return e.enter("lineEnding"),e.consume(L),e.exit("lineEnding"),I}function I(L){return L===null||he(L)?E(L):(e.enter("htmlFlowData"),T(L))}function W(L){return L===45?(e.consume(L),C):T(L)}function G(L){return L===47?(e.consume(L),l="",P):T(L)}function P(L){if(L===62){const se=l.toLowerCase();return Qx.includes(se)?(e.consume(L),Q):T(L)}return It(L)&&l.length<8?(e.consume(L),l+=String.fromCharCode(L),P):T(L)}function z(L){return L===93?(e.consume(L),C):T(L)}function C(L){return L===62?(e.consume(L),Q):L===45&&s===2?(e.consume(L),C):T(L)}function Q(L){return L===null||he(L)?(e.exit("htmlFlowData"),q(L)):(e.consume(L),Q)}function q(L){return e.exit("htmlFlow"),t(L)}}function VR(e,t,n){const r=this;return s;function s(l){return he(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i):n(l)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function GR(e,t,n){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(ro,t,n)}}const YR={name:"htmlText",tokenize:XR};function XR(e,t,n){const r=this;let s,i,l;return a;function a(C){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(C),c}function c(C){return C===33?(e.consume(C),u):C===47?(e.consume(C),j):C===63?(e.consume(C),_):It(C)?(e.consume(C),D):n(C)}function u(C){return C===45?(e.consume(C),h):C===91?(e.consume(C),i=0,m):It(C)?(e.consume(C),y):n(C)}function h(C){return C===45?(e.consume(C),p):n(C)}function d(C){return C===null?n(C):C===45?(e.consume(C),f):he(C)?(l=d,G(C)):(e.consume(C),d)}function f(C){return C===45?(e.consume(C),p):d(C)}function p(C){return C===62?W(C):C===45?f(C):d(C)}function m(C){const Q="CDATA[";return C===Q.charCodeAt(i++)?(e.consume(C),i===Q.length?x:m):n(C)}function x(C){return C===null?n(C):C===93?(e.consume(C),w):he(C)?(l=x,G(C)):(e.consume(C),x)}function w(C){return C===93?(e.consume(C),v):x(C)}function v(C){return C===62?W(C):C===93?(e.consume(C),v):x(C)}function y(C){return C===null||C===62?W(C):he(C)?(l=y,G(C)):(e.consume(C),y)}function _(C){return C===null?n(C):C===63?(e.consume(C),b):he(C)?(l=_,G(C)):(e.consume(C),_)}function b(C){return C===62?W(C):_(C)}function j(C){return It(C)?(e.consume(C),S):n(C)}function S(C){return C===45||At(C)?(e.consume(C),S):N(C)}function N(C){return he(C)?(l=N,G(C)):we(C)?(e.consume(C),N):W(C)}function D(C){return C===45||At(C)?(e.consume(C),D):C===47||C===62||Me(C)?A(C):n(C)}function A(C){return C===47?(e.consume(C),W):C===58||C===95||It(C)?(e.consume(C),k):he(C)?(l=A,G(C)):we(C)?(e.consume(C),A):W(C)}function k(C){return C===45||C===46||C===58||C===95||At(C)?(e.consume(C),k):R(C)}function R(C){return C===61?(e.consume(C),T):he(C)?(l=R,G(C)):we(C)?(e.consume(C),R):A(C)}function T(C){return C===null||C===60||C===61||C===62||C===96?n(C):C===34||C===39?(e.consume(C),s=C,E):he(C)?(l=T,G(C)):we(C)?(e.consume(C),T):(e.consume(C),O)}function E(C){return C===s?(e.consume(C),s=void 0,I):C===null?n(C):he(C)?(l=E,G(C)):(e.consume(C),E)}function O(C){return C===null||C===34||C===39||C===60||C===61||C===96?n(C):C===47||C===62||Me(C)?A(C):(e.consume(C),O)}function I(C){return C===47||C===62||Me(C)?A(C):n(C)}function W(C){return C===62?(e.consume(C),e.exit("htmlTextData"),e.exit("htmlText"),t):n(C)}function G(C){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),P}function P(C){return we(C)?je(e,z,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):z(C)}function z(C){return e.enter("htmlTextData"),l(C)}}const Ap={name:"labelEnd",resolveAll:eM,resolveTo:tM,tokenize:nM},QR={tokenize:rM},JR={tokenize:sM},ZR={tokenize:iM};function eM(e){let t=-1;const n=[];for(;++t=3&&(u===null||he(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===s?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),we(u)?je(e,a,"whitespace")(u):a(u))}}const Ht={continuation:{tokenize:mM},exit:xM,name:"list",tokenize:pM},hM={partial:!0,tokenize:vM},fM={partial:!0,tokenize:gM};function pM(e,t,n){const r=this,s=r.events[r.events.length-1];let i=s&&s[1].type==="linePrefix"?s[2].sliceSerialize(s[1],!0).length:0,l=0;return a;function a(p){const m=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Xh(p)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(xa,n,u)(p):u(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(p)}return n(p)}function c(p){return Xh(p)&&++l<10?(e.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(ro,r.interrupt?n:h,e.attempt(hM,f,d))}function h(p){return r.containerState.initialBlankLine=!0,i++,f(p)}function d(p){return we(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function mM(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(ro,s,i);function s(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,je(e,t,"listItemIndent",r.containerState.size+1)(a)}function i(a){return r.containerState.furtherBlankLines||!we(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(fM,t,l)(a))}function l(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,je(e,e.attempt(Ht,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function gM(e,t,n){const r=this;return je(e,s,"listItemIndent",r.containerState.size+1);function s(i){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(i):n(i)}}function xM(e){e.exit(this.containerState.type)}function vM(e,t,n){const r=this;return je(e,s,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function s(i){const l=r.events[r.events.length-1];return!we(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Jx={name:"setextUnderline",resolveTo:yM,tokenize:_M};function yM(e,t){let n=e.length,r,s,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(s=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const l={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",l,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=l,e.push(["exit",l,t]),e}function _M(e,t,n){const r=this;let s;return i;function i(u){let h=r.events.length,d;for(;h--;)if(r.events[h][1].type!=="lineEnding"&&r.events[h][1].type!=="linePrefix"&&r.events[h][1].type!=="content"){d=r.events[h][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),s=u,l(u)):n(u)}function l(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===s?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),we(u)?je(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||he(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const bM={tokenize:wM};function wM(e){const t=this,n=e.attempt(ro,r,e.attempt(this.parser.constructs.flowInitial,s,je(e,e.attempt(this.parser.constructs.flow,s,e.attempt(NR,s)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function s(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const SM={resolveAll:iS()},kM=sS("string"),CM=sS("text");function sS(e){return{resolveAll:iS(e==="text"?jM:void 0),tokenize:t};function t(n){const r=this,s=this.parser.constructs[e],i=n.attempt(s,l,a);return l;function l(h){return u(h)?i(h):a(h)}function a(h){if(h===null){n.consume(h);return}return n.enter("data"),n.consume(h),c}function c(h){return u(h)?(n.exit("data"),i(h)):(n.consume(h),c)}function u(h){if(h===null)return!0;const d=s[h];let f=-1;if(d)for(;++f-1){const a=l[0];typeof a=="string"?l[0]=a.slice(r):l.shift()}i>0&&l.push(e[s].slice(0,i))}return l}function zM(e,t){let n=-1;const r=[];let s;for(;++n0){const kn=xe.tokenStack[xe.tokenStack.length-1];(kn[1]||ev).call(xe,void 0,kn[0])}for(ne.position={start:wr(H.length>0?H[0][1].start:{line:1,column:1,offset:0}),end:wr(H.length>0?H[H.length-2][1].end:{line:1,column:1,offset:0})},De=-1;++De0&&(r.className=["language-"+s[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function ZM(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function eI(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function tI(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),s=ji(r.toLowerCase()),i=e.footnoteOrder.indexOf(r);let l,a=e.footnoteCounts.get(r);a===void 0?(a=0,e.footnoteOrder.push(r),l=e.footnoteOrder.length):l=i+1,a+=1,e.footnoteCounts.set(r,a);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+s,id:n+"fnref-"+s+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function nI(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function rI(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function aS(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const s=e.all(t),i=s[0];i&&i.type==="text"?i.value="["+i.value:s.unshift({type:"text",value:"["});const l=s[s.length-1];return l&&l.type==="text"?l.value+=r:s.push({type:"text",value:r}),s}function sI(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return aS(e,t);const s={src:ji(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(t,i),e.applyData(t,i)}function iI(e,t){const n={src:ji(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function lI(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function oI(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return aS(e,t);const s={href:ji(r.url||"")};r.title!==null&&r.title!==void 0&&(s.title=r.title);const i={type:"element",tagName:"a",properties:s,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function aI(e,t){const n={href:ji(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function cI(e,t,n){const r=e.all(t),s=n?uI(n):cS(t),i={},l=[];if(typeof t.checked=="boolean"){const h=r[0];let d;h&&h.type==="element"&&h.tagName==="p"?d=h:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let a=-1;for(;++a1}function dI(e,t){const n={},r=e.all(t);let s=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++s0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},a=kp(t.children[1]),c=Ww(t.children[t.children.length-1]);a&&c&&(l.position={start:a,end:c}),s.push(l)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function gI(e,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,a=l?l.length:t.children.length;let c=-1;const u=[];for(;++c0,!0),r[0]),s=r.index+r[0].length,r=n.exec(t);return i.push(rv(t.slice(s),s>0,!1)),i.join("")}function rv(e,t,n){let r=0,s=e.length;if(t){let i=e.codePointAt(r);for(;i===tv||i===nv;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(s-1);for(;i===tv||i===nv;)s--,i=e.codePointAt(s-1)}return s>r?e.slice(r,s):""}function yI(e,t){const n={type:"text",value:vI(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function _I(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const bI={blockquote:XM,break:QM,code:JM,delete:ZM,emphasis:eI,footnoteReference:tI,heading:nI,html:rI,imageReference:sI,image:iI,inlineCode:lI,linkReference:oI,link:aI,listItem:cI,list:dI,paragraph:hI,root:fI,strong:pI,table:mI,tableCell:xI,tableRow:gI,text:yI,thematicBreak:_I,toml:Oo,yaml:Oo,definition:Oo,footnoteDefinition:Oo};function Oo(){}const uS=-1,Tc=0,bl=1,ic=2,Tp=3,Lp=4,Dp=5,Rp=6,dS=7,hS=8,wI=typeof self=="object"?self:globalThis,sv=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new wI[e](t)},SI=(e,t)=>{const n=(s,i)=>(e.set(i,s),s),r=s=>{if(e.has(s))return e.get(s);const[i,l]=t[s];switch(i){case Tc:case uS:return n(l,s);case bl:{const a=n([],s);for(const c of l)a.push(r(c));return a}case ic:{const a=n({},s);for(const[c,u]of l)a[r(c)]=r(u);return a}case Tp:return n(new Date(l),s);case Lp:{const{source:a,flags:c}=l;return n(new RegExp(a,c),s)}case Dp:{const a=n(new Map,s);for(const[c,u]of l)a.set(r(c),r(u));return a}case Rp:{const a=n(new Set,s);for(const c of l)a.add(r(c));return a}case dS:{const{name:a,message:c}=l;return n(sv(a,c),s)}case hS:return n(BigInt(l),s);case"BigInt":return n(Object(BigInt(l)),s);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:a}=new Uint8Array(l);return n(new DataView(a),l)}}return n(sv(i,l),s)};return r},iv=e=>SI(new Map,e)(0),Bs="",{toString:kI}={},{keys:CI}=Object,Qi=e=>{const t=typeof e;if(t!=="object"||!e)return[Tc,t];const n=kI.call(e).slice(8,-1);switch(n){case"Array":return[bl,Bs];case"Object":return[ic,Bs];case"Date":return[Tp,Bs];case"RegExp":return[Lp,Bs];case"Map":return[Dp,Bs];case"Set":return[Rp,Bs];case"DataView":return[bl,n]}return n.includes("Array")?[bl,n]:n.includes("Error")?[dS,n]:[ic,n]},Bo=([e,t])=>e===Tc&&(t==="function"||t==="symbol"),jI=(e,t,n,r)=>{const s=(l,a)=>{const c=r.push(l)-1;return n.set(a,c),c},i=l=>{if(n.has(l))return n.get(l);let[a,c]=Qi(l);switch(a){case Tc:{let h=l;switch(c){case"bigint":a=hS,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);h=null;break;case"undefined":return s([uS],l)}return s([a,h],l)}case bl:{if(c){let f=l;return c==="DataView"?f=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(f=new Uint8Array(l)),s([c,[...f]],l)}const h=[],d=s([a,h],l);for(const f of l)h.push(i(f));return d}case ic:{if(c)switch(c){case"BigInt":return s([c,l.toString()],l);case"Boolean":case"Number":case"String":return s([c,l.valueOf()],l)}if(t&&"toJSON"in l)return i(l.toJSON());const h=[],d=s([a,h],l);for(const f of CI(l))(e||!Bo(Qi(l[f])))&&h.push([i(f),i(l[f])]);return d}case Tp:return s([a,l.toISOString()],l);case Lp:{const{source:h,flags:d}=l;return s([a,{source:h,flags:d}],l)}case Dp:{const h=[],d=s([a,h],l);for(const[f,p]of l)(e||!(Bo(Qi(f))||Bo(Qi(p))))&&h.push([i(f),i(p)]);return d}case Rp:{const h=[],d=s([a,h],l);for(const f of l)(e||!Bo(Qi(f)))&&h.push(i(f));return d}}const{message:u}=l;return s([a,{name:c,message:u}],l)};return i},lv=(e,{json:t,lossy:n}={})=>{const r=[];return jI(!(t||n),!!t,new Map,r)(e),r},lc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?iv(lv(e,t)):structuredClone(e):(e,t)=>iv(lv(e,t));function NI(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function EI(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function PI(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||NI,r=e.options.footnoteBackLabel||EI,s=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let c=-1;for(;++c0&&m.push({type:"text",value:" "});let y=typeof n=="string"?n:n(c,p);typeof y=="string"&&(y={type:"text",value:y}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const w=h[h.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const y=w.children[w.children.length-1];y&&y.type==="text"?y.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...m)}else h.push(...m);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(h,!0)};e.patch(u,v),a.push(v)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...lc(l),id:"footnote-label"},children:[{type:"text",value:s}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:` -`}]}}const Lc=function(e){if(e==null)return DI;if(typeof e=="function")return Dc(e);if(typeof e=="object")return Array.isArray(e)?AI(e):TI(e);if(typeof e=="string")return LI(e);throw new Error("Expected function, string, or object as test")};function AI(e){const t=[];let n=-1;for(;++n":""))+")"})}return f;function f(){let p=fS,m,x,w;if((!t||i(c,u,h[h.length-1]||void 0))&&(p=OI(n(c,h)),p[0]===Jh))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==II)for(x=(r?v.children.length:-1)+l,w=h.concat(v);x>-1&&x0&&n.push({type:"text",value:` -`}),n}function ov(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function av(e,t){const n=zI(e,t),r=n.one(e,void 0),s=PI(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return s&&i.children.push({type:"text",value:` -`},s),i}function UI(e,t){return e&&"run"in e?async function(n,r){const s=av(n,{file:r,...t});await e.run(s,r)}:function(n,r){return av(n,{file:r,...e||t})}}function cv(e){if(e)throw e}var va=Object.prototype.hasOwnProperty,mS=Object.prototype.toString,uv=Object.defineProperty,dv=Object.getOwnPropertyDescriptor,hv=function(t){return typeof Array.isArray=="function"?Array.isArray(t):mS.call(t)==="[object Array]"},fv=function(t){if(!t||mS.call(t)!=="[object Object]")return!1;var n=va.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&va.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var s;for(s in t);return typeof s>"u"||va.call(t,s)},pv=function(t,n){uv&&n.name==="__proto__"?uv(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},mv=function(t,n){if(n==="__proto__")if(va.call(t,n)){if(dv)return dv(t,n).value}else return;return t[n]},qI=function e(){var t,n,r,s,i,l,a=arguments[0],c=1,u=arguments.length,h=!1;for(typeof a=="boolean"&&(h=a,a=arguments[1]||{},c=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});cl.length;let c;a&&l.push(s);try{c=e.apply(this,l)}catch(u){const h=u;if(a&&n)throw h;return s(h)}a||(c&&c.then&&typeof c.then=="function"?c.then(i,s):c instanceof Error?s(c):i(c))}function s(l,...a){n||(n=!0,t(l,...a))}function i(l){s(null,l)}}const $n={basename:GI,dirname:YI,extname:XI,join:QI,sep:"/"};function GI(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');so(e);let n=0,r=-1,s=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else r<0&&(i=!0,r=s+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,a=t.length-1;for(;s--;)if(e.codePointAt(s)===47){if(i){n=s+1;break}}else l<0&&(i=!0,l=s+1),a>-1&&(e.codePointAt(s)===t.codePointAt(a--)?a<0&&(r=s):(a=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function YI(e){if(so(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function XI(e){so(e);let t=e.length,n=-1,r=0,s=-1,i=0,l;for(;t--;){const a=e.codePointAt(t);if(a===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),a===46?s<0?s=t:i!==1&&(i=1):s>-1&&(i=-1)}return s<0||n<0||i===0||i===1&&s===n-1&&s===r+1?"":e.slice(s,n)}function QI(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function ZI(e,t){let n="",r=0,s=-1,i=0,l=-1,a,c;for(;++l<=e.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,i=0;continue}}else if(n.length>0){n="",r=0,s=l,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,i=0}else a===46&&i>-1?i++:i=-1}return n}function so(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const e3={cwd:t3};function t3(){return"/"}function tf(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function n3(e){if(typeof e=="string")e=new URL(e);else if(!tf(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return r3(e)}function r3(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[p,...m]=h;const x=r[f][1];ef(x)&&ef(p)&&(p=Uu(!0,x,p)),r[f]=[u,p,...m]}}}}const o3=new Ip().freeze();function Gu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Yu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Xu(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function xv(e){if(!ef(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function vv(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function zo(e){return a3(e)?e:new gS(e)}function a3(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function c3(e){return typeof e=="string"||u3(e)}function u3(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const d3="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",yv=[],_v={allowDangerousHtml:!0},h3=/^(https?|ircs?|mailto|xmpp)$/i,f3=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function xS(e){const t=p3(e),n=m3(e);return g3(t.runSync(t.parse(n),n),e)}function p3(e){const t=e.rehypePlugins||yv,n=e.remarkPlugins||yv,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,..._v}:_v;return o3().use(YM).use(n).use(UI,r).use(t)}function m3(e){const t=e.children||"",n=new gS;return typeof t=="string"&&(n.value=t),n}function g3(e,t){const n=t.allowedElements,r=t.allowElement,s=t.components,i=t.disallowedElements,l=t.skipHtml,a=t.unwrapDisallowed,c=t.urlTransform||x3;for(const h of f3)Object.hasOwn(t,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+d3+h.id,void 0);return Mp(e,u),LD(e,{Fragment:o.Fragment,components:s,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(h,d,f){if(h.type==="raw"&&f&&typeof d=="number")return l?f.children.splice(d,1):f.children[d]={type:"text",value:h.value},d;if(h.type==="element"){let p;for(p in $u)if(Object.hasOwn($u,p)&&Object.hasOwn(h.properties,p)){const m=h.properties[p],x=$u[p];(x===null||x.includes(h.tagName))&&(h.properties[p]=c(String(m||""),p,h))}}if(h.type==="element"){let p=n?!n.includes(h.tagName):i?i.includes(h.tagName):!1;if(!p&&r&&typeof d=="number"&&(p=!r(h,d,f)),p&&f&&typeof d=="number")return a&&h.children?f.children.splice(d,1,...h.children):f.children.splice(d,1),d}}}function x3(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),s=e.indexOf("/");return t===-1||s!==-1&&t>s||n!==-1&&t>n||r!==-1&&t>r||h3.test(e.slice(0,t))?e:""}function bv(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,s=n.indexOf(t);for(;s!==-1;)r++,s=n.indexOf(t,s+t.length);return r}function v3(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function y3(e,t,n){const s=Lc((n||{}).ignore||[]),i=_3(t);let l=-1;for(;++l0?{type:"text",value:S}:void 0),S===!1?f.lastIndex=b+1:(m!==b&&y.push({type:"text",value:u.value.slice(m,b)}),Array.isArray(S)?y.push(...S):S&&y.push(S),m=b+_[0].length,v=!0),!f.global)break;_=f.exec(u.value)}return v?(m?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const s=bv(e,"(");let i=bv(e,")");for(;r!==-1&&s>i;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[e,n]}function vS(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||ks(n)||Pc(n))&&(!t||n!==47)}yS.peek=H3;function M3(){this.buffer()}function I3(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function O3(){this.buffer()}function B3(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function z3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ln(this.sliceSerialize(e)).toLowerCase(),n.label=t}function F3(e){this.exit(e)}function $3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ln(this.sliceSerialize(e)).toLowerCase(),n.label=t}function W3(e){this.exit(e)}function H3(){return"["}function yS(e,t,n,r){const s=n.createTracker(r);let i=s.move("[^");const l=n.enter("footnoteReference"),a=n.enter("reference");return i+=s.move(n.safe(n.associationId(e),{after:"]",before:i})),a(),l(),i+=s.move("]"),i}function U3(){return{enter:{gfmFootnoteCallString:M3,gfmFootnoteCall:I3,gfmFootnoteDefinitionLabelString:O3,gfmFootnoteDefinition:B3},exit:{gfmFootnoteCallString:z3,gfmFootnoteCall:F3,gfmFootnoteDefinitionLabelString:$3,gfmFootnoteDefinition:W3}}}function q3(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:yS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,s,i,l){const a=i.createTracker(l);let c=a.move("[^");const u=i.enter("footnoteDefinition"),h=i.enter("label");return c+=a.move(i.safe(i.associationId(r),{before:c,after:"]"})),h(),c+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),c+=a.move((t?` -`:" ")+i.indentLines(i.containerFlow(r,a.current()),t?_S:K3))),u(),c}}function K3(e,t,n){return t===0?e:_S(e,t,n)}function _S(e,t,n){return(n?"":" ")+e}const V3=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];bS.peek=J3;function G3(){return{canContainEols:["delete"],enter:{strikethrough:X3},exit:{strikethrough:Q3}}}function Y3(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:V3}],handlers:{delete:bS}}}function X3(e){this.enter({type:"delete",children:[]},e)}function Q3(e){this.exit(e)}function bS(e,t,n,r){const s=n.createTracker(r),i=n.enter("strikethrough");let l=s.move("~~");return l+=n.containerPhrasing(e,{...s.current(),before:l,after:"~"}),l+=s.move("~~"),i(),l}function J3(){return"~"}function Z3(e){return e.length}function e5(e,t){const n=t||{},r=(n.align||[]).concat(),s=n.stringLength||Z3,i=[],l=[],a=[],c=[];let u=0,h=-1;for(;++hu&&(u=e[h].length);++vc[v])&&(c[v]=_)}x.push(y)}l[h]=x,a[h]=w}let d=-1;if(typeof r=="object"&&"length"in r)for(;++dc[d]&&(c[d]=y),p[d]=y),f[d]=_}l.splice(1,0,f),a.splice(1,0,p),h=-1;const m=[];for(;++h "),i.shift(2);const l=n.indentLines(n.containerFlow(e,i.current()),r5);return s(),l}function r5(e,t,n){return">"+(n?"":" ")+e}function s5(e,t){return Sv(e,t.inConstruct,!0)&&!Sv(e,t.notInConstruct,!1)}function Sv(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++rl&&(l=i):i=1,s=r+t.length,r=n.indexOf(t,s);return l}function l5(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function o5(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function a5(e,t,n,r){const s=o5(n),i=e.value||"",l=s==="`"?"GraveAccent":"Tilde";if(l5(e,n)){const d=n.enter("codeIndented"),f=n.indentLines(i,c5);return d(),f}const a=n.createTracker(r),c=s.repeat(Math.max(i5(i,s)+1,3)),u=n.enter("codeFenced");let h=a.move(c);if(e.lang){const d=n.enter(`codeFencedLang${l}`);h+=a.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...a.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${l}`);h+=a.move(" "),h+=a.move(n.safe(e.meta,{before:h,after:` -`,encode:["`"],...a.current()})),d()}return h+=a.move(` -`),i&&(h+=a.move(i+` -`)),h+=a.move(c),u(),h}function c5(e,t,n){return(n?"":" ")+e}function Op(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function u5(e,t,n,r){const s=Op(n),i=s==='"'?"Quote":"Apostrophe",l=n.enter("definition");let a=n.enter("label");const c=n.createTracker(r);let u=c.move("[");return u+=c.move(n.safe(n.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),a(),!e.url||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(a=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":` -`,...c.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(n.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),a()),l(),u}function d5(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ul(e){return"&#x"+e.toString(16).toUpperCase()+";"}function oc(e,t,n){const r=vi(e),s=vi(t);return r===void 0?s===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:s===void 0?{inside:!1,outside:!1}:s===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}wS.peek=h5;function wS(e,t,n,r){const s=d5(n),i=n.enter("emphasis"),l=n.createTracker(r),a=l.move(s);let c=l.move(n.containerPhrasing(e,{after:s,before:a,...l.current()}));const u=c.charCodeAt(0),h=oc(r.before.charCodeAt(r.before.length-1),u,s);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=oc(r.after.charCodeAt(0),d,s);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},a+c+p}function h5(e,t,n){return n.options.emphasis||"*"}function f5(e,t){let n=!1;return Mp(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Jh}),!!((!e.depth||e.depth<3)&&Ep(e)&&(t.options.setext||n))}function p5(e,t,n,r){const s=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(f5(e,n)){const h=n.enter("headingSetext"),d=n.enter("phrasing"),f=n.containerPhrasing(e,{...i.current(),before:` -`,after:` -`});return d(),h(),f+` -`+(s===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(` -`))+1))}const l="#".repeat(s),a=n.enter("headingAtx"),c=n.enter("phrasing");i.move(l+" ");let u=n.containerPhrasing(e,{before:"# ",after:` -`,...i.current()});return/^[\t ]/.test(u)&&(u=Ul(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,n.options.closeAtx&&(u+=" "+l),c(),a(),u}SS.peek=m5;function SS(e){return e.value||""}function m5(){return"<"}kS.peek=g5;function kS(e,t,n,r){const s=Op(n),i=s==='"'?"Quote":"Apostrophe",l=n.enter("image");let a=n.enter("label");const c=n.createTracker(r);let u=c.move("![");return u+=c.move(n.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),a(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(a=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(a=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),a(),e.title&&(a=n.enter(`title${i}`),u+=c.move(" "+s),u+=c.move(n.safe(e.title,{before:u,after:s,...c.current()})),u+=c.move(s),a()),u+=c.move(")"),l(),u}function g5(){return"!"}CS.peek=x5;function CS(e,t,n,r){const s=e.referenceType,i=n.enter("imageReference");let l=n.enter("label");const a=n.createTracker(r);let c=a.move("![");const u=n.safe(e.alt,{before:c,after:"]",...a.current()});c+=a.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...a.current()});return l(),n.stack=h,i(),s==="full"||!u||u!==d?c+=a.move(d+"]"):s==="shortcut"?c=c.slice(0,-1):c+=a.move("]"),c}function x5(){return"!"}jS.peek=v5;function jS(e,t,n){let r=e.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i\u007F]/.test(e.url))}ES.peek=y5;function ES(e,t,n,r){const s=Op(n),i=s==='"'?"Quote":"Apostrophe",l=n.createTracker(r);let a,c;if(NS(e,n)){const h=n.stack;n.stack=[],a=n.enter("autolink");let d=l.move("<");return d+=l.move(n.containerPhrasing(e,{before:d,after:">",...l.current()})),d+=l.move(">"),a(),n.stack=h,d}a=n.enter("link"),c=n.enter("label");let u=l.move("[");return u+=l.move(n.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(c=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),c(),e.title&&(c=n.enter(`title${i}`),u+=l.move(" "+s),u+=l.move(n.safe(e.title,{before:u,after:s,...l.current()})),u+=l.move(s),c()),u+=l.move(")"),a(),u}function y5(e,t,n){return NS(e,n)?"<":"["}PS.peek=_5;function PS(e,t,n,r){const s=e.referenceType,i=n.enter("linkReference");let l=n.enter("label");const a=n.createTracker(r);let c=a.move("[");const u=n.containerPhrasing(e,{before:c,after:"]",...a.current()});c+=a.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...a.current()});return l(),n.stack=h,i(),s==="full"||!u||u!==d?c+=a.move(d+"]"):s==="shortcut"?c=c.slice(0,-1):c+=a.move("]"),c}function _5(){return"["}function Bp(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function b5(e){const t=Bp(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function w5(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function AS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function S5(e,t,n,r){const s=n.enter("list"),i=n.bulletCurrent;let l=e.ordered?w5(n):Bp(n);const a=e.ordered?l==="."?")":".":b5(n);let c=t&&n.bulletLastUsed?l===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),AS(n)===l&&h){let d=-1;for(;++d-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let l=i.length+1;(s==="tab"||s==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(l=Math.ceil(l/4)*4);const a=n.createTracker(r);a.move(i+" ".repeat(l-i.length)),a.shift(l);const c=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,a.current()),h);return c(),u;function h(d,f,p){return f?(p?"":" ".repeat(l))+d:(p?i:i+" ".repeat(l-i.length))+d}}function j5(e,t,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),l=n.containerPhrasing(e,r);return i(),s(),l}const N5=Lc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function E5(e,t,n,r){return(e.children.some(function(l){return N5(l)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function P5(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}TS.peek=A5;function TS(e,t,n,r){const s=P5(n),i=n.enter("strong"),l=n.createTracker(r),a=l.move(s+s);let c=l.move(n.containerPhrasing(e,{after:s,before:a,...l.current()}));const u=c.charCodeAt(0),h=oc(r.before.charCodeAt(r.before.length-1),u,s);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=oc(r.after.charCodeAt(0),d,s);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},a+c+p}function A5(e,t,n){return n.options.strong||"*"}function T5(e,t,n,r){return n.safe(e.value,r)}function L5(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function D5(e,t,n){const r=(AS(n)+(n.options.ruleSpaces?" ":"")).repeat(L5(n));return n.options.ruleSpaces?r.slice(0,-1):r}const LS={blockquote:n5,break:kv,code:a5,definition:u5,emphasis:wS,hardBreak:kv,heading:p5,html:SS,image:kS,imageReference:CS,inlineCode:jS,link:ES,linkReference:PS,list:S5,listItem:C5,paragraph:j5,root:E5,strong:TS,text:T5,thematicBreak:D5};function R5(){return{enter:{table:M5,tableData:Cv,tableHeader:Cv,tableRow:O5},exit:{codeText:B5,table:I5,tableData:ed,tableHeader:ed,tableRow:ed}}}function M5(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function I5(e){this.exit(e),this.data.inTable=void 0}function O5(e){this.enter({type:"tableRow",children:[]},e)}function ed(e){this.exit(e)}function Cv(e){this.enter({type:"tableCell",children:[]},e)}function B5(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,z5));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function z5(e,t){return t==="|"?t:e}function F5(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,s=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:c,tableRow:a}};function l(p,m,x,w){return u(h(p,x,w),p.align)}function a(p,m,x,w){const v=d(p,x,w),y=u([v]);return y.slice(0,y.indexOf(` -`))}function c(p,m,x,w){const v=x.enter("tableCell"),y=x.enter("phrasing"),_=x.containerPhrasing(p,{...w,before:i,after:i});return y(),v(),_}function u(p,m){return e5(p,{align:m,alignDelimiters:r,padding:n,stringLength:s})}function h(p,m,x){const w=p.children;let v=-1;const y=[],_=m.enter("table");for(;++v0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const sO={tokenize:hO,partial:!0};function iO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:cO,continuation:{tokenize:uO},exit:dO}},text:{91:{name:"gfmFootnoteCall",tokenize:aO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:lO,resolveTo:oO}}}}function lO(e,t,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let l;for(;s--;){const c=r.events[s][1];if(c.type==="labelImage"){l=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return a;function a(c){if(!l||!l._balanced)return n(c);const u=Ln(r.sliceSerialize({start:l.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function oO(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},a=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",i,t],["enter",l,t],["exit",l,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...a),e}function aO(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,l;return a;function a(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),c}function c(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(i>999||d===93&&!l||d===null||d===91||Me(d))return n(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return s.includes(Ln(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return Me(d)||(l=!0),i++,e.consume(d),d===92?h:u}function h(d){return d===91||d===92||d===93?(e.consume(d),i++,u):u(d)}}function cO(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,l=0,a;return c;function c(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):n(m)}function h(m){if(l>999||m===93&&!a||m===null||m===91||Me(m))return n(m);if(m===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return i=Ln(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Me(m)||(a=!0),l++,e.consume(m),m===92?d:h}function d(m){return m===91||m===92||m===93?(e.consume(m),l++,h):h(m)}function f(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),s.includes(i)||s.push(i),je(e,p,"gfmFootnoteDefinitionWhitespace")):n(m)}function p(m){return t(m)}}function uO(e,t,n){return e.check(ro,t,e.attempt(sO,t,n))}function dO(e){e.exit("gfmFootnoteDefinition")}function hO(e,t,n){const r=this;return je(e,s,"gfmFootnoteDefinitionIndent",5);function s(i){const l=r.events[r.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?t(i):n(i)}}function fO(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(l,a){let c=-1;for(;++c1?c(m):(l.consume(m),d++,p);if(d<2&&!n)return c(m);const w=l.exit("strikethroughSequenceTemporary"),v=vi(m);return w._open=!v||v===2&&!!x,w._close=!x||x===2&&!!v,a(m)}}}class pO{constructor(){this.map=[]}add(t,n,r){mO(this,t,n,r)}consume(t){if(this.map.sort(function(i,l){return i[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const i of s)t.push(i);s=r.pop()}this.map.length=0}}function mO(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s-1;){const O=r.events[R][1].type;if(O==="lineEnding"||O==="linePrefix")R--;else break}const T=R>-1?r.events[R][1].type:null,E=T==="tableHead"||T==="tableRow"?S:c;return E===S&&r.parser.lazy[r.now().line]?n(k):E(k)}function c(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(l=!0,i+=1),h(k)}function h(k){return k===null?n(k):he(k)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),p):n(k):we(k)?je(e,h,"whitespace")(k):(i+=1,l&&(l=!1,s+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),d(k)))}function d(k){return k===null||k===124||Me(k)?(e.exit("data"),h(k)):(e.consume(k),k===92?f:d)}function f(k){return k===92||k===124?(e.consume(k),d):d(k)}function p(k){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(k):(e.enter("tableDelimiterRow"),l=!1,we(k)?je(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):m(k))}function m(k){return k===45||k===58?w(k):k===124?(l=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),x):j(k)}function x(k){return we(k)?je(e,w,"whitespace")(k):w(k)}function w(k){return k===58?(i+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),v):k===45?(i+=1,v(k)):k===null||he(k)?b(k):j(k)}function v(k){return k===45?(e.enter("tableDelimiterFiller"),y(k)):j(k)}function y(k){return k===45?(e.consume(k),y):k===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(k))}function _(k){return we(k)?je(e,b,"whitespace")(k):b(k)}function b(k){return k===124?m(k):k===null||he(k)?!l||s!==i?j(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):j(k)}function j(k){return n(k)}function S(k){return e.enter("tableRow"),N(k)}function N(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),N):k===null||he(k)?(e.exit("tableRow"),t(k)):we(k)?je(e,N,"whitespace")(k):(e.enter("data"),D(k))}function D(k){return k===null||k===124||Me(k)?(e.exit("data"),N(k)):(e.consume(k),k===92?A:D)}function A(k){return k===92||k===124?(e.consume(k),D):D(k)}}function yO(e,t){let n=-1,r=!0,s=0,i=[0,0,0,0],l=[0,0,0,0],a=!1,c=0,u,h,d;const f=new pO;for(;++nn[2]+1){const m=n[2]+1,x=n[3]-n[2]-1;e.add(m,x,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return s!==void 0&&(i.end=Object.assign({},Ws(t.events,s)),e.add(s,0,[["exit",i,t]]),i=void 0),i}function Nv(e,t,n,r,s){const i=[],l=Ws(t.events,n);s&&(s.end=Object.assign({},l),i.push(["exit",s,t])),r.end=Object.assign({},l),i.push(["exit",r,t]),e.add(n+1,0,i)}function Ws(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const _O={name:"tasklistCheck",tokenize:wO};function bO(){return{text:{91:_O}}}function wO(e,t,n){const r=this;return s;function s(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),i)}function i(c){return Me(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),l):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),l):n(c)}function l(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),a):n(c)}function a(c){return he(c)?t(c):we(c)?e.check({tokenize:SO},t,n)(c):n(c)}}function SO(e,t,n){return je(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function kO(e){return Yw([Y5(),iO(),fO(e),xO(),bO()])}const CO={};function $S(e){const t=this,n=e||CO,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),l=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(kO(n)),i.push(q5()),l.push(K5(n))}function jO({template:e,profiles:t,onSave:n,onClose:r,busy:s=!1}){const[i,l]=g.useState(e?.name??""),[a,c]=g.useState(e?.contentMd??""),[u,h]=g.useState(e?.defaultProfileId??""),[d,f]=g.useState("edit"),p=i.trim().length>0&&!s;async function m(x){x.preventDefault(),p&&await n(i.trim(),a,u)}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"template editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:e?`Edit template — ${e.name}`:"New template"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close template editor",onClick:r,disabled:s,children:"✕"})]}),o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"te-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ie,{id:"te-name","aria-label":"template name",placeholder:"My template",value:i,onChange:x=>l(x.target.value),disabled:s,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"te-profile",className:"text-xs font-medium text-muted",children:"Default profile"}),t.length>0?o.jsxs("select",{id:"te-profile","aria-label":"template default profile",value:u,onChange:x=>h(x.target.value),disabled:s,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"— none —"}),t.map(x=>o.jsx("option",{value:x.id,children:x.name},x.id))]}):o.jsx(ie,{id:"te-profile","aria-label":"template default profile",placeholder:"profile-id (optional)",value:u,onChange:x=>h(x.target.value),disabled:s,className:"min-w-48"})]})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>o.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":d===x,onClick:()=>f(x),className:U("px-4 py-2 text-sm font-medium capitalize transition-colors",d===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:d==="edit"?o.jsx("textarea",{"aria-label":"template content",value:a,onChange:x=>c(x.target.value),disabled:s,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Agent instructions - -...`}):o.jsx("div",{className:U("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:a.trim()?o.jsx(xS,{remarkPlugins:[$S],children:a}):o.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:r,disabled:s,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save template",disabled:!p,loading:s,children:"Save"})]})]})]})}function Ji(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NO(){const{template:e}=ue(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(!1),a=g.useCallback(async()=>{l(!0),s(null);try{const f=await e.listTemplates();n(f)}catch(f){s(Ji(f))}finally{l(!1)}},[e]);g.useEffect(()=>{a()},[a]);const c=g.useCallback(async f=>{l(!0),s(null);try{const p=await e.createTemplate(f);n(m=>[...m,p])}catch(p){s(Ji(p))}finally{l(!1)}},[e]),u=g.useCallback(async(f,p)=>{l(!0),s(null);try{const m=await e.updateTemplate(f,p);n(x=>x.map(w=>w.id===f?m:w))}catch(m){s(Ji(m))}finally{l(!1)}},[e]),h=g.useCallback(async f=>{l(!0),s(null);try{await e.deleteTemplate(f),n(p=>p.filter(m=>m.id!==f))}catch(p){s(Ji(p))}finally{l(!1)}},[e]),d=g.useCallback(async(f,p,m)=>{l(!0),s(null);try{await e.createAgentFromTemplate(f,p,m)}catch(x){s(Ji(x))}finally{l(!1)}},[e]);return{templates:t,error:r,busy:i,refresh:a,createTemplate:c,updateTemplate:u,deleteTemplate:h,createAgentFromTemplate:d}}function WS({projectId:e}){const t=NO(),{profile:n}=ue(),[r,s]=g.useState([]),[i,l]=g.useState(!1),[a,c]=g.useState(null),[u,h]=g.useState(!1);async function d(p){if(!i){try{const m=await n.listProfiles();s(m)}catch{}l(!0)}c(p)}async function f(p,m,x){if(a){h(!0);try{a.mode==="create"?await t.createTemplate({name:p,content:m,defaultProfileId:x}):await t.updateTemplate(a.template.id,m),c(null)}finally{h(!1)}}}return o.jsxs(o.Fragment,{children:[a!==null&&o.jsx(jO,{template:a.mode==="edit"?a.template:null,profiles:r,onSave:f,onClose:()=>c(null),busy:u}),o.jsxs(ke,{title:"Templates",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Templates"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Ie,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create template",disabled:t.busy,onClick:()=>void d({mode:"create"}),children:"New template"})]})]}),o.jsx("div",{className:"p-4",children:t.templates.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No templates yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.templates.map(p=>o.jsx("li",{className:"flex flex-col gap-2 py-3 first:pt-0 last:pb-0",children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"font-medium text-content",children:p.name}),o.jsxs("span",{className:"text-xs text-muted",children:["v",p.version]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit ${p.name}`,disabled:t.busy,onClick:()=>void d({mode:"edit",template:p}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"primary","aria-label":`create agent from ${p.name}`,disabled:t.busy,onClick:()=>void t.createAgentFromTemplate(e,p.id),children:"Create agent"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete template ${p.name}`,disabled:t.busy,onClick:()=>void t.deleteTemplate(p.id),className:"text-danger hover:text-danger",children:"Delete"})]})]})},p.id))})})]})]})}function EO({skill:e,onSave:t,onClose:n,busy:r=!1}){const[s,i]=g.useState(e?.name??""),[l,a]=g.useState(e?.contentMd??""),[c,u]=g.useState(e?.scope??"project"),[h,d]=g.useState("edit"),f=e!=null,p=s.trim().length>0&&l.trim().length>0&&!r;async function m(x){x.preventDefault(),p&&await t(s.trim(),l,c)}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"skill editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:f?`Edit skill — ${e.name}`:"New skill"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close skill editor",onClick:n,disabled:r,children:"✕"})]}),o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"se-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ie,{id:"se-name","aria-label":"skill name",placeholder:"My skill",value:s,onChange:x=>i(x.target.value),disabled:r,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"se-scope",className:"text-xs font-medium text-muted",children:"Scope"}),o.jsxs("select",{id:"se-scope","aria-label":"skill scope",value:c,onChange:x=>u(x.target.value),disabled:r||f,className:U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"project",children:"Project"}),o.jsx("option",{value:"global",children:"Global"})]})]})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>o.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":h===x,onClick:()=>d(x),className:U("px-4 py-2 text-sm font-medium capitalize transition-colors",h===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:h==="edit"?o.jsx("textarea",{"aria-label":"skill content",value:l,onChange:x=>a(x.target.value),disabled:r,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Skill workflow - -...`}):o.jsx("div",{className:U("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:l.trim()?o.jsx(xS,{remarkPlugins:[$S],children:l}):o.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:n,disabled:r,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save skill",disabled:!p,loading:r,children:"Save"})]})]})]})}function $o(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function PO(e){const{skill:t}=ue(),[n,r]=g.useState([]),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState(!1),h=g.useCallback(async()=>{if(e){u(!0),a(null);try{const[x,w]=await Promise.all([t.listSkills(e,"global"),t.listSkills(e,"project")]);r(x),i(w)}catch(x){a($o(x))}finally{u(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=x=>x==="global"?r:i,f=g.useCallback(async x=>{u(!0),a(null);try{const w=await t.createSkill({...x,projectId:e});d(x.scope)(v=>[...v,w])}catch(w){a($o(w))}finally{u(!1)}},[t,e]),p=g.useCallback(async(x,w,v)=>{u(!0),a(null);try{const y=await t.updateSkill(e,x,w,v);d(x)(_=>_.map(b=>b.id===w?y:b))}catch(y){a($o(y))}finally{u(!1)}},[t,e]),m=g.useCallback(async(x,w)=>{u(!0),a(null);try{await t.deleteSkill(e,x,w),d(x)(v=>v.filter(y=>y.id!==w))}catch(v){a($o(v))}finally{u(!1)}},[t,e]);return{globalSkills:n,projectSkills:s,error:l,busy:c,refresh:h,createSkill:f,updateSkill:p,deleteSkill:m}}function HS({projectId:e}){const t=PO(e),[n,r]=g.useState(null),[s,i]=g.useState(!1);async function l(c,u,h){if(n){i(!0);try{n.mode==="create"?await t.createSkill({name:c,content:u,scope:h}):await t.updateSkill(n.skill.scope,n.skill.id,u),r(null)}finally{i(!1)}}}function a(c,u){return o.jsx("div",{className:"p-4",children:u.length===0?o.jsxs("p",{className:"text-sm text-muted",children:["No ",c," skills yet."]}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.map(h=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[o.jsx("span",{className:"min-w-0 font-medium text-content",children:h.name}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit skill ${h.name}`,disabled:t.busy,onClick:()=>r({mode:"edit",skill:h}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete skill ${h.name}`,disabled:t.busy,onClick:()=>void t.deleteSkill(h.scope,h.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},h.id))})})}return o.jsxs(o.Fragment,{children:[n!==null&&o.jsx(EO,{skill:n.mode==="edit"?n.skill:null,onSave:l,onClose:()=>r(null),busy:s}),o.jsxs(ke,{title:"Skills",className:"flex flex-col gap-0",children:[t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Skills"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Ie,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create skill",disabled:t.busy,onClick:()=>r({mode:"create"}),children:"New skill"})]})]}),o.jsx("div",{className:"border-b border-border px-4 pt-3",children:o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Project"})}),a("project",t.projectSkills),o.jsx("div",{className:"border-y border-border px-4 pt-3",children:o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Global"})}),a("global",t.globalSkills)]})]})}function td(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function US(){const{embedder:e}=ue(),[t,n]=g.useState([]),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{const[p,m]=await Promise.all([e.listEmbedderProfiles(),e.describeEmbedderEngines()]);n(p),s(m)}catch(p){l(td(p))}finally{c(!1)}},[e]);g.useEffect(()=>{u()},[u]);const h=g.useCallback(async p=>{c(!0),l(null);try{await e.saveEmbedderProfile(p),await u()}catch(m){l(td(m)),c(!1)}},[e,u]),d=g.useCallback(async p=>{c(!0),l(null);try{await e.deleteEmbedderProfile(p),await u()}catch(m){l(td(m)),c(!1)}},[e,u]),f=t.find(p=>p.strategy!=="none")??null;return{profiles:t,engines:r,active:f,error:i,busy:a,refresh:u,saveProfile:h,deleteProfile:d}}const qS="http://localhost:11434/api/embeddings",KS="https://api.openai.com/v1/embeddings",nd=[{strategy:"none",key:"none",label:"None (naïve recall)"},{strategy:"localOnnx",key:"localOnnx",label:"Local ONNX"},{strategy:"localServer",key:"localServer",label:"Ollama (local server)"},{strategy:"api",key:"api",label:"API"},{strategy:"api",key:"custom",label:"Custom"}],Hs={id:"",name:"",model:"",endpoint:"",apiKeyEnv:"",dimension:"",onnxEngineId:""};function AO(e,t,n){if(n)return{id:n.id,name:n.name,model:n.model??"",endpoint:n.endpoint??"",apiKeyEnv:n.apiKeyEnv??"",dimension:String(n.dimension),onnxEngineId:e==="localOnnx"?t.find(r=>r.id===n.model)?.id??t[0]?.id??"":""};switch(e){case"localOnnx":{const r=t.find(s=>s.recommended)??t[0];return{...Hs,id:"onnx-local",name:r?.displayName??"Local ONNX",model:r?.id??"",dimension:r?String(r.dimension):"",onnxEngineId:r?.id??""}}case"localServer":return{...Hs,id:"ollama",name:"Ollama",endpoint:qS,model:"nomic-embed-text",dimension:"768"};case"api":return{...Hs,id:"api",name:"API embedder",endpoint:KS,apiKeyEnv:"OPENAI_API_KEY",model:"text-embedding-3-small",dimension:"1536"};case"custom":return{...Hs,id:"custom",name:"Custom embedder"};default:return{...Hs}}}function TO(e,t){switch(e){case"none":return!0;case"localOnnx":return t.vectorOnnxEnabled;case"localServer":case"api":return t.vectorHttpEnabled}}function VS(){const e=US(),[t,n]=g.useState("localOnnx"),[r,s]=g.useState(Hs),i=e.engines?.recommendedOnnx??[],l={vectorOnnxEnabled:e.engines?.vectorOnnxEnabled??!1,vectorHttpEnabled:e.engines?.vectorHttpEnabled??!1};g.useEffect(()=>{if(!e.engines)return;const y=nd.find(b=>b.key===t),_=e.active&&y&&e.active.strategy===y.strategy?e.active:null;s(AO(t,e.engines.recommendedOnnx,_))},[e.engines,e.active,t]);const c=nd.find(y=>y.key===t).strategy;function u(y){s(_=>({..._,...y}))}function h(y){const _=i.find(b=>b.id===y);u({onnxEngineId:y,model:_?.id??y,dimension:_?String(_.dimension):r.dimension})}const d=Number.parseInt(r.dimension,10),f=g.useMemo(()=>c==="none"?{ok:!0}:r.id.trim()?r.name.trim()?!Number.isFinite(d)||d<=0?{ok:!1,msg:"Dimension must be a positive number."}:(c==="localServer"||c==="api")&&!r.endpoint.trim()?{ok:!1,msg:"Endpoint is required."}:{ok:!0}:{ok:!1,msg:"Name is required."}:{ok:!1,msg:"Id is required."},[c,r,d]);function p(){return{id:r.id.trim(),name:r.name.trim(),strategy:c,dimension:d,model:r.model.trim()||void 0,endpoint:(c==="localServer"||c==="api")&&r.endpoint.trim()||void 0,apiKeyEnv:c==="api"&&r.apiKeyEnv.trim()||void 0}}async function m(){f.ok&&await e.saveProfile(p())}async function x(){for(const y of e.profiles)await e.deleteProfile(y.id);n("none")}const w=U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),v=e.active!==null;return o.jsxs(ke,{title:"Memory / Embedder",className:"flex flex-col gap-0",children:[e.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[o.jsx("p",{className:"rounded-md border border-border bg-raised px-3 py-2 text-xs text-muted","data-testid":"embedder-restart-note",children:"The embedder change takes effect at the next app start."}),o.jsxs("p",{className:"text-xs text-faint","data-testid":"embedder-active",children:["Current:"," ",v?o.jsxs("span",{className:"text-content",children:["Vector — ",e.active.strategy,e.active.model?` ${e.active.model}`:""]}):o.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),o.jsxs("fieldset",{className:"flex flex-col gap-2","aria-label":"embedder strategy",children:[o.jsx("legend",{className:"mb-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Strategy"}),nd.map(y=>{const _=TO(y.strategy,l),b=y.key==="localOnnx";return o.jsxs("label",{className:U("flex items-center gap-2 rounded-md border px-3 py-2 text-sm",t===y.key?"border-primary bg-raised":"border-border",!_&&"opacity-50"),"data-testid":`embedder-strategy-${y.key}`,children:[o.jsx("input",{type:"radio",name:"embedder-strategy",value:y.key,checked:t===y.key,disabled:!_,onChange:()=>n(y.key),"aria-label":y.label}),o.jsx("span",{className:"text-content",children:y.label}),b&&o.jsx("span",{className:"rounded border border-primary/40 bg-primary/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-primary",children:"Recommended"}),!_&&o.jsx("span",{className:"text-[11px] text-faint",children:"not available in this build"})]},y.key)})]}),c!=="none"&&o.jsxs("div",{className:"flex flex-col gap-3",children:[c==="localOnnx"&&o.jsx(qt,{label:"ONNX model",children:({id:y})=>o.jsx("select",{id:y,"aria-label":"onnx model",className:w,value:r.onnxEngineId,disabled:e.busy,onChange:_=>h(_.target.value),children:i.map(_=>o.jsxs("option",{value:_.id,children:[_.displayName,_.recommended?" — recommended":""," (dim"," ",_.dimension,", ~",_.approxSizeMb," MB)"]},_.id))})}),(c==="localServer"||c==="api")&&o.jsx(qt,{label:"Endpoint",children:({id:y})=>o.jsx(ie,{id:y,"aria-label":"endpoint",placeholder:c==="localServer"?qS:KS,value:r.endpoint,disabled:e.busy,onChange:_=>u({endpoint:_.target.value})})}),c==="api"&&o.jsx(qt,{label:"API key environment variable",hint:"Name of the env var holding the key — never the key itself.",children:({id:y,describedBy:_})=>o.jsx(ie,{id:y,"aria-label":"api key env var",placeholder:"OPENAI_API_KEY","aria-describedby":_,value:r.apiKeyEnv,disabled:e.busy,onChange:b=>u({apiKeyEnv:b.target.value})})}),c!=="localOnnx"&&o.jsx(qt,{label:"Model",children:({id:y})=>o.jsx(ie,{id:y,"aria-label":"model",placeholder:"model name",value:r.model,disabled:e.busy,onChange:_=>u({model:_.target.value})})}),o.jsx(qt,{label:"Dimension",error:f.ok?void 0:f.msg,children:({id:y,describedBy:_})=>o.jsx(ie,{id:y,"aria-label":"dimension",type:"number",min:1,value:r.dimension,"aria-describedby":_,disabled:e.busy,onChange:b=>u({dimension:b.target.value})})}),o.jsx(qt,{label:"Profile id",children:({id:y})=>o.jsx(ie,{id:y,"aria-label":"profile id",placeholder:"my-embedder",value:r.id,disabled:e.busy,onChange:_=>u({id:_.target.value})})}),o.jsx(qt,{label:"Profile name",children:({id:y})=>o.jsx(ie,{id:y,"aria-label":"profile name",placeholder:"My embedder",value:r.name,disabled:e.busy,onChange:_=>u({name:_.target.value})})})]}),o.jsxs("div",{className:"flex items-center gap-2 border-t border-border pt-3",children:[e.busy&&o.jsx(Ie,{size:14}),c!=="none"&&o.jsx(M,{type:"button",variant:"primary","aria-label":"save embedder",disabled:e.busy||!f.ok,onClick:()=>void m(),children:"Save"}),o.jsx(M,{type:"button","aria-label":"back to none",disabled:e.busy,onClick:()=>void x(),children:"Back to None"})]})]})]})}const LO=["user","feedback","project","reference"];function DO({entry:e,loadContent:t,resolveLinks:n,onCreate:r,onUpdate:s,onClose:i,busy:l=!1}){const a=e!=null,[c,u]=g.useState(e?.title??""),[h,d]=g.useState(e?.hook??""),[f,p]=g.useState(e?.type??"project"),[m,x]=g.useState(""),[w,v]=g.useState([]);g.useEffect(()=>{if(!e)return;let j=!1;return(async()=>{try{if(t){const S=await t(e.slug);j||x(S)}if(n){const S=await n(e.slug);j||v(S)}}catch{}})(),()=>{j=!0}},[e,t,n]);const y=h.trim().length>0&&m.trim().length>0&&!l&&(a||c.trim().length>0);async function _(j){j.preventDefault(),y&&(a?await s(e.slug,h.trim(),f,m):await r(c.trim(),h.trim(),f,m))}const b=U("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"memory editor",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[o.jsx("h2",{className:"text-sm font-semibold text-content",children:a?`Edit note — ${e.title}`:"New note"}),o.jsx(M,{type:"button",variant:"ghost","aria-label":"close memory editor",onClick:i,disabled:l,children:"✕"})]}),o.jsxs("form",{onSubmit:j=>void _(j),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a?o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Slug"}),o.jsx("code",{className:"truncate rounded-md border border-border bg-raised px-3 py-2 text-sm text-muted",children:e.slug})]}):o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsx("label",{htmlFor:"me-name",className:"text-xs font-medium text-muted",children:"Name"}),o.jsx(ie,{id:"me-name","aria-label":"memory name",placeholder:"My note",value:c,onChange:j=>u(j.target.value),disabled:l,className:"min-w-48"})]}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsx("label",{htmlFor:"me-type",className:"text-xs font-medium text-muted",children:"Type"}),o.jsx("select",{id:"me-type","aria-label":"memory type",value:f,onChange:j=>p(j.target.value),disabled:l,className:b,children:LO.map(j=>o.jsx("option",{value:j,children:j},j))})]})]}),o.jsxs("div",{className:"flex shrink-0 flex-col gap-1 border-b border-border px-4 py-3",children:[o.jsx("label",{htmlFor:"me-description",className:"text-xs font-medium text-muted",children:"Description"}),o.jsx(ie,{id:"me-description","aria-label":"memory description",placeholder:"One-line hook",value:h,onChange:j=>d(j.target.value),disabled:l})]}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:[o.jsx("label",{htmlFor:"me-content",className:"mb-1 text-xs font-medium text-muted",children:"Content"}),o.jsx("textarea",{id:"me-content","aria-label":"memory content",value:m,onChange:j=>x(j.target.value),disabled:l,className:U("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Note - -Use [[other-slug]] to link…`}),a&&o.jsxs("div",{className:"mt-3 shrink-0",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Links"}),w.length===0?o.jsx("p",{className:"mt-1 text-sm text-muted",children:"No resolved links."}):o.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:w.map(j=>o.jsx("li",{className:"rounded-md border border-border bg-raised px-2 py-0.5 text-xs text-muted",children:j},j))})]})]}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[o.jsx(M,{type:"button",variant:"ghost",onClick:i,disabled:l,children:"Cancel"}),o.jsx(M,{type:"submit",variant:"primary","aria-label":"Save note",disabled:!y,loading:l,children:"Save"})]})]})]})}function Wo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function RO(e){const{memory:t,system:n}=ue(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(!1),u=g.useCallback(async()=>{if(e){c(!0),l(null);try{s(await t.readIndex(e))}catch(m){l(Wo(m))}finally{c(!1)}}},[t,e]);g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let m,x=!1;return n.onDomainEvent(w=>{w.type==="memorySaved"&&u()}).then(w=>{x?w():m=w}),()=>{x=!0,m?.()}},[u,n]);const h=g.useCallback(async m=>{c(!0),l(null);try{await t.createMemory({...m,projectId:e}),await u()}catch(x){l(Wo(x)),c(!1)}},[t,e,u]),d=g.useCallback(async(m,x,w,v)=>{c(!0),l(null);try{await t.updateMemory(e,m,x,w,v),await u()}catch(y){l(Wo(y)),c(!1)}},[t,e,u]),f=g.useCallback(async m=>{c(!0),l(null);try{await t.deleteMemory(e,m),await u()}catch(x){l(Wo(x)),c(!1)}},[t,e,u]),p=g.useCallback(m=>t.resolveLinks(e,m),[t,e]);return{entries:r,error:i,busy:a,refresh:u,createMemory:h,updateMemory:d,deleteMemory:f,resolveLinks:p}}function GS({projectId:e}){const t=RO(e),n=US(),{memory:r}=ue(),[s,i]=g.useState(null),[l,a]=g.useState(!1),c=g.useCallback(async d=>(await r.getMemory(e,d)).content,[r,e]);async function u(d,f,p,m){a(!0);try{await t.createMemory({name:d,description:f,type:p,content:m}),i(null)}finally{a(!1)}}async function h(d,f,p,m){a(!0);try{await t.updateMemory(d,f,p,m),i(null)}finally{a(!1)}}return o.jsxs(o.Fragment,{children:[s!==null&&o.jsx(DO,{entry:s.mode==="edit"?s.entry:null,loadContent:c,resolveLinks:t.resolveLinks,onCreate:u,onUpdate:h,onClose:()=>i(null),busy:l}),o.jsxs(ke,{title:"Memory",className:"flex flex-col gap-0",children:[o.jsxs("p",{className:"border-b border-border px-4 py-2 text-xs text-faint","data-testid":"memory-tier",children:["Tier:"," ",n.active?o.jsxs("span",{className:"text-content",children:["Vector — ",n.active.strategy,n.active.model?` ${n.active.model}`:""]}):o.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Notes"}),o.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&o.jsx(Ie,{size:14}),o.jsx(M,{type:"button",variant:"primary","aria-label":"create memory",disabled:t.busy,onClick:()=>i({mode:"create"}),children:"New note"})]})]}),o.jsx("div",{className:"p-4",children:t.entries.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No memory notes yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.entries.map(d=>o.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"min-w-0 truncate font-medium text-content",children:d.title}),o.jsx("span",{className:"shrink-0 rounded border border-border bg-raised px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted",children:d.type})]}),o.jsx("span",{className:"truncate text-xs text-muted",children:d.hook})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit memory ${d.title}`,disabled:t.busy,onClick:()=>i({mode:"edit",entry:d}),children:"Edit"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete memory ${d.title}`,disabled:t.busy,onClick:()=>void t.deleteMemory(d.slug),className:"text-danger hover:text-danger",children:"Delete"})]})]},d.slug))})})]})]})}const Ev=[{id:"readProject",label:"Lecture projet",tools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read"]},{id:"readTickets",label:"Lecture tickets",tools:["idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"]},{id:"delegation",label:"Délégation agents",tools:["idea_ask_agent","idea_launch_agent","idea_stop_agent"]},{id:"contextMemory",label:"Contexte et mémoire",tools:["idea_update_context","idea_context_propose","idea_memory_write"]},{id:"tickets",label:"Tickets",tools:["idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]},{id:"work",label:"Travail et exécution",tools:["idea_run_in_background","idea_workstate_set"]},{id:"skills",label:"Skills",tools:["idea_create_skill"]}],MO={idea_list_agents:"Lister les agents",idea_context_read:"Lire le contexte d'un agent",idea_memory_read:"Lire la mémoire projet",idea_skill_read:"Lire un skill",idea_workstate_read:"Lire l'état de travail",idea_ticket_read:"Lire un ticket",idea_ticket_list:"Lister les tickets",idea_ticket_read_carnet:"Lire le carnet d'un ticket",idea_sprint_list:"Lister les sprints",idea_ask_agent:"Déléguer à un agent",idea_launch_agent:"Lancer un agent",idea_stop_agent:"Arrêter un agent",idea_update_context:"Modifier le contexte d'un agent",idea_context_propose:"Proposer un contexte",idea_memory_write:"Écrire la mémoire projet",idea_workstate_set:"Écrire l'état de travail",idea_create_skill:"Créer un skill",idea_ticket_create:"Créer un ticket",idea_ticket_update:"Modifier un ticket",idea_ticket_update_status:"Modifier le statut d'un ticket",idea_ticket_update_priority:"Modifier la priorité d'un ticket",idea_ticket_update_carnet:"Modifier le carnet d'un ticket",idea_ticket_link:"Lier des tickets",idea_ticket_unlink:"Délier des tickets",idea_run_in_background:"Exécuter une commande en arrière-plan"};function IO(e){return MO[e]??e}function Ho(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function OO(e){const{permission:t}=ue(),[n,r]=g.useState(null),[s,i]=g.useState(!1),[l,a]=g.useState(!1),[c,u]=g.useState(null),h=g.useCallback(async()=>{if(t){i(!0),u(null);try{r(await t.getMcpToolPermissions(e))}catch(m){u(Ho(m))}finally{i(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=g.useCallback(async m=>{if(t){a(!0),u(null);try{r(await t.updateProjectMcpToolPermissions(e,m))}catch(x){throw u(Ho(x)),x}finally{a(!1)}}},[t,e]),f=g.useCallback(async(m,x)=>{if(t){a(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,x))}catch(w){throw u(Ho(w)),w}finally{a(!1)}}},[t,e]),p=g.useCallback(async m=>{if(t){a(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,null))}catch(x){throw u(Ho(x)),x}finally{a(!1)}}},[t,e]);return{doc:n,loading:s,busy:l,error:c,refresh:h,saveProjectDefault:d,saveAgentOverride:f,resetAgentOverride:p}}const BO=new Set(["readProject","readTickets"]);function zO(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function FO(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(r=>n.has(r))}function $O({projectId:e,agents:t}){const n=OO(e),[r,s]=g.useState({type:"project"}),i=g.useRef(!1);function l(u){i.current&&!window.confirm("Des modifications non enregistrées seront perdues. Continuer ?")||(i.current=!1,s(u))}if(n.loading&&!n.doc)return o.jsxs("div",{"data-testid":"mcp-tool-permissions-skeleton",className:"flex flex-col gap-3 p-4",children:[o.jsx("div",{className:"h-4 w-40 animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),o.jsx("div",{className:"h-32 w-full animate-pulse rounded bg-raised"})]});if(n.error&&!n.doc)return o.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[o.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),o.jsx(M,{size:"sm",onClick:()=>void n.refresh(),children:"Réessayer"})]});if(!n.doc)return null;const a=n.doc,c=r.type==="agent"?a.agents.find(u=>u.agentId===r.agentId)??null:null;return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4 md:flex-row",children:[o.jsxs("nav",{"aria-label":"cibles des permissions MCP",className:"flex w-full shrink-0 flex-col gap-2 md:w-56",children:[o.jsxs("button",{type:"button","aria-pressed":r.type==="project",onClick:()=>l({type:"project"}),className:U("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",r.type==="project"?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsx("span",{className:"font-medium text-content",children:"Défaut projet"}),o.jsx("span",{className:"text-xs text-muted",children:a.projectDefault?"Personnalisé":"Lecture seule"})]}),o.jsx("h4",{className:"mt-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun agent dans ce projet."}):o.jsx("ul",{className:"flex flex-col gap-1.5",children:t.map(u=>{const h=a.agents.some(f=>f.agentId===u.id),d=r.type==="agent"&&r.agentId===u.id;return o.jsx("li",{children:o.jsxs("button",{type:"button","aria-pressed":d,onClick:()=>l({type:"agent",agentId:u.id,agentName:u.name}),className:U("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",d?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsx("span",{className:"truncate font-medium text-content",children:u.name}),o.jsx("span",{className:U("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",h?"bg-warning/15 text-warning":"bg-primary/10 text-muted"),children:h?"Override":"Hérité"})]})},u.id)})})]}),o.jsx("div",{className:"min-w-0 flex-1",children:r.type==="project"?o.jsx(Pv,{targetKind:"project",title:"Tools MCP IdeA — Défaut projet",catalogue:a.catalogue,storedAllowed:a.projectDefault?.allowedTools??null,comparisonBaseline:a.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{i.current=u},onSaveProjectDefault:async u=>{await n.saveProjectDefault({allowedTools:u})}},"project"):o.jsx(Pv,{targetKind:"agent",title:`Tools MCP IdeA — ${r.agentName}`,catalogue:a.catalogue,storedAllowed:c?.policy.allowedTools??null,comparisonBaseline:a.projectDefault?.allowedTools??a.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{i.current=u},onSaveAgentOverride:async u=>{await n.saveAgentOverride(r.agentId,{allowedTools:u})},onResetOverride:async()=>{await n.resetAgentOverride(r.agentId)}},r.agentId)})]})}function Pv({targetKind:e,title:t,catalogue:n,storedAllowed:r,comparisonBaseline:s,busy:i,onDirtyChange:l,onSaveProjectDefault:a,onSaveAgentOverride:c,onResetOverride:u}){const h=r??s,[d,f]=g.useState(e==="project"||r!=null),[p,m]=g.useState(r!=null),[x,w]=g.useState(h),[v,y]=g.useState(h),[_,b]=g.useState(!1),[j,S]=g.useState(!1),[N,D]=g.useState(null),[A,k]=g.useState(()=>Object.fromEntries(Ev.map(se=>[se.id,BO.has(se.id)?e==="project":!0]))),R=e==="project"||d,T=R?x:s,E=R&&!FO(x,v);g.useEffect(()=>{l(E)},[E]),g.useEffect(()=>{if(!j)return;const se=window.setTimeout(()=>S(!1),2e3);return()=>window.clearTimeout(se)},[j]);const O=n.readOnlyTools.filter(se=>T.includes(se)).length,I=n.writeActionTools.filter(se=>T.includes(se)).length,W=g.useMemo(()=>new Set([...n.readOnlyTools,...n.writeActionTools]),[n]),G=g.useMemo(()=>Array.from(new Set([...T,...s])).filter(se=>!W.has(se)),[T,s,W]);function P(se){D(null),w(te=>zO(te,se))}function z(se){k(te=>({...te,[se]:!te[se]}))}function C(){f(!0),w(s),y(s)}function Q(){w(v),b(!1),D(null)}async function q(){if(D(null),e==="project"){if(x.some(te=>n.writeActionTools.includes(te)&&!v.includes(te))&&!_){b(!0);return}b(!1);try{await a?.(x),y(x),S(!0)}catch(te){D(rd(te))}return}try{await c?.(x),y(x),m(!0),S(!0)}catch(se){D(rd(se))}}async function L(){D(null);try{await u?.(),f(!1),m(!1),w(s),y(s),S(!0)}catch(se){D(rd(se))}}return o.jsx(ke,{title:t,className:"flex h-full flex-col",flush:!0,children:o.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e==="agent"&&o.jsx("p",{className:"text-xs text-muted",children:d?"Override personnalisé":"Hérite du défaut projet"}),e==="agent"&&!d&&o.jsx(M,{size:"sm",onClick:C,disabled:i,children:"Créer un override"}),o.jsxs("div",{children:[o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Résumé effectif"}),o.jsxs("p",{className:"text-sm text-content",children:[O," lecture autorisés · ",I," écriture autorisé",I>1?"s":""]})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Détail des tools"}),Ev.map(se=>o.jsx(Av,{group:se,expanded:A[se.id]??!0,onToggle:()=>z(se.id),catalogue:n,editable:R,targetKind:e,draftSet:x,displaySet:T,comparisonBaseline:s,onToggleTool:P},se.id)),G.length>0&&o.jsx(Av,{group:{id:"unknown",label:"Tools inconnus",tools:G},expanded:A.unknown??!0,onToggle:()=>z("unknown"),catalogue:n,editable:!1,targetKind:e,draftSet:x,displaySet:T,comparisonBaseline:s,onToggleTool:P,unknown:!0})]}),_&&o.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning",children:[o.jsx("p",{children:"Ce tool sera autorisé pour tous les agents sans override. Confirmer cette modification ?"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>b(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"primary",onClick:()=>void q(),children:"Confirmer"})]})]}),N&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:N}),j&&o.jsx("p",{role:"status",className:"text-sm text-success",children:"Permissions enregistrées"}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[o.jsx("div",{children:E&&o.jsx("span",{className:"text-xs text-warning",children:"Modifications non enregistrées"})}),o.jsxs("div",{className:"flex gap-2",children:[e==="agent"&&p&&o.jsx(M,{size:"sm",variant:"ghost",disabled:i,onClick:()=>void L(),children:"Réinitialiser l'override"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:i||!E,onClick:Q,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"primary",disabled:i||!R||!E,loading:i&&E,onClick:()=>void q(),children:"Enregistrer"})]})]})]})})}function Av({group:e,expanded:t,onToggle:n,catalogue:r,editable:s,targetKind:i,displaySet:l,comparisonBaseline:a,onToggleTool:c,unknown:u}){const h=e.tools.filter(f=>l.includes(f)).length,d=e.tools.length;return o.jsxs("div",{className:"rounded-md border border-border",children:[o.jsxs("button",{type:"button","aria-expanded":t,"aria-label":`${e.label}, ${h} sur ${d} autorisé${d>1?"s":""}`,onClick:n,className:"flex min-h-[32px] w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-raised",children:[o.jsx("span",{className:"font-medium text-content",children:e.label}),o.jsxs("span",{className:"text-xs text-muted",children:[h,"/",d," autorisés"]})]}),t&&o.jsx("ul",{className:"flex flex-col divide-y divide-border border-t border-border",children:e.tools.map(f=>o.jsx(UO,{tool:f,isRead:r.readOnlyTools.includes(f),unknown:u,editable:s,checked:l.includes(f),status:WO(f,s,i,l,a,u),onToggle:()=>c(f)},f))})]})}function WO(e,t,n,r,s,i){if(i)return"unknown";if(n==="agent"&&!t)return"inherited";if(n==="agent"&&t){const l=r.includes(e),a=s.includes(e);return l&&!a?"added":!l&&a?"removed":l?"allowed":"denied"}return r.includes(e)?"allowed":"denied"}const HO={allowed:"Autorisé",denied:"Refusé",inherited:"Hérité",added:"Ajouté",removed:"Retiré",unknown:"Inconnu"};function UO({tool:e,isRead:t,unknown:n,editable:r,checked:s,status:i,onToggle:l}){const a=IO(e),c=`mcp-tool-${e}`;return o.jsxs("li",{className:"flex min-h-[32px] items-center gap-2 px-3 py-1.5",children:[o.jsx("input",{id:c,type:"checkbox",checked:s,disabled:!r||n,onChange:l,"aria-label":`${a}, ${e}`}),o.jsxs("label",{htmlFor:c,className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"font-mono text-xs text-content",children:e}),!n&&o.jsx("span",{className:U("rounded-full px-1.5 py-0.5 text-[10px] font-medium",t?"bg-primary/10 text-primary":"bg-warning/15 text-warning"),children:t?"Lecture":"Écriture"})]}),o.jsx("span",{className:"text-xs text-muted",children:a})]}),o.jsx("span",{className:U("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",i==="allowed"||i==="added"?"bg-success/15 text-success":i==="denied"||i==="removed"?"bg-danger/10 text-muted":i==="unknown"?"bg-danger/15 text-danger":"bg-primary/10 text-muted"),children:HO[i]})]})}function rd(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Tv={fallback:"ask",read:"none",write:"none",delete:"none",executeBash:"none"},YS=["read","write","delete","executeBash"];function ts(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function XS(e){if(!e)return{...Tv};const t={...Tv,fallback:e.fallback};for(const n of YS)t[n]=qO(e.rules,n);return t}function qO(e,t){const n=e.filter(r=>r.capability===t);return n.some(r=>r.effect==="deny")?"deny":n.some(r=>r.effect==="allow")?"allow":"none"}function Lv(e){const t=[];for(const n of YS){const r=e[n];r!=="none"&&t.push(KO(n,r))}return{fallback:e.fallback,rules:t}}function KO(e,t){return e==="executeBash"?{capability:e,effect:t,commands:[]}:{capability:e,effect:t,paths:["**"]}}function Uo(e){return e?e.rules.some(t=>{if(t.capability==="executeBash")return(t.commands??[]).length>0;const n=t.paths??[];return n.length!==1||n[0]!=="**"}):!1}function VO(e){const{agent:t,permission:n}=ue(),[r,s]=g.useState([]),[i,l]=g.useState(null),[a,c]=g.useState(null),[u,h]=g.useState({}),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useCallback(async()=>{f(!0),m(null);try{const[D,A,k]=await Promise.all([t.listAgents(e),n.getProjectPermissions(e),n.getProjectSystemPermissions(e)]),R=await Promise.all(D.map(async T=>{try{return[T.id,await n.resolveAgentSystemPermissions(e,T.id)]}catch{return[T.id,null]}}));s(D),l(A),c(k),h(Object.fromEntries(R.filter(T=>T[1]!==null)))}catch(D){m(ts(D))}finally{f(!1)}},[t,n,e]);g.useEffect(()=>{x()},[x]);const w=g.useMemo(()=>{const D=new Map((i?.agents??[]).map(k=>[k.agentId,k.permissions])),A=new Map((a?.agents??[]).map(k=>[k.agentId,k.permissions]));return r.map(k=>({agent:k,override:D.get(k.id)??null,systemOverride:A.get(k.id)??null,resolvedSystem:u[k.id]??null}))},[r,i,a,u]),v=g.useMemo(()=>XS(i?.projectDefaults??null),[i]),y=g.useCallback(async D=>{f(!0),m(null);try{l(await n.updateProjectPermissions(e,Lv(D)))}catch(A){m(ts(A))}finally{f(!1)}},[n,e]),_=g.useCallback(async()=>{f(!0),m(null);try{l(await n.updateProjectPermissions(e,null))}catch(D){m(ts(D))}finally{f(!1)}},[n,e]),b=g.useCallback(async(D,A)=>{f(!0),m(null);try{l(await n.updateAgentPermissions(e,D,Lv(A)))}catch(k){m(ts(k))}finally{f(!1)}},[n,e]),j=g.useCallback(async D=>{f(!0),m(null);try{l(await n.updateAgentPermissions(e,D,null))}catch(A){m(ts(A))}finally{f(!1)}},[n,e]),S=g.useCallback(async D=>{f(!0),m(null);try{const A=await n.updateProjectSystemPermissions(e,D);c(A),await x()}catch(A){m(ts(A))}finally{f(!1)}},[n,e,x]),N=g.useCallback(async(D,A)=>{f(!0),m(null);try{const k=await n.updateAgentSystemPermissions(e,D,A);c(k),await x()}catch(k){m(ts(k))}finally{f(!1)}},[n,e,x]);return{agents:r,rows:w,document:i,systemDocument:a,projectDraft:v,busy:d,error:p,refresh:x,saveProjectDefaults:y,clearProjectDefaults:_,saveAgentOverride:b,clearAgentOverride:j,saveProjectSystemPermissions:S,saveAgentSystemPermissions:N}}const zs=[{id:"system",label:"Système"},{id:"mcpTools",label:"Tools MCP IdeA"}],GO=[{key:"read",label:"Read"},{key:"write",label:"Write"},{key:"delete",label:"Delete"},{key:"executeBash",label:"Bash"}],YO={ask:"Ask",allow:"Allow",deny:"Deny"},sd={allow:"Autorisé",deny:"Interdit",ask:"Demande"};function QS({projectId:e}){const t=VO(e),[n,r]=g.useState({type:"project"}),[s,i]=g.useState("system"),l=n.type==="agent"?t.rows.find(w=>w.agent.id===n.agentId)??null:null,a=l?.override??t.document?.projectDefaults??null,c=n.type==="project"?t.systemDocument?.projectDefault??null:l?.systemOverride??t.systemDocument?.projectDefault??null,u=n.type==="project"?t.rows[0]?.resolvedSystem??null:l?.resolvedSystem??null,h=n.type==="project"?t.projectDraft:XS(l?.override??t.document?.projectDefaults??null),d=n.type==="project"?Uo(t.document?.projectDefaults):Uo(l?.override),f=t.document?.projectDefaults!=null;async function p(w){n.type==="project"?await t.saveProjectDefaults(w):await t.saveAgentOverride(n.agentId,w)}async function m(){n.type==="project"?await t.clearProjectDefaults():await t.clearAgentOverride(n.agentId)}async function x(w){n.type==="project"?await t.saveProjectSystemPermissions(w):await t.saveAgentSystemPermissions(n.agentId,w)}return o.jsxs(ke,{title:"Permissions",actions:o.jsx(M,{size:"sm",variant:"ghost",disabled:t.busy,onClick:()=>void t.refresh(),children:"Refresh"}),className:"flex min-h-0 flex-1 flex-col",flush:!0,children:[o.jsx("div",{role:"tablist","aria-label":"Permissions",className:"flex gap-1 border-b border-border px-4 pt-2",children:zs.map(w=>o.jsx("button",{type:"button",role:"tab",id:`permissions-tab-${w.id}`,"aria-selected":s===w.id,"aria-controls":`permissions-tabpanel-${w.id}`,tabIndex:s===w.id?0:-1,onClick:()=>i(w.id),onKeyDown:v=>{if(v.key!=="ArrowRight"&&v.key!=="ArrowLeft")return;v.preventDefault();const y=zs.findIndex(b=>b.id===s),_=v.key==="ArrowRight"?(y+1)%zs.length:(y-1+zs.length)%zs.length;i(zs[_].id)},className:U("min-h-[32px] rounded-t-md border-b-2 px-3 py-1.5 text-sm font-medium transition-colors",s===w.id?"border-primary text-content":"border-transparent text-muted hover:text-content"),children:w.label},w.id))}),t.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{role:"tabpanel",id:"permissions-tabpanel-system","aria-labelledby":"permissions-tab-system",hidden:s!=="system",className:"flex flex-col gap-4 p-4",children:[o.jsx(Dv,{title:"Project defaults",subtitle:f?"Configured":"Native CLI behavior",active:n.type==="project",custom:Uo(t.document?.projectDefaults),onSelect:()=>r({type:"project"}),policy:t.document?.projectDefaults??null}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.busy&&o.jsx(Ie,{size:14})]}),t.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):o.jsx("ul",{className:"flex flex-col gap-2",children:t.rows.map(w=>{const v=n.type==="agent"&&n.agentId===w.agent.id;return o.jsx("li",{children:o.jsx(Dv,{title:w.agent.name,subtitle:w.override?"Override":"Inherited",active:v,custom:Uo(w.override),onSelect:()=>r({type:"agent",agentId:w.agent.id,agentName:w.agent.name}),policy:w.override})},w.agent.id)})})]}),o.jsx(QO,{title:n.type==="project"?"Project defaults":`Override — ${n.agentName}`,draft:h,sourcePolicy:a,custom:d,canClear:n.type==="project"?t.document?.projectDefaults!=null:l?.override!=null,busy:t.busy,onSave:w=>void p(w),onClear:()=>void m()},n.type==="project"?"project":n.agentId),o.jsx(XO,{title:n.type==="project"?"Réseau — defaults projet":`Réseau — ${n.agentName}`,source:c,resolved:u,inherited:n.type==="agent"&&l?.systemOverride==null?t.systemDocument?.projectDefault??null:null,busy:t.busy,onSave:w=>void x(w)},`network-${n.type==="project"?"project":n.agentId}`)]}),o.jsx("div",{role:"tabpanel",id:"permissions-tabpanel-mcpTools","aria-labelledby":"permissions-tab-mcpTools",hidden:s!=="mcpTools",className:"flex min-h-0 flex-1 flex-col",children:s==="mcpTools"&&o.jsx($O,{projectId:e,agents:t.agents})})]})}function Dv({title:e,subtitle:t,active:n,custom:r,policy:s,onSelect:i}){return o.jsxs("button",{type:"button",onClick:i,"aria-pressed":n,className:U("flex w-full min-w-0 items-center justify-between gap-3 rounded-md border px-3 py-2 text-left","transition-colors hover:border-border-strong hover:bg-raised",n?"border-primary bg-raised":"border-border bg-surface"),children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:e}),o.jsx("span",{className:"text-xs text-muted",children:t})]}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[r&&o.jsx("span",{className:"rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Custom"}),s&&o.jsx("span",{className:"rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary",children:YO[s.fallback]})]})]})}function XO({title:e,source:t,inherited:n,resolved:r,busy:s,onSave:i}){const l=t?.network??"",[a,c]=g.useState(l);g.useEffect(()=>{c(l)},[l]);const u=r?.control.mode==="readOnly",h=a!==l,d=r?.wanted??t?.network??n?.network??null,f=r?.effective??null,p=r?.runtimeLock.state==="locked",m=r?.runtimeControl.mode==="readOnly",x=r?.runtimeLock.reason??r?.runtimeControl.reason??null,w=r?.runtimeLock.state==="none"&&m;return o.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[o.jsxs("header",{className:"border-b border-border px-3 py-2.5",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-xs text-muted",children:"Politique voulue, état effectif et verrou runtime."})]}),o.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[o.jsxs("div",{className:"grid grid-cols-1 gap-2 text-xs sm:grid-cols-2",children:[o.jsx(qo,{label:"Wanted",value:d?`Réseau ${sd[d].toLowerCase()}`:"Non configuré"}),o.jsx(qo,{label:"Effective",value:f?`Réseau ${sd[f].toLowerCase()}`:"Indisponible"}),o.jsx(qo,{label:"Runtime",value:p?"Runtime verrouillé":w?"Aucun runtime actif":m?"Runtime en lecture seule":"Runtime modifiable"}),o.jsx(qo,{label:"Control",value:u?"Lecture seule":"Modifiable"})]}),u&&o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:r?.control.reason??"Cette configuration réseau est en lecture seule."}),!u&&w&&o.jsx("p",{className:"rounded-md border border-primary/30 bg-primary/10 px-3 py-2 text-xs text-primary",children:"Aucun runtime actif. La configuration sera appliquée au prochain lancement."}),!u&&p&&o.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:x??"Le runtime actif expose un état réseau en lecture seule."}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Réseau"}),o.jsxs("select",{"aria-label":`${e} network`,value:a,disabled:s||u,onChange:v=>c(v.target.value),className:U("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"",children:"Non configuré"}),o.jsx("option",{value:"allow",children:"Réseau autorisé"}),o.jsx("option",{value:"deny",children:"Réseau interdit"}),o.jsx("option",{value:"ask",children:"Demande d'autorisation"})]})]}),n?.network&&!t?.network&&o.jsxs("p",{className:"text-xs text-muted",children:["Hérite du projet : Réseau ",sd[n.network].toLowerCase(),"."]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"Clear network",disabled:s||u||!t?.network,onClick:()=>i(null),children:"Clear"}),o.jsx(M,{size:"sm",variant:"primary","aria-label":"Save network",disabled:s||u||!h,loading:s&&h,onClick:()=>i(a?{network:a}:null),children:"Save"})]})]})]})}function qo({label:e,value:t}){return o.jsxs("div",{className:"rounded-md border border-border/70 bg-raised px-3 py-2",children:[o.jsx("span",{className:"block text-[11px] font-medium uppercase text-faint",children:e}),o.jsx("span",{className:"text-xs text-content",children:t})]})}function QO({title:e,draft:t,sourcePolicy:n,custom:r,canClear:s,busy:i,onSave:l,onClear:a}){const[c,u]=g.useState(t),h=g.useRef(t);g.useEffect(()=>{u(p=>JSON.stringify(p)===JSON.stringify(h.current)?t:p),h.current=t},[t]);const d=g.useMemo(()=>JSON.stringify(c)!==JSON.stringify(t),[t,c]);function f(p,m){u(x=>({...x,[p]:m}))}return o.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[o.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-3 py-2.5",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:"truncate text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-xs text-muted",children:n?`${n.rules.length} rules`:"Not configured"})]}),r&&o.jsx("span",{className:"shrink-0 rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Advanced"})]}),o.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Fallback"}),o.jsxs("select",{"aria-label":`${e} fallback`,value:c.fallback,disabled:i,onChange:p=>u(m=>({...m,fallback:p.target.value})),className:U("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[o.jsx("option",{value:"ask",children:"Ask"}),o.jsx("option",{value:"allow",children:"Allow"}),o.jsx("option",{value:"deny",children:"Deny"})]})]}),o.jsx("div",{className:"grid grid-cols-1 gap-2",children:GO.map(p=>o.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:p.label}),o.jsx(JO,{value:c[p.key],disabled:i,label:p.label,onChange:m=>f(p.key,m)})]},p.key))}),o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:i||!s,onClick:a,children:"Clear"}),o.jsx(M,{size:"sm",variant:"primary",disabled:i||!d,loading:i&&d,onClick:()=>l(c),children:"Save"})]})]})]})}function JO({value:e,disabled:t,label:n,onChange:r}){const s=[{value:"none",label:"None"},{value:"allow",label:"Allow"},{value:"deny",label:"Deny"}];return o.jsx("div",{role:"group","aria-label":`${n} permission`,className:"grid grid-cols-3 overflow-hidden rounded-md border border-border",children:s.map(i=>o.jsx("button",{type:"button",disabled:t,"aria-pressed":e===i.value,onClick:()=>r(i.value),className:U("h-8 min-w-0 border-r border-border px-2 text-xs font-medium last:border-r-0","transition-colors disabled:cursor-not-allowed disabled:opacity-50",e===i.value?i.value==="deny"?"bg-danger/20 text-danger":i.value==="allow"?"bg-success/20 text-success":"bg-raised text-content":"bg-surface text-muted hover:bg-raised hover:text-content"),children:i.label},i.value))})}function Fp(e){return e.type.startsWith("issue")}function JS(e){return e.type.startsWith("sprint")}function ZO(e){return e.replace(/[\s-]+/g,"").toUpperCase()}const eB=["open","inProgress","QA","closed"],tB=["low","medium","high","critical"],nB=["number","priority","status","title"],rB=["asc","desc"];function ZS(e){return`tickets:listFilters:${e}`}function sB(e){return`tickets:pickerFilters:${e}`}function e0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rv(e,t){if(!Array.isArray(e))return;const n=new Set(t),r=[];for(const s of e)typeof s=="string"&&n.has(s)&&!r.includes(s)&&r.push(s);return r.length>0?r:void 0}function iB(e){if(!e0(e))return;const{field:t,direction:n}=e;if(typeof t=="string"&&nB.includes(t)&&typeof n=="string"&&rB.includes(n))return{field:t,direction:n}}function t0(e,t={}){if(!e0(e))return{};const n={};typeof e.text=="string"&&e.text.length>0&&(n.text=e.text);const r=Rv(e.statuses,eB);r&&(n.statuses=r);const s=Rv(e.priorities,tB);if(s&&(n.priorities=s),typeof e.assignedAgentId=="string"&&e.assignedAgentId){const{validAgentIds:l}=t;(!l||l.has(e.assignedAgentId))&&(n.assignedAgentId=e.assignedAgentId)}const i=iB(e.sort);return i&&(n.sort=i),typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0&&(n.limit=e.limit),n}function lB(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.assignedAgentId&&(t.assignedAgentId=e.assignedAgentId),e.sort&&(t.sort=e.sort),typeof e.limit=="number"&&(t.limit=e.limit),Object.keys(t).length>0?t:null}function oB(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.sort&&(t.sort=e.sort),Object.keys(t).length>0?t:null}function Mv(e,t,n){return e?t0(e.read(ZS(t)),n):{}}function aB(e,t,n){if(!e)return;const r=lB(n),s=ZS(t);r?e.write(s,r):e.remove(s)}function Sr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function $p(e){const{ticket:t,system:n,uiPreferences:r}=ue(),[s,i]=g.useState(null),[l,a]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(!1),[f,p]=g.useState(()=>Mv(r,e)),m=g.useRef(e);g.useEffect(()=>{m.current!==e&&(m.current=e,p(Mv(r,e)))},[e,r]),g.useEffect(()=>{aB(r,e,f)},[r,e,f]);const x=g.useMemo(()=>JSON.stringify(f),[f]),w=g.useCallback(async()=>{d(!0),u(null);try{i(await t.list(e,f))}catch(R){u(Sr(R))}finally{d(!1)}},[e,t,x]),v=g.useCallback(R=>{p(T=>{const E=T.statuses??[],O=E.includes(R)?E.filter(G=>G!==R):[...E,R],{statuses:I,...W}=T;return O.length>0?{...W,statuses:O}:W})},[]),y=g.useCallback(R=>{p(T=>{const E=T.priorities??[],O=E.includes(R)?E.filter(G=>G!==R):[...E,R],{priorities:I,...W}=T;return O.length>0?{...W,priorities:O}:W})},[]),_=g.useCallback(()=>{p(({statuses:R,priorities:T,...E})=>E)},[]),b=g.useCallback(async()=>{try{a(await t.listSprints(e))}catch(R){u(Sr(R))}},[e,t]),j=g.useCallback(async R=>{u(null);try{const T=await t.create(e,R);return await w(),T}catch(T){return u(Sr(T)),null}},[e,t,w]),S=g.useCallback(async(R,T)=>{u(null);try{const E=await t.read(e,R);return await t.setTicketSprint(e,R,T,E.version),await Promise.all([w(),b()]),!0}catch(E){return u(Sr(E)),!1}},[e,t,w,b]),N=g.useCallback(async R=>{u(null);try{const T=await t.createSprint(e,R);return await b(),T}catch(T){return u(Sr(T)),null}},[e,t,b]),D=g.useCallback(async(R,T)=>{u(null);try{const E=l.find(O=>O.id===R);return E?(await t.renameSprint(e,R,T,E.version),await b(),!0):!1}catch(E){return u(Sr(E)),!1}},[e,t,l,b]),A=g.useCallback(async(R,T)=>{u(null);const E=[...l].sort((G,P)=>G.order-P.order),O=E.findIndex(G=>G.id===R),I=T==="up"?O-1:O+1;if(O===-1||I<0||I>=E.length)return!1;const W=[...E];[W[O],W[I]]=[W[I],W[O]];try{return await t.reorderSprints(e,W.map(G=>G.id)),await b(),!0}catch(G){return u(Sr(G)),!1}},[e,t,l,b]),k=g.useCallback(async R=>{u(null);try{return await t.deleteSprint(e,R),await Promise.all([w(),b()]),!0}catch(T){return u(Sr(T)),!1}},[e,t,w,b]);return g.useEffect(()=>{w()},[w]),g.useEffect(()=>{b()},[b]),g.useEffect(()=>{if(!n)return;let R,T=!1;return n.onDomainEvent(E=>{Fp(E)&&w(),(JS(E)||E.type==="issueSprintChanged")&&b()}).then(E=>{T?E():R=E}),()=>{T=!0,R?.()}},[w,b,n]),{list:s,sprints:l,error:c,busy:h,query:f,setQuery:p,toggleStatus:v,togglePriority:y,clearFacets:_,refresh:w,create:j,assignSprint:S,createSprint:N,renameSprint:D,moveSprint:A,deleteSprint:k}}function n0(e){const{agent:t}=ue(),[n,r]=g.useState([]),[s,i]=g.useState(!1);g.useEffect(()=>{let c=!1;return i(!1),t.listAgents(e).then(u=>{c||(r(u),i(!0))}).catch(()=>{c||(r([]),i(!0))}),()=>{c=!0}},[e,t]);const l=g.useMemo(()=>new Map(n.map(c=>[c.id,c.name])),[n]);return{agents:n,nameOf:c=>l.get(c)??`${c.slice(0,8)}…`,loaded:s}}const Rc=["open","inProgress","QA","closed"],Ni=["low","medium","high","critical"],r0=["relatesTo","blocks","blockedBy","duplicates","dependsOn"];function Wp(e){switch(e){case"open":return"Open";case"inProgress":return"In progress";case"QA":return"QA";case"closed":return"Closed"}}function Mc(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Iv(e){switch(e){case"relatesTo":return"relates to";case"blocks":return"blocks";case"blockedBy":return"blocked by";case"duplicates":return"duplicates";case"dependsOn":return"depends on"}}function cB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function uB(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function s0(e){return U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function io({status:e}){return o.jsx("span",{className:s0(cB(e)),children:Wp(e)})}function lo({priority:e}){return o.jsx("span",{className:s0(uB(e)),children:Mc(e)})}function yi({ticketRef:e,onOpen:t,className:n}){const r=U("inline-flex shrink-0 items-center rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",n);return t?o.jsx("button",{type:"button","aria-label":`open ticket ${e}`,className:U(r,"transition-colors hover:bg-primary/15 hover:text-primary"),onClick:()=>t(e),children:e}):o.jsx("code",{className:r,children:e})}const dB=/#\d+/g;function hB(e,t){const n=[];let r=0,s=0;for(const i of e.matchAll(dB)){const l=i.index??0;l>r&&n.push(e.slice(r,l)),n.push(o.jsx(yi,{ticketRef:i[0],onOpen:t},`ref-${s++}-${l}`)),r=l+i[0].length}return r0||r.length>0;return o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(ie,{"aria-label":"search tickets",placeholder:a,value:e,onChange:d=>t(d.target.value)}),o.jsxs("fieldset",{"aria-label":"filter by status",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Statut"}),Rc.map(d=>o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[o.jsx("input",{type:"checkbox","aria-label":`filter status ${Wp(d)}`,className:"accent-primary",checked:n.includes(d),onChange:()=>s(d)}),o.jsx(io,{status:d})]},d))]}),o.jsxs("fieldset",{"aria-label":"filter by priority",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Priorité"}),Ni.map(d=>o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[o.jsx("input",{type:"checkbox","aria-label":`filter priority ${Mc(d)}`,className:"accent-primary",checked:r.includes(d),onChange:()=>i(d)}),o.jsx(lo,{priority:d})]},d))]}),u&&o.jsxs("div",{"aria-label":"sort tickets",className:"flex flex-wrap items-center gap-2",children:[o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted",children:["Trier par",o.jsxs("select",{"aria-label":"sort tickets by",className:fB,value:c?.field??"",onChange:d=>{const f=d.target.value;u(f===""?void 0:{field:f,direction:c?.direction??"asc"})},children:[o.jsx("option",{value:"",children:"Par défaut"}),pB.map(d=>o.jsx("option",{value:d,children:i0[d]},d))]})]}),c&&o.jsx(M,{size:"sm",variant:"ghost","aria-label":`sort direction ${c.direction==="asc"?"ascending":"descending"}`,onClick:()=>u({field:c.field,direction:c.direction==="asc"?"desc":"asc"}),children:c.direction==="asc"?"Croissant ↑":"Décroissant ↓"})]}),l&&h&&o.jsx("div",{children:o.jsx(M,{size:"sm",variant:"ghost","aria-label":"clear filters",onClick:l,children:"Effacer"})})]})}function Ov(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Ic(e,t={}){const{initialQuery:n,excludeRefs:r,debounceMs:s=200,refreshOnEvents:i,persistenceKey:l}=t,{ticket:a,system:c,uiPreferences:u}=ue(),h=g.useRef(null);if(h.current===null){const K=l&&u?t0(u.read(l)):{};h.current={statuses:n?.statuses??K.statuses,priorities:n?.priorities??K.priorities,assignedAgentId:n?.assignedAgentId??K.assignedAgentId,text:n?.text??K.text,sort:n?.sort??K.sort}}const d=h.current,[f,p]=g.useState({statuses:d.statuses,priorities:d.priorities,assignedAgentId:d.assignedAgentId}),[m,x]=g.useState(d.text??""),[w,v]=g.useState(m),[y,_]=g.useState(d.sort),[b,j]=g.useState([]),[S,N]=g.useState(void 0),[D,A]=g.useState(!1),[k,R]=g.useState(null),[T,E]=g.useState(0),O=g.useCallback(()=>E(K=>K+1),[]),I=n?.limit,W=(r??[]).join(","),G=g.useMemo(()=>new Set(r??[]),[W]);g.useEffect(()=>{const K=setTimeout(()=>v(m),s);return()=>clearTimeout(K)},[m,s]),g.useEffect(()=>{if(!l||!u)return;const K=w.trim(),Y=oB({...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...K?{text:K}:{},...y?{sort:y}:{}});Y?u.write(l,Y):u.remove(l)},[l,u,f,w,y]);const P=g.useMemo(()=>JSON.stringify({facets:f,text:w.trim(),sort:y,limit:I}),[f,w,y,I]),z=g.useRef(0),C=g.useCallback(K=>{const Y=w.trim();return{...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...f.assignedAgentId?{assignedAgentId:f.assignedAgentId}:{},...Y?{text:Y}:{},...y?{sort:y}:{},...I?{limit:I}:{},...K?{cursor:K}:{}}},[f,w,y,I]);g.useEffect(()=>{const K=++z.current;A(!0),R(null),a.list(e,C()).then(Y=>{K===z.current&&(j(Y.items),N(Y.nextCursor))}).catch(Y=>{K===z.current&&(R(Ov(Y)),j([]),N(void 0))}).finally(()=>{K===z.current&&A(!1)})},[P,e,a,T]),g.useEffect(()=>{if(!i||!c)return;let K,Y=!1;return c.onDomainEvent(ae=>{(Fp(ae)||JS(ae))&&E(pe=>pe+1)}).then(ae=>{Y?ae():K=ae}),()=>{Y=!0,K?.()}},[i,c]);const Q=g.useCallback(()=>{if(D||!S)return;const K=++z.current;A(!0),R(null),a.list(e,C(S)).then(Y=>{K===z.current&&(j(ae=>[...ae,...Y.items]),N(Y.nextCursor))}).catch(Y=>{K===z.current&&R(Ov(Y))}).finally(()=>{K===z.current&&A(!1)})},[D,S,a,e,C]),q=g.useCallback(K=>{p(Y=>{const ae=Y.statuses??[],pe=ae.includes(K)?ae.filter(Pe=>Pe!==K):[...ae,K];return{...Y,statuses:pe.length>0?pe:void 0}})},[]),L=g.useCallback(K=>{p(Y=>{const ae=Y.priorities??[],pe=ae.includes(K)?ae.filter(Pe=>Pe!==K):[...ae,K];return{...Y,priorities:pe.length>0?pe:void 0}})},[]),se=g.useCallback(()=>{p(K=>({...K,statuses:void 0,priorities:void 0}))},[]),te=g.useCallback(async K=>{const Y=await a.read(e,K);return{ref:Y.ref,id:Y.id,number:Y.number,title:Y.title,status:Y.status,priority:Y.priority}},[a,e]);return{rows:g.useMemo(()=>G.size===0?b:b.filter(K=>!G.has(K.ref)),[b,G]),busy:D,error:k,text:m,setText:x,statuses:f.statuses??[],priorities:f.priorities??[],toggleStatus:q,togglePriority:L,clearFacets:se,sort:y,setSort:_,hasMore:S!==void 0,loadMore:Q,refresh:O,resolve:te}}const Bv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function l0({open:e,projectId:t,title:n="Sélectionner un ticket",confirmLabel:r="Sélectionner",selectionMode:s="single",excludeRefs:i,initialQuery:l,persistFilters:a=!0,onSelect:c,onClose:u}){return e?o.jsx(mB,{projectId:t,title:n,confirmLabel:r,selectionMode:s,excludeRefs:i,initialQuery:l,persistFilters:a,onSelect:c,onClose:u}):null}function mB({projectId:e,title:t,confirmLabel:n,selectionMode:r,excludeRefs:s,initialQuery:i,persistFilters:l,onSelect:a,onClose:c}){const u=Ic(e,{initialQuery:i,excludeRefs:s,persistenceKey:l?sB(e):void 0}),h=g.useRef(null),[d,f]=g.useState(!1),[p,m]=g.useState(null),[x,w]=g.useState(()=>new Set),v=r==="multi";g.useEffect(()=>{const S=document.activeElement,N=h.current;N?.querySelector(Bv)?.focus();function A(k){if(k.key==="Escape"){k.preventDefault(),c();return}if(k.key!=="Tab"||!N)return;const R=Array.from(N.querySelectorAll(Bv)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(R.length===0)return;const T=R[0],E=R[R.length-1],O=document.activeElement;k.shiftKey&&O===T?(k.preventDefault(),E.focus()):!k.shiftKey&&O===E&&(k.preventDefault(),T.focus())}return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A),S?.focus?.()}},[c]);function y(S){return S&&typeof S=="object"&&"message"in S?String(S.message):String(S)}function _(S){w(N=>{const D=new Set(N);return D.has(S)?D.delete(S):D.add(S),D})}async function b(S){if(!d){f(!0),m(null);try{const N=await u.resolve(S);a(N),c()}catch(N){m(y(N)),f(!1)}}}async function j(){if(!(d||x.size===0)){f(!0),m(null);try{const S=await Promise.all(Array.from(x).map(N=>u.resolve(N)));a(S),c()}catch(S){m(y(S)),f(!1)}}}return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindowNested},onMouseDown:S=>{S.target===S.currentTarget&&c()},children:o.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-label":t,className:"flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:t}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close ticket picker",onClick:c,children:"Close"})]}),o.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:o.jsx(Hp,{text:u.text,onTextChange:u.setText,statuses:u.statuses,priorities:u.priorities,onToggleStatus:u.toggleStatus,onTogglePriority:u.togglePriority,onClearFacets:u.clearFacets,sort:u.sort,onSortChange:u.setSort})}),(u.error||p)&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??u.error}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[u.busy&&u.rows.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Loading tickets…"})]}):u.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No matching tickets."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.rows.map(S=>{const N=x.has(S.ref);return o.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:o.jsxs("button",{type:"button","aria-label":`select ticket ${S.ref}`,...v?{role:"checkbox","aria-checked":N}:{},disabled:d,onClick:()=>v?_(S.ref):void b(S.ref),className:U("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none","disabled:cursor-not-allowed disabled:opacity-60",v&&N&&"bg-raised"),children:[v&&o.jsx("span",{"aria-hidden":"true",className:U("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",N?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),o.jsx(yi,{ticketRef:S.ref,className:"mt-0.5"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:S.title}),o.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[o.jsx(io,{status:S.status}),o.jsx(lo,{priority:S.priority})]})]})},S.ref)})}),u.hasMore&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:u.busy,onClick:()=>u.loadMore(),children:"Load more"})})]}),v&&o.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3",children:[o.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[x.size," sélectionné",x.size>1?"s":""]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel ticket selection",onClick:c,children:"Annuler"}),o.jsx(M,{size:"sm","aria-label":"confirm ticket selection",loading:d,disabled:x.size===0||d,onClick:()=>void j(),children:x.size>0?`${n} (${x.size})`:n})]})]})]})})}function gB({projectId:e,vm:t,onClose:n}){const r=Ic(e,{refreshOnEvents:!0}),s=r.rows,i=[...t.sprints].sort((x,w)=>x.order-w.order),[l,a]=g.useState(""),[c,u]=g.useState({}),[h,d]=g.useState(null),[f,p]=g.useState(null);async function m(x){x.preventDefault();const w=l.trim()||`Sprint ${i.length+1}`;await t.createSprint(w)&&a("")}return o.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"manage sprints",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:"Manage sprints"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"Close"})]}),t.error&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-5 py-2 text-sm text-danger",children:t.error}),o.jsxs("div",{className:"flex-1 overflow-auto p-5",children:[o.jsxs("form",{onSubmit:m,className:"mb-5 flex items-center gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsx(ie,{"aria-label":"new sprint name",placeholder:"Sprint name (optional)",value:l,onChange:x=>a(x.target.value),className:"max-w-xs"}),o.jsx(M,{type:"submit",size:"sm",disabled:t.busy,children:"Create sprint"})]}),o.jsx("div",{className:"mb-5",children:o.jsx(Hp,{text:r.text,onTextChange:r.setText,statuses:r.statuses,priorities:r.priorities,onToggleStatus:r.toggleStatus,onTogglePriority:r.togglePriority,onClearFacets:r.clearFacets,sort:r.sort,onSortChange:r.setSort})}),r.error&&o.jsx("p",{role:"alert",className:"mb-4 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),i.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No sprints yet."}):o.jsx("ul",{className:"flex flex-col gap-4",children:i.map((x,w)=>{const v=s.filter(_=>_.sprintId===x.id),y=c[x.id]??x.name;return o.jsxs("li",{"aria-label":`sprint row ${x.name}`,className:"rounded-md border border-border p-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",x.order]}),o.jsx(ie,{"aria-label":`rename sprint ${x.name}`,value:y,disabled:t.busy,onChange:_=>u(b=>({...b,[x.id]:_.target.value})),className:"max-w-xs"}),o.jsx(M,{size:"sm","aria-label":`save sprint ${x.name}`,disabled:t.busy||y.trim()===""||y.trim()===x.name,onClick:async()=>{await t.renameSprint(x.id,y.trim())&&u(b=>{const{[x.id]:j,...S}=b;return S})},children:"Save"}),o.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} up`,disabled:t.busy||w===0,onClick:()=>void t.moveSprint(x.id,"up"),children:"↑"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} down`,disabled:t.busy||w===i.length-1,onClick:()=>void t.moveSprint(x.id,"down"),children:"↓"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete sprint ${x.name}`,disabled:t.busy,className:"text-danger hover:text-danger",onClick:()=>d({id:x.id,name:x.name}),children:"Delete"})]})]}),o.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[v.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No tickets in this sprint."}):o.jsx("ul",{className:"flex flex-col gap-1",children:v.map(_=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx(yi,{ticketRef:_.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:_.title}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(io,{status:_.status}),o.jsx(lo,{priority:_.priority})]}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`remove ${_.ref} from sprint`,disabled:t.busy,onClick:()=>void t.assignSprint(_.ref,null),children:"Remove"})]},_.ref))}),o.jsx("div",{className:"mt-1",children:o.jsx(M,{size:"sm",variant:"ghost","aria-label":`add ticket to sprint ${x.name}`,disabled:t.busy,onClick:()=>p({id:x.id,name:x.name}),children:"Ajouter des tickets"})})]})]},x.id)})}),r.hasMore&&o.jsx("div",{className:"mt-4 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:r.busy,onClick:()=>r.loadMore(),children:"Load more tickets"})})]}),h&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"delete sprint confirmation",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Supprimer le sprint « ",h.name," » ?"]}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Les tickets de ce sprint ne seront pas supprimés : ils seront simplement désassignés et retourneront au backlog « Sans sprint »."}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete sprint",disabled:t.busy,onClick:()=>d(null),children:"Annuler"}),o.jsx(M,{size:"sm","aria-label":"confirm delete sprint",className:"text-danger hover:text-danger",disabled:t.busy,onClick:async()=>{await t.deleteSprint(h.id),d(null)},children:"Supprimer"})]})]})}),o.jsx(l0,{open:f!==null,projectId:e,title:f?`Ajouter des tickets au sprint « ${f.name} »`:"Ajouter des tickets",confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:s.filter(x=>x.sprintId===f?.id).map(x=>x.ref),onSelect:x=>{const w=Array.isArray(x)?x:[x];if(f)for(const v of w)t.assignSprint(v.ref,f.id)},onClose:()=>p(null)})]})}const zv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function xB({open:e,projectId:t,selectedSprintId:n,title:r="Sélectionner un sprint",onSelect:s,onClose:i}){return e?o.jsx(yB,{projectId:t,selectedSprintId:n??null,title:r,onSelect:s,onClose:i}):null}function vB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function yB({projectId:e,selectedSprintId:t,title:n,onSelect:r,onClose:s}){const{ticket:i}=ue(),l=g.useRef(null),[a,c]=g.useState(null),[u,h]=g.useState(null);g.useEffect(()=>{let p=!1;return h(null),i.listSprints(e).then(m=>{p||c(m)}).catch(m=>{p||(h(vB(m)),c([]))}),()=>{p=!0}},[i,e]),g.useEffect(()=>{const p=document.activeElement,m=l.current;m?.querySelector(zv)?.focus();function w(v){if(v.key==="Escape"){v.preventDefault(),s();return}if(v.key!=="Tab"||!m)return;const y=Array.from(m.querySelectorAll(zv)).filter(S=>S.offsetParent!==null||S===document.activeElement);if(y.length===0)return;const _=y[0],b=y[y.length-1],j=document.activeElement;v.shiftKey&&j===_?(v.preventDefault(),b.focus()):!v.shiftKey&&j===b&&(v.preventDefault(),_.focus())}return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w),p?.focus?.()}},[s]);const d=a?[...a].sort((p,m)=>p.order-m.order):[];function f(p){r(p),s()}return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:Sn.floatingWindowNested},onMouseDown:p=>{p.target===p.currentTarget&&s()},children:o.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":n,className:"flex max-h-[80vh] w-full max-w-sm flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:n}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close sprint picker",onClick:s,children:"Close"})]}),u&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:u}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[o.jsxs("ul",{className:"flex flex-col divide-y divide-border",children:[o.jsx("li",{className:"py-1.5 first:pt-0",children:o.jsx(Fv,{label:"Sans sprint",ariaLabel:"select no sprint",selected:t===null,onClick:()=>f(null)})}),a===null?o.jsxs("li",{className:"flex items-center gap-2 py-2 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Loading sprints…"})]}):d.map(p=>o.jsx("li",{className:"py-1.5 last:pb-0",children:o.jsx(Fv,{label:p.name,ariaLabel:`select sprint ${p.name}`,count:p.ticketCount,selected:t===p.id,onClick:()=>f(p)})},p.id))]}),a!==null&&d.length===0&&!u&&o.jsx("p",{className:"mt-2 text-sm text-muted",children:"No sprints yet."})]})]})})}function Fv({label:e,ariaLabel:t,count:n,selected:r,onClick:s}){return o.jsxs("button",{type:"button",role:"option","aria-selected":r,"aria-label":t,onClick:s,className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none",r&&"bg-raised"),children:[o.jsx("span",{"aria-hidden":"true",className:U("flex h-4 w-4 shrink-0 items-center justify-center text-[10px] font-bold",r?"text-primary":"text-transparent"),children:"✓"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e}),n!==void 0&&o.jsx("span",{className:"shrink-0 rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:n})]})}const rf=U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function _B({projectId:e,onOpen:t}){const n=$p(e),{agents:r,nameOf:s,loaded:i}=n0(e);g.useEffect(()=>{if(!i)return;const N=n.query.assignedAgentId;if(N&&!r.some(D=>D.id===N)){const{assignedAgentId:D,...A}=n.query;n.setQuery(A)}},[i,r,n.query,n.setQuery]);const[l,a]=g.useState(!1),[c,u]=g.useState(!1),[h,d]=g.useState(""),[f,p]=g.useState("medium"),[m,x]=g.useState(null),[w,v]=g.useState(!1),y=n.list?.items??[],_=new Set(n.sprints.map(N=>N.id)),b=n.sprints.map(N=>({sprint:N,tickets:y.filter(D=>D.sprintId===N.id)})).filter(N=>N.tickets.length>0),j=y.filter(N=>!N.sprintId||!_.has(N.sprintId));async function S(N){if(N.preventDefault(),!h.trim())return;const D=await n.create({title:h.trim(),priority:f});D&&(m&&await n.assignSprint(D.ref,m.id),d(""),p("medium"),x(null),a(!1),t(D.ref))}return o.jsxs(ke,{title:"Tickets",actions:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>a(N=>!N),children:l?"Cancel":"New"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"manage sprints",onClick:()=>u(!0),children:"Sprints"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"})]}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),l&&o.jsxs("form",{onSubmit:S,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsx(ie,{"aria-label":"new ticket title",placeholder:"Ticket title",value:h,onChange:N=>d(N.target.value)}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("select",{"aria-label":"new ticket priority",className:rf,value:f,onChange:N=>p(N.target.value),children:Ni.map(N=>o.jsx("option",{value:N,children:Mc(N)},N))}),o.jsx(M,{type:"submit",size:"sm",disabled:!h.trim()||n.busy,children:"Create"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs text-muted",children:"Sprint"}),o.jsx(M,{type:"button",size:"sm",variant:"ghost","aria-label":"choose sprint for new ticket",disabled:n.busy,onClick:()=>v(!0),className:"border border-border",children:m?m.name:"Sans sprint"})]})]}),o.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[o.jsx(Hp,{text:n.query.text??"",onTextChange:N=>n.setQuery({...n.query,text:N||void 0}),statuses:n.query.statuses??[],priorities:n.query.priorities??[],onToggleStatus:n.toggleStatus,onTogglePriority:n.togglePriority,onClearFacets:n.clearFacets,sort:n.query.sort,onSortChange:N=>{const{sort:D,...A}=n.query;n.setQuery(N?{...A,sort:N}:A)}}),o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:o.jsxs("select",{"aria-label":"filter by assignee",className:rf,value:n.query.assignedAgentId??"",onChange:N=>n.setQuery({...n.query,assignedAgentId:N.target.value||void 0}),children:[o.jsx("option",{value:"",children:"All assignees"}),r.map(N=>o.jsx("option",{value:N.id,children:N.name},N.id))]})})]}),n.busy&&n.list===null?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Loading tickets…"})]}):y.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No tickets."}):o.jsxs("div",{className:"flex flex-col gap-4",children:[b.map(N=>o.jsx($v,{heading:N.sprint.name,count:N.tickets.length,tickets:N.tickets,sprints:n.sprints,onOpen:t,nameOf:s,onAssignSprint:n.assignSprint},N.sprint.id)),j.length>0&&o.jsx($v,{heading:"Sans sprint",count:j.length,tickets:j,sprints:n.sprints,onOpen:t,nameOf:s,onAssignSprint:n.assignSprint})]}),n.list?.nextCursor&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Load more"})}),c&&o.jsx(gB,{projectId:e,vm:n,onClose:()=>u(!1)}),o.jsx(xB,{open:w,projectId:e,selectedSprintId:m?.id??null,title:"Sprint du nouveau ticket",onSelect:N=>x(N),onClose:()=>v(!1)})]})}function $v({heading:e,count:t,tickets:n,sprints:r,onOpen:s,nameOf:i,onAssignSprint:l}){return o.jsxs("section",{"aria-label":`sprint section ${e}`,children:[o.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t})]}),o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.map(a=>o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(yi,{ticketRef:a.ref,onOpen:s,className:"mt-0.5"}),o.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>s(a.ref),children:[o.jsx("span",{className:"block truncate text-sm font-medium text-content hover:underline",children:a.title}),a.assignedAgentIds.length>0&&o.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted",children:a.assignedAgentIds.map(i).join(", ")})]}),o.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[o.jsx(io,{status:a.status}),o.jsx(lo,{priority:a.priority})]})]}),o.jsx("div",{className:"mt-1 pl-6",children:o.jsxs("select",{"aria-label":`sprint for ${a.ref}`,className:rf,value:a.sprintId??"",onChange:c=>l(a.ref,c.target.value||null),children:[o.jsx("option",{value:"",children:"— No sprint —"}),r.map(c=>o.jsx("option",{value:c.id,children:c.name},c.id))]})})]},a.ref))})]})}function Ko(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function bB(e){return!!e&&typeof e=="object"&&typeof e.message=="string"&&e.message.includes("version conflict")}function o0(e,t){const{ticket:n,system:r}=ue(),[s,i]=g.useState(null),[l,a]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(0),w=g.useCallback(async()=>{p(!0),a(null);try{i(await n.read(e,t,!0)),u(!1),x(A=>A+1)}catch(A){a(Ko(A))}finally{p(!1)}},[e,t,n]);g.useEffect(()=>{w()},[w]),g.useEffect(()=>{if(!r)return;let A,k=!1;return r.onDomainEvent(R=>{if(R.type==="issueDeleted"&&R.issueRef===t){d(!0);return}Fp(R)&&R.issueRef===t&&w()}).then(R=>{k?R():A=R}),()=>{k=!0,A?.()}},[w,r,t]);const v=g.useCallback(async(A,k)=>{if(!s)return!1;p(!0),a(null);try{const R=await A(s.version);return i({...R,carnet:k!==void 0?k:s.carnet}),u(!1),!0}catch(R){if(bB(R)){a("This ticket was modified elsewhere. It has been reloaded — re-apply your change.");try{i(await n.read(e,t,!0))}catch(T){a(Ko(T))}u(!0),x(T=>T+1)}else a(Ko(R));return!1}finally{p(!1)}},[s,n,e,t]),y=g.useCallback(A=>v(k=>n.update(e,t,{...A,expectedVersion:k})),[v,n,e,t]),_=g.useCallback(A=>v(k=>n.updateCarnet(e,t,A,k),A),[v,n,e,t]),b=g.useCallback((A,k)=>v(R=>n.link(e,t,A,k,R)),[v,n,e,t]),j=g.useCallback((A,k)=>v(R=>n.unlink(e,t,A,R,k)),[v,n,e,t]),S=g.useCallback((A,k)=>v(R=>n.assign(e,t,A,k,R)),[v,n,e,t]),N=g.useCallback(A=>v(k=>n.setTicketSprint(e,t,A,k)),[v,n,e,t]),D=g.useCallback(async()=>{p(!0),a(null);try{return await n.delete(e,t),!0}catch(A){return a(Ko(A)),!1}finally{p(!1)}},[n,e,t]);return{ticket:s,error:l,conflict:c,deleted:h,busy:f,reloadCount:m,refresh:w,updateFields:y,saveCarnet:_,link:b,unlink:j,assign:S,setSprint:N,remove:D}}function Vo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function wB(e,t){const{ticket:n,profile:r}=ue(),[s,i]=g.useState([]),[l,a]=g.useState(null),[c,u]=g.useState([]),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef(null);w.current=l,g.useEffect(()=>{let b=!1;return(async()=>{try{const j=await r?.listProfiles()??[];b||i(j)}catch(j){b||x(Vo(j))}})(),()=>{b=!0}},[r]);const v=g.useCallback(async b=>{if(b){d(!0),x(null);try{const j=await n.openTicketChat(e,t,b);a(j.sessionId),u([])}catch(j){x(Vo(j))}finally{d(!1)}}},[n,e,t]),y=g.useCallback(async()=>{if(w.current){a(null),u([]);try{await n.closeTicketChat(e,t)}catch(b){x(Vo(b))}}},[n,e,t]),_=g.useCallback(async b=>{const j=b.trim();if(!l||!j||f)return;x(null),p(!0),u(N=>[...N,{role:"user",text:j},{role:"assistant",text:"",pending:!0}]);const S=N=>{u(D=>{const A=[...D],k=A.length-1;return k<0||A[k].role!=="assistant"?D:(N.kind==="textDelta"?A[k]={...A[k],text:A[k].text+N.text}:N.kind==="toolActivity"?A[k]={...A[k],text:`${A[k].text} -· ${N.label}`}:N.kind==="error"?A[k]={role:"assistant",text:`⚠️ ${N.message}`,pending:!1}:A[k]={role:"assistant",text:N.content,pending:!1},A)}),(N.kind==="final"||N.kind==="error")&&p(!1)};try{await n.sendTicketChat(l,j,S)}catch(N){x(Vo(N)),u(D=>{const A=[...D],k=A.length-1;return k>=0&&A[k].role==="assistant"&&A[k].pending&&(A[k]={...A[k],pending:!1}),A}),p(!1)}},[n,l,f]);return g.useEffect(()=>()=>{w.current&&n.closeTicketChat(e,t).catch(()=>{})},[n,e,t]),{profiles:s,sessionId:l,turns:c,opening:h,busy:f,error:m,open:v,close:y,send:_}}const SB=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function kB({projectId:e,ticketRef:t}){const n=wB(e,t),[r,s]=g.useState(""),[i,l]=g.useState(""),a=g.useRef(null);g.useEffect(()=>{const h=a.current;h&&(h.scrollTop=h.scrollHeight)},[n.turns]);const c=n.sessionId!==null;function u(){const h=i.trim();!h||n.busy||(n.send(h),l(""))}return o.jsxs("div",{className:"flex flex-col gap-3",children:[c?o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-xs text-muted",children:"Conversation ouverte — l'assistant peut lire le projet et éditer ce ticket."}),o.jsx(M,{size:"sm",variant:"ghost",disabled:n.busy,onClick:()=>void n.close(),children:"Fermer la conversation"})]}),o.jsx("div",{ref:a,className:"flex max-h-96 min-h-32 flex-col gap-2 overflow-auto rounded-md border border-border bg-raised/40 p-3",children:n.turns.length===0?o.jsx("p",{className:"m-auto text-xs text-muted",children:"Démarrez la conversation en décrivant ce que l'assistant doit faire sur ce ticket."}):n.turns.map((h,d)=>o.jsx("div",{className:U("flex",h.role==="user"?"justify-end":"justify-start"),children:o.jsxs("div",{className:U("max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm",h.role==="user"?"bg-primary/15 text-content":"bg-surface text-content"),children:[h.text,h.pending&&o.jsx("span",{className:"ml-1 inline-flex items-center align-middle text-muted",children:o.jsx(Ie,{size:12})})]})},d))}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("textarea",{"aria-label":"message à l'assistant",className:U("min-h-10 flex-1 resize-none rounded-md bg-raised p-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),rows:2,placeholder:"Votre message…",value:i,disabled:n.busy,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),u())}}),o.jsx(M,{size:"sm",disabled:!i.trim()||n.busy,loading:n.busy,onClick:u,children:"Envoyer"})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("select",{"aria-label":"profil de l'assistant",className:SB,value:r,disabled:n.opening||n.profiles.length===0,onChange:h=>s(h.target.value),children:[o.jsx("option",{value:"",children:n.profiles.length===0?"Aucun profil disponible":"Choisir un profil IA…"}),n.profiles.map(h=>o.jsx("option",{value:h.id,children:h.name},h.id))]}),o.jsx(M,{size:"sm",disabled:!r||n.opening,loading:n.opening,onClick:()=>void n.open(r),children:"Ouvrir la conversation"})]}),n.error&&o.jsx("p",{role:"alert",className:"text-xs text-danger",children:n.error})]})}const Go=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Wv=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");async function CB(e){return typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):!1}function Zi({title:e,hint:t,children:n}){return o.jsxs("section",{className:"flex flex-col gap-2 border-b border-border px-5 py-4",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:e}),t&&o.jsx("p",{className:"mt-0.5 text-xs text-muted",children:t})]}),n]})}function jB({projectId:e,ticketRef:t,onClose:n,onOpenRef:r}){const s=o0(e,t),{agents:i,nameOf:l}=n0(e),a=s.ticket,[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState("relatesTo"),[w,v]=g.useState(""),[y,_]=g.useState(!1),[b,j]=g.useState(!1),[S,N]=g.useState(!1),[D,A]=g.useState(!1),[k,R]=g.useState(!1);g.useEffect(()=>{s.deleted&&n()},[s.deleted,n]);const T=s.reloadCount,E=g.useRef(-1),O=g.useRef(null);g.useEffect(()=>{if(!a||E.current===T)return;E.current=T;const q=a.carnet??"",L=O.current;L===null||s.conflict?(u(a.title),d(a.description),p(q)):(u(te=>te===L.title?a.title:te),d(te=>te===L.description?a.description:te),p(te=>te===L.carnet?q:te)),O.current={title:a.title,description:a.description,carnet:q}},[a,T,s.conflict]);const I=!!a&&(c!==a.title||h!==a.description),W=!!a&&f!==(a.carnet??""),G=I||W,P=i.filter(q=>!a?.assignedAgentIds.includes(q.id));function z(){G?j(!0):n()}async function C(){let q=!0;I&&(q=await s.updateFields({title:c,description:h})&&q),q&&W&&(q=await s.saveCarnet(f)&&q),j(!1),q&&n()}async function Q(){if(!a)return;await CB(`Travaille sur le ticket ${a.ref} : ${a.title}`)&&(_(!0),window.setTimeout(()=>_(!1),1200))}return o.jsxs(Wh,{open:!0,title:`ticket ${t}`,size:"xl",onClose:z,children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(yi,{ticketRef:t}),a&&o.jsx(io,{status:a.status}),a&&o.jsx(lo,{priority:a.priority}),o.jsx("span",{className:"truncate text-sm font-medium text-content",children:a?.title??t})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:!a,onClick:()=>void Q(),title:"Copy a delegation prompt to hand this ticket to an agent",children:y?"Copied":"Delegation context"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!a||s.busy,onClick:()=>N(!0),className:"text-danger hover:text-danger",title:"Supprimer définitivement ce ticket",children:"Supprimer"})]})]}),s.conflict&&o.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-1 py-2 text-sm text-warning",children:"This ticket was modified elsewhere and reloaded. Re-apply your change."}),s.error&&!s.conflict&&o.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-1 py-2 text-sm text-danger",children:s.error}),s.busy&&!a?o.jsxs("div",{className:"flex items-center gap-2 py-5 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Loading ticket…"})]}):a?o.jsxs("div",{className:"-mx-4",children:[o.jsxs(Zi,{title:"Details",children:[o.jsx("label",{className:"text-xs font-medium text-muted",htmlFor:"td-title",children:"Title"}),o.jsx(ie,{id:"td-title",value:c,onChange:q=>u(q.target.value),disabled:s.busy}),o.jsx("label",{className:"mt-2 text-xs font-medium text-muted",htmlFor:"td-desc",children:"Description"}),o.jsx("textarea",{id:"td-desc",className:U(Wv,"min-h-24"),value:h,onChange:q=>d(q.target.value),disabled:s.busy}),h.trim()&&o.jsx("p",{className:"whitespace-pre-wrap break-words rounded-md bg-raised/40 px-3 py-2 text-xs text-muted",children:hB(h,r)}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsx(M,{size:"sm",disabled:!I||s.busy,loading:s.busy&&I,onClick:()=>void s.updateFields({title:c,description:h}),children:"Save changes"}),I&&o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>{u(a.title),d(a.description)},children:"Reset"})]})]}),o.jsx(Zi,{title:"Status & priority",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Status",o.jsx("select",{"aria-label":"ticket status",className:Go,value:a.status,disabled:s.busy,onChange:q=>void s.updateFields({status:q.target.value}),children:Rc.map(q=>o.jsx("option",{value:q,children:Wp(q)},q))})]}),o.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Priority",o.jsx("select",{"aria-label":"ticket priority",className:Go,value:a.priority,disabled:s.busy,onChange:q=>void s.updateFields({priority:q.target.value}),children:Ni.map(q=>o.jsx("option",{value:q,children:Mc(q)},q))})]})]})}),o.jsxs(Zi,{title:"Carnet",hint:"Markdown notebook scoped to this ticket only — separate from project memory. Saving replaces the whole carnet.",children:[o.jsx("textarea",{"aria-label":"ticket carnet",className:U(Wv,"min-h-40 font-mono"),value:f,onChange:q=>p(q.target.value),disabled:s.busy}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(M,{size:"sm",disabled:!W||s.busy,loading:s.busy&&W,onClick:()=>void s.saveCarnet(f),children:"Save carnet"}),W&&o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>p(a.carnet??""),children:"Reset"})]})]}),o.jsxs(Zi,{title:"Linked tickets",children:[a.links.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No linked tickets."}):o.jsx("ul",{className:"flex flex-col gap-1",children:a.links.map(q=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"text-xs text-muted",children:Iv(q.kind)}),o.jsx(yi,{ticketRef:q.targetRef,onOpen:r}),o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:()=>void s.unlink(q.targetRef,q.kind),children:"Remove"})]},`${q.kind}-${q.targetRef}`))}),o.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[o.jsx("select",{"aria-label":"link kind",className:Go,value:m,disabled:s.busy,onChange:q=>x(q.target.value),children:r0.map(q=>o.jsx("option",{value:q,children:Iv(q)},q))}),o.jsx(M,{size:"sm","aria-label":"add link",disabled:s.busy,onClick:()=>A(!0),children:"Add link"})]})]}),o.jsxs(Zi,{title:"Assigned agents",hint:"Only agents known to this project can be assigned.",children:[a.assignedAgentIds.length===0?o.jsx("p",{className:"text-xs text-muted",children:"No agents assigned."}):o.jsx("ul",{className:"flex flex-wrap gap-2",children:a.assignedAgentIds.map(q=>o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[l(q),o.jsx("button",{type:"button","aria-label":`unassign ${l(q)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:s.busy,onClick:()=>void s.assign(q,!1),children:"×"})]},q))}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsxs("select",{"aria-label":"assign agent",className:Go,value:w,disabled:s.busy||P.length===0,onChange:q=>v(q.target.value),children:[o.jsx("option",{value:"",children:P.length===0?"No more agents":"Select an agent…"}),P.map(q=>o.jsx("option",{value:q.id,children:q.name},q.id))]}),o.jsx(M,{size:"sm",disabled:!w||s.busy,onClick:async()=>{await s.assign(w,!0)&&v("")},children:"Assign"})]})]}),o.jsx(l0,{open:D,projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...a.links.map(q=>q.targetRef)],onSelect:q=>{const L=Array.isArray(q)?q[0]:q;L&&s.link(L.ref,m),A(!1)},onClose:()=>A(!1)})]}):o.jsx("div",{className:"flex items-center justify-center py-10 text-sm text-muted",children:"Ticket not found."}),a&&o.jsx("div",{className:"pointer-events-none sticky bottom-0 z-10 -mx-4 -mb-4 flex justify-end px-4 pb-4 pt-2",children:o.jsx(M,{"aria-label":"ouvrir l'assistant IA",className:"pointer-events-auto shadow-lg",onClick:()=>R(!0),children:"🤖 Assistant IA"})}),o.jsx(Wh,{open:k,title:`Assistant IA — ${t}`,size:"lg",onClose:()=>R(!1),children:o.jsx(kB,{projectId:e,ticketRef:t})}),b&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"unsaved changes",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Modifications non sauvegardées"}),o.jsx("p",{className:"mt-2 text-sm text-muted",children:"Vous avez des modifications non sauvegardées. Voulez-vous les sauvegarder avant de fermer ?"}),o.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel close",disabled:s.busy,onClick:()=>j(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":"close without saving",disabled:s.busy,onClick:n,className:"text-danger hover:text-danger",children:"Fermer sans sauvegarder"}),o.jsx(M,{size:"sm","aria-label":"save and close",loading:s.busy,disabled:s.busy,onClick:()=>void C(),children:"Sauvegarder"})]})]})}),S&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"confirmer la suppression",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:o.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[o.jsx("h4",{className:"text-sm font-semibold text-content",children:"Supprimer le ticket"}),o.jsxs("p",{className:"mt-2 text-sm text-muted",children:["Supprimer définitivement le ticket ",t," ? Cette action est irréversible."]}),o.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete",disabled:s.busy,onClick:()=>N(!1),children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger","aria-label":"confirm delete",loading:s.busy,disabled:s.busy,onClick:async()=>{await s.remove()&&N(!1)},children:"Supprimer"})]})]})})]})}function NB({projectId:e}){const[t,n]=g.useState(null);return o.jsxs(o.Fragment,{children:[o.jsx(_B,{projectId:e,onOpen:n}),t&&o.jsx(jB,{projectId:e,ticketRef:t,onClose:()=>n(null),onOpenRef:n},`${e}-${t}`)]})}function Hv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function a0({projectId:e}){const{project:t}=ue(),[n,r]=g.useState(""),[s,i]=g.useState(""),[l,a]=g.useState(!1),[c,u]=g.useState(null);g.useEffect(()=>{let f=!1;return a(!0),u(null),t.readProjectContext(e).then(p=>{f||(r(p),i(p))}).catch(p=>{f||u(Hv(p))}).finally(()=>{f||a(!1)}),()=>{f=!0}},[t,e]);async function h(){a(!0),u(null);try{await t.updateProjectContext(e,n),i(n)}catch(f){u(Hv(f))}finally{a(!1)}}const d=n!==s;return o.jsxs(ke,{title:"Project Context",className:"flex flex-col gap-0",children:[c&&o.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:c}),o.jsx("div",{className:"border-b border-border px-4 py-2",children:o.jsx("code",{className:"text-xs text-muted",children:".ideai/CONTEXT.md"})}),o.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[o.jsx("textarea",{"aria-label":"project context",value:n,onChange:f=>r(f.target.value),rows:18,className:U("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:l}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l&&o.jsx(Ie,{size:14}),o.jsx(M,{variant:"primary",disabled:l||!d,onClick:()=>void h(),children:"Save"})]})]})]})}function c0({panel:e,projectId:t,projectRoot:n,onOpenConversation:r}){switch(e){case"context":return o.jsx(a0,{projectId:t});case"work":return o.jsx(aT,{projectId:t,onOpenConversation:r});case"tickets":return o.jsx(NB,{projectId:t});case"agents":return o.jsx(_w,{projectId:t,projectRoot:n});case"templates":return o.jsx(WS,{projectId:t});case"skills":return o.jsx(HS,{projectId:t});case"permissions":return o.jsx(QS,{projectId:t});case"memory":return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(GS,{projectId:t}),o.jsx(VS,{})]});case"git":return o.jsx(Rw,{projectId:t})}}const Un={projects:"Projects",context:"Project context",work:"Work state",tickets:"Tickets",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Memory",git:"Git"};function Ar(e,t){return e[t]??"closed"}function ls(e,t){return typeof e=="object"&&e.dock===t}function Uv(e,t){return Object.keys(Un).filter(n=>ls(Ar(e,n),t))}function EB(e){return Object.keys(Un).filter(t=>Ar(e,t)==="floating")}function id(e){return e==="detached"}function PB(e){return e!=="projects"&&e in Un}function AB(e,t){let n=!1;const r={...e};for(const s of t){if(!s.visible||!PB(s.panel))continue;const i=s.panel;Ar(e,i)==="closed"&&(r[i]="detached",n=!0)}return n?r:e}const TB={projects:"md",context:"lg",work:"lg",tickets:"lg",agents:"lg",templates:"lg",skills:"lg",permissions:"md",memory:"lg",git:"lg"};function LB(e){return e.type==="backgroundTaskChanged"&&(e.state==="completed"||e.state==="failed"||e.state==="cancelled"||e.state==="delivered")}function DB(){const e=RL(),{system:t,window:n,focusedProject:r,git:s}=ue(),[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState({}),[d,f]=g.useState(340),[p,m]=g.useState(340),[x,w]=g.useState(null),[v,y]=g.useState(null),[_,b]=g.useState(null),[j,S]=g.useState([]),N=e.openTabs.find(B=>B.id===e.activeTabId)??null,[D,A]=g.useState(!1);g.useEffect(()=>{if(!N){A(!1);return}let B=!1;return s.branches(N.id).then(()=>{B||A(!0)}).catch(()=>{B||A(!1)}),()=>{B=!0}},[s,N?.id]);const{registry:k}=vp(),T=yA(k,{projectOpen:N!==null,gitRepository:D,agentSelected:!1,terminalFocused:!1,layoutCellFocused:!1});g.useEffect(()=>{y(null),b(null)},[N?.id]),g.useEffect(()=>{r?.setFocusedProject(N?{id:N.id,name:N.name,root:N.root}:null)},[r,N?.id,N?.name,N?.root]),g.useEffect(()=>{let B,fe=!1;return t.onDomainEvent(de=>{if(!LB(de))return;const Ee={id:`${de.taskId}-${de.state}-${Date.now()}`,projectId:de.projectId,agentId:de.agentId,taskId:de.taskId,state:de.state};S(dt=>[...dt.slice(-2),Ee]),window.setTimeout(()=>{S(dt=>dt.filter(Rn=>Rn.id!==Ee.id))},7e3)}).then(de=>{fe?de():B=de}),()=>{fe=!0,B?.()}},[t]);const E=v?.kind??"terminal",O=i.trim().length>0&&a.trim().length>0&&!e.busy;async function I(B){B.preventDefault(),O&&(await e.createProject(i.trim(),a.trim()),l(""),c(""))}async function W(){const B=await t.pickFolder();B!==null&&c(B)}function G(B,fe){h(de=>{const Ee={...de};if(fe==="floating")for(const dt of Object.keys(Ee))dt!==B&&Ee[dt]==="floating"&&delete Ee[dt];return Ee[B]=fe,Ee})}function P(B){h(fe=>{if(!(B in fe))return fe;const de={...fe};return delete de[B],de})}function z(){h(B=>{let fe=!1;const de={...B};for(const Ee of Object.keys(de))de[Ee]==="floating"&&(delete de[Ee],fe=!0);return fe?de:B})}function C(B){N&&n.openViewWindow(B).then(()=>G(B,"detached")).catch(()=>{})}g.useEffect(()=>{let B,fe=!1;return n.onViewWindowClosed(({panel:de})=>{h(Ee=>Ee[de]==="detached"?(()=>{const dt={...Ee};return delete dt[de],dt})():Ee)}).then(de=>{fe?de():B=de}),()=>{fe=!0,B?.()}},[n]),g.useEffect(()=>{let B=!1;return n.listOpenViewWindows().then(fe=>{B||h(de=>AB(de,fe))}).catch(()=>{}),()=>{B=!0}},[n]);function Q(B){b(B),z()}const q=["context","work","tickets","agents","templates","skills","permissions","memory","git","projects"];function L(B){const fe=Ar(u,B),de=[{id:"closed",label:"Fermé",active:fe==="closed",onSelect:()=>P(B)},{id:"floating",label:"Flottant",active:fe==="floating",onSelect:()=>G(B,"floating")},{id:"dock-left",label:"Ancré à gauche",active:ls(fe,"left"),onSelect:()=>G(B,{dock:"left"})},{id:"dock-right",label:"Ancré à droite",active:ls(fe,"right"),onSelect:()=>G(B,{dock:"right"})}];return B!=="projects"&&de.push({id:"detached",label:"Fenêtre détachée",active:id(fe),disabled:!N,onSelect:()=>C(B)}),de}const se=[{id:"panels",label:"Panneaux",items:[...q.map(B=>({id:B,label:Un[B],active:Ar(u,B)!=="closed",onSelect:()=>{},submenu:L(B)})),...T.itemsFor("panels")]},...T.topLevelMenus,{id:"settings",label:"Paramètres",items:[...Lw.map(B=>({id:B,label:Tw[B],active:x===B,onSelect:()=>{w(B),z()}})),...T.itemsFor("settings")]}],te=o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("form",{onSubmit:I,className:"flex flex-col gap-2",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"New project"}),o.jsx(ie,{"aria-label":"project name",placeholder:"Project name",value:i,onChange:B=>l(B.target.value)}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ie,{"aria-label":"project root",placeholder:"/absolute/project/root",value:a,onChange:B=>c(B.target.value),className:"flex-1"}),o.jsx(M,{type:"button","aria-label":"browse project folder",onClick:()=>void W(),disabled:e.busy,children:"Browse…"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(M,{type:"submit",variant:"primary",disabled:!O,className:"flex-1",children:"Create project"}),o.jsx(M,{type:"button",onClick:()=>void e.refresh(),disabled:e.busy,children:"Refresh"})]})]}),o.jsx(ke,{title:"Known projects",children:e.projects.length===0?o.jsx("p",{className:"text-sm text-muted",children:"No projects yet."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:e.projects.map(B=>o.jsxs("li",{className:"flex items-center justify-between gap-2 py-2 first:pt-0 last:pb-0",children:[o.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[o.jsx("span",{className:"font-medium text-content",children:B.name}),o.jsx("code",{className:"truncate text-xs text-muted",children:B.root})]}),o.jsx(M,{size:"sm",onClick:()=>void e.openProject(B.id),children:"Open"})]},B.id))})})]});function J(B){return B==="projects"?te:N?o.jsx(c0,{panel:B,projectId:N.id,projectRoot:N.root,onOpenConversation:Q}):o.jsx("p",{className:"text-sm text-muted",children:"Open a project to use this panel."})}const K=!N&&Ar(u,"projects")==="closed",Y=Uv(u,"left"),ae=Uv(u,"right"),pe=EB(u);function Pe({panel:B}){const fe=Ar(u,B),de=Un[B],Ee="bg-raised text-content ring-1 ring-border-strong";return o.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(Hn,{size:"sm",title:"Ancré à gauche","aria-label":`Ancré à gauche — ${de}`,"aria-pressed":ls(fe,"left"),className:U(ls(fe,"left")&&Ee),onClick:()=>G(B,{dock:"left"}),children:"⇤"}),o.jsx(Hn,{size:"sm",title:"Ancré à droite","aria-label":`Ancré à droite — ${de}`,"aria-pressed":ls(fe,"right"),className:U(ls(fe,"right")&&Ee),onClick:()=>G(B,{dock:"right"}),children:"⇥"}),o.jsx(Hn,{size:"sm",title:"Flottant","aria-label":`Flottant — ${de}`,"aria-pressed":fe==="floating",className:U(fe==="floating"&&Ee),onClick:()=>G(B,"floating"),children:"□"}),B!=="projects"&&o.jsx(Hn,{size:"sm",title:"Fenêtre détachée","aria-label":`Fenêtre détachée — ${de}`,"aria-pressed":id(fe),disabled:!N,className:U(id(fe)&&Ee),onClick:()=>C(B),children:"↗"}),o.jsx(Hn,{size:"sm",title:"Fermé","aria-label":`Fermé — ${de}`,onClick:()=>P(B),children:"×"})]})}function $(B){return o.jsxs("section",{"aria-label":`${Un[B]} panel`,className:"flex min-h-0 flex-1 flex-col border-b border-border last:border-b-0",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2",children:[o.jsx("span",{className:"truncate text-sm font-medium text-content",children:Un[B]}),o.jsx(Pe,{panel:B})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3",children:J(B)})]},B)}return o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.error&&o.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),o.jsx(ML,{items:e.openTabs.map(B=>({id:B.id,label:B.name})),activeTabId:e.activeTabId,onSelect:B=>e.activateTab(B),onClose:B=>void e.closeTab(B),projectsPanelOpen:Ar(u,"projects")!=="closed",onOpenProjectsPanel:()=>{w(null),G("projects","floating")}}),o.jsx(YP,{menus:se}),o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[Y.length>0&&o.jsx(fx,{side:"left",width:d,onResize:f,"aria-label":"left dock",children:Y.map($)}),o.jsx("main",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:x?o.jsx(SL,{section:x,onSectionChange:w,onClose:()=>w(null)}):N&&_?o.jsx(fT,{projectId:N.id,conversationId:_,onClose:()=>b(null)},`${N.id}-${_}`):N?o.jsxs(o.Fragment,{children:[o.jsx(KA,{projectId:N.id,onActiveLayoutChange:y}),E==="gitGraph"?o.jsx(DL,{projectId:N.id},`${N.id}-${v?.id??"default"}-graph`):o.jsx(zA,{projectId:N.id,cwd:N.root,layoutId:v?.id,onOpenConversation:Q,onOpenPluginsSettings:()=>{w("plugins"),z()}},`${N.id}-${v?.id??"default"}`)]}):o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-xl",children:K?te:o.jsx("p",{className:"text-sm text-muted",children:"Select or create a project to get started."})})})}),ae.length>0&&o.jsx(fx,{side:"right",width:p,onResize:m,"aria-label":"right dock",children:ae.map($)})]}),pe.map(B=>o.jsxs(Wh,{open:!0,title:Un[B],size:TB[B],onClose:()=>P(B),children:[o.jsx("div",{className:"mb-3 flex justify-end border-b border-border pb-3",children:o.jsx(Pe,{panel:B})}),J(B)]},B)),j.length>0&&o.jsx("div",{className:"fixed bottom-4 right-4 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",style:{zIndex:Sn.toast},children:j.map(B=>o.jsxs("button",{type:"button",className:"rounded-md border border-border bg-surface px-3 py-2 text-left shadow-lg hover:border-border-strong",onClick:()=>{e.openTabs.some(de=>de.id===B.projectId)&&e.activateTab(B.projectId),w(null),b(null),G("work","floating"),S(de=>de.filter(Ee=>Ee.id!==B.id))},children:[o.jsxs("span",{className:"block text-sm font-medium text-content",children:["Background task ",B.state]}),o.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted",children:[B.agentId.slice(0,8)," · ",B.taskId.slice(0,8)]})]},B.id))})]})}const RB=5;function MB(e){if(e.totalWorkCount===1)return"1 travail actif sera interrompu si vous quittez IdeA maintenant.";const t=[];return e.busyAgentCount>0&&t.push(e.busyAgentCount===1?"1 agent travaille encore":`${e.busyAgentCount} agents travaillent encore`),e.activeBackgroundTaskCount>0&&t.push(e.activeBackgroundTaskCount===1?"1 tâche de fond est encore active":`${e.activeBackgroundTaskCount} tâches de fond sont encore actives`),`${t.join(" et ")}. Ces travaux seront interrompus si vous quittez IdeA maintenant.`}function IB(e){return e.kind==="busyAgent"?`Agent ${e.agentName} — ${e.projectName}`:`Tâche de fond ${e.taskId.slice(0,8)} — ${e.projectName}`}function OB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const qv="app-exit-confirm-title",Kv="app-exit-confirm-desc";function BB(){const{system:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{let p=!1,m;return e.onAppExitWorkGuard(x=>{n(x)}).then(x=>{p?x():m=x}).catch(()=>{}),()=>{p=!0,m?.()}},[e]),g.useEffect(()=>{t&&a.current?.focus()},[t!=null]);function u(){r||(n(null),l(null))}async function h(){s(!0),l(null);try{await e.confirmAppExit()}catch(p){l(OB(p))}finally{s(!1)}}if(g.useEffect(()=>{if(!t)return;function p(m){if(m.key==="Escape"){m.preventDefault(),u();return}if(m.key!=="Tab")return;const x=c.current?.querySelectorAll('button:not(:disabled), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(!x||x.length===0)return;const w=x[0],v=x[x.length-1];m.shiftKey&&document.activeElement===w?(m.preventDefault(),v.focus()):!m.shiftKey&&document.activeElement===v&&(m.preventDefault(),w.focus())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t!=null,r]),!t)return null;const d=t.details.slice(0,RB),f=t.details.length-d.length;return o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.toast},children:o.jsxs("div",{ref:c,role:"alertdialog","aria-modal":"true","aria-labelledby":qv,"aria-describedby":Kv,onClick:p=>p.stopPropagation(),className:"flex w-full max-w-[520px] min-w-[440px] flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{id:qv,className:"text-sm font-semibold text-content",children:"Du travail est encore en cours"}),o.jsx("p",{id:Kv,className:"text-sm text-content",children:MB(t)}),o.jsx("p",{className:"text-sm text-muted",children:"Annulez la fermeture pour laisser les agents et les tâches se terminer."}),d.length>0&&o.jsxs("ul",{className:"flex flex-col gap-1 rounded-md bg-canvas p-2 text-xs text-muted",children:[d.map((p,m)=>o.jsx("li",{children:`• ${IB(p)}`},m)),f>0&&o.jsxs("li",{children:["+ ",f," autre",f>1?"s":""]})]}),i&&o.jsx("p",{role:"alert",className:"text-sm text-danger",children:"IdeA n'a pas pu quitter correctement. Réessayez ou consultez les logs."}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx(M,{ref:a,size:"sm",variant:"ghost",disabled:r,onClick:u,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger",disabled:r,loading:r,onClick:()=>void h(),children:r?"Fermeture…":"Quitter quand même"})]})]})})}function zB(){const{system:e,profile:t}=ue(),[n,r]=g.useState(null),[s,i]=g.useState(null),[l,a]=g.useState([]),[c,u]=g.useState(null);return g.useEffect(()=>{let h,d=!1;return e.onDomainEvent(f=>a(p=>[...p,f])).then(f=>{d?f():h=f}).catch(()=>{}),e.health("ui-boot").then(f=>r(f)).catch(f=>i(FB(f))),()=>{d=!0,h?.()}},[e]),g.useEffect(()=>{let h=!1;return t.firstRunState().then(d=>{h||u(d.isFirstRun)}).catch(()=>{h||u(!1)}),()=>{h=!0}},[t]),o.jsx(OP,{children:o.jsxs(hA,{children:[o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between border-b border-border px-6 py-3",children:[o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"IdeA"}),o.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"tauri"})]}),o.jsx(xw,{justify:"end",children:o.jsx("span",{className:"text-xs text-faint",children:n?o.jsxs(o.Fragment,{children:["backend ",o.jsx("span",{className:"text-success",children:"●"})," v",n.version," ·"," ",l.length," events"]}):s?o.jsx("span",{className:"text-danger",children:"backend unavailable"}):o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx(Ie,{size:12})," checking…"]})})})]}),o.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[s&&o.jsx(ke,{className:"mx-4 mt-4 border-danger/40",children:o.jsxs("p",{className:"text-sm text-danger",children:["Error: ",s]})}),c?o.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:o.jsx("div",{className:"w-full max-w-xl",children:o.jsx(Cw,{onDone:()=>u(!1)})})}):o.jsx(DB,{})]})]}),o.jsx(BB,{})]})})}function FB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const $B=new Set(Object.keys(Un).filter(e=>e!=="projects"));function WB(e){const n=new URLSearchParams(e).get("panel");return!n||!$B.has(n)?null:{panel:n}}function HB({panel:e}){const{focusedProject:t}=ue(),[n,r]=g.useState(void 0);return g.useEffect(()=>{let s=!1,i;return t.getFocusedProject().then(l=>{s||r(l)}).catch(()=>{s||r(null)}),t.onFocusedProjectChanged(l=>{s||r(l)}).then(l=>{s?l():i=l}),()=>{s=!0,i?.()}},[t]),o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5",children:[o.jsx("h1",{className:"text-sm font-semibold text-content",children:Un[e]}),n&&o.jsxs("span",{className:"truncate text-xs text-muted",children:["· ",n.name]})]}),o.jsx("main",{className:"min-h-0 flex-1 overflow-auto p-4",children:n?o.jsx(c0,{panel:e,projectId:n.id,projectRoot:n.root}):o.jsx(ke,{children:o.jsx("p",{className:"text-sm text-muted",children:"Ouvrez un projet dans la fenêtre principale pour afficher ce panneau."})})})]})}function UB(e){if(e&&typeof e=="object"&&"message"in e){const t=e;return{code:String(t.code??"ERROR"),message:String(t.message)}}return{code:"ERROR",message:String(e)}}function qB({session:e,onPaired:t}){const[n,r]=g.useState(""),[s,i]=g.useState(()=>jx(hL())),[l,a]=g.useState(null),[c,u]=g.useState(!1),h=ZO(n),d=s.trim(),f=h.length>0&&d.length>0,p=l?.code==="invalidName"?l.message:null,m=l&&!p?l.message:null;async function x(w){if(w.preventDefault(),!(!f||c)){u(!0),a(null);try{await e.pair(h,jx(d)),t()}catch(v){a(UB(v))}finally{u(!1)}}}return o.jsx("div",{className:"flex h-full items-center justify-center overflow-y-auto bg-canvas p-4 sm:p-6",children:o.jsx(ke,{className:"w-full max-w-sm",children:o.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Appairer cet appareil"}),o.jsx("p",{className:"text-sm text-muted",children:"Saisissez le code affiché par le serveur IdeA pour connecter ce navigateur."})]}),o.jsx(qt,{label:"Code d'appairage",hint:"8 caractères : chiffres et lettres A-F",children:({id:w,describedBy:v})=>o.jsx(ie,{id:w,"aria-describedby":v,value:n,onChange:y=>r(y.target.value),placeholder:"p. ex. AB12CD34",autoFocus:!0,autoComplete:"one-time-code",inputMode:"text",autoCapitalize:"characters",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!m})}),o.jsx(qt,{label:"Nom de cet appareil",hint:"Pour le reconnaître dans la liste des appareils.",error:p??void 0,children:({id:w,describedBy:v})=>o.jsx(ie,{id:w,"aria-describedby":v,value:s,onChange:y=>i(y.target.value),maxLength:_p,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!p})}),m&&o.jsx("p",{role:"alert","data-testid":"pairing-error",className:"text-sm text-danger",children:m}),o.jsx(M,{type:"submit",disabled:c||!f,children:c?"Appairage…":"Appairer"})]})})})}const KB=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Ctrl-C",aria:"Ctrl-C (interrompre)",data:""},{label:"Ctrl-D",aria:"Ctrl-D (fin de saisie)",data:""},{label:"↑",aria:"Flèche haut",data:"\x1B[A"},{label:"↓",aria:"Flèche bas",data:"\x1B[B"},{label:"←",aria:"Flèche gauche",data:"\x1B[D"},{label:"→",aria:"Flèche droite",data:"\x1B[C"}];function VB({api:e,className:t}){return o.jsx("div",{role:"toolbar","aria-label":"Touches du terminal","data-testid":"terminal-key-bar",className:U("flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-raised/40 px-2 py-1.5",t),children:KB.map(n=>o.jsx(M,{size:"sm",variant:"secondary","aria-label":n.aria??n.label,disabled:!e,onPointerDown:r=>r.preventDefault(),onClick:()=>{e?.send(n.data),e?.focus()},className:"min-h-11 shrink-0 font-mono",children:n.label},n.label))})}function GB({projectId:e,agentId:t,cwd:n,nodeId:r,refitSignal:s}){const{agent:i}=ue(),[l,a]=g.useState(null),[c,u]=g.useState(null),h=g.useCallback((f,p)=>i.launchAgent(e,t,r?{...f,nodeId:r}:f,p),[i,e,t,r]),d=g.useCallback((f,p)=>i.reattach(f,p),[i]);return o.jsxs("div",{"data-testid":"web-agent-cell",className:"flex h-[60dvh] min-h-64 w-full flex-col overflow-hidden rounded-md border border-border sm:h-80",children:[o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(pp,{cwd:n,agentMode:!0,open:h,reattach:d,sessionId:l,onSessionId:a,onReady:u,refitSignal:s})}),o.jsx(VB,{api:c})]})}function YB(e){g.useEffect(()=>{const t=Fh();if(!t)return;let n=t.getConnectionState();return t.onConnectionStateChange(r=>{r==="connected"&&n==="reconnecting"&&e(),n=r})},[e])}function XB(){const[e,t]=g.useState(()=>Fh()?.getConnectionState()??null);return g.useEffect(()=>{const n=Fh();if(n)return t(n.getConnectionState()),n.onConnectionStateChange(t)},[]),e}function Oc(e){switch(e){case"open":return"Ouvert";case"inProgress":return"En cours";case"QA":return"QA";case"closed":return"Fermé"}}function oo(e){switch(e){case"low":return"Faible";case"medium":return"Moyenne";case"high":return"Haute";case"critical":return"Critique"}}function Vv(e){switch(e){case"relatesTo":return"en relation avec";case"blocks":return"bloque";case"blockedBy":return"bloqué par";case"duplicates":return"duplique";case"dependsOn":return"dépend de"}}function QB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function JB(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function u0(e){return U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function Up({status:e}){return o.jsx("span",{className:u0(QB(e)),children:Oc(e)})}function qp({priority:e}){return o.jsx("span",{className:u0(JB(e)),children:oo(e)})}const Gv=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),ZB=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function e4({sprints:e,busy:t,error:n,onCancel:r,onCreate:s}){const[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState("medium"),[d,f]=g.useState("");async function p(m){m.preventDefault();const x=i.trim();x&&await s({title:x,priority:u,...a.trim()?{description:a.trim()}:{}},d||null)}return o.jsxs(ke,{title:"Nouveau ticket",actions:o.jsx(M,{size:"sm",variant:"ghost",onClick:r,children:"Annuler"}),children:[n&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n}),o.jsxs("form",{onSubmit:p,className:"flex flex-col gap-3",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),o.jsx(ie,{"aria-label":"Titre",value:i,onChange:m=>l(m.target.value),disabled:t,autoFocus:!0})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Priorité"}),o.jsx("select",{"aria-label":"Priorité",className:Gv,value:u,disabled:t,onChange:m=>h(m.target.value),children:Ni.map(m=>o.jsx("option",{value:m,children:oo(m)},m))})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Sprint"}),o.jsxs("select",{"aria-label":"Sprint",className:Gv,value:d,disabled:t,onChange:m=>f(m.target.value),children:[o.jsx("option",{value:"",children:"Sans sprint"}),e.map(m=>o.jsx("option",{value:m.id,children:m.name},m.id))]})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),o.jsx("textarea",{"aria-label":"Description",className:U(ZB,"min-h-20"),value:a,onChange:m=>c(m.target.value),disabled:t})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx(M,{type:"button",variant:"ghost",size:"sm",disabled:t,onClick:r,children:"Annuler"}),o.jsx(M,{type:"submit",size:"sm",disabled:!i.trim()||t,loading:t,children:"Créer"})]})]})]})}function d0({title:e,body:t,confirmLabel:n,busy:r=!1,onConfirm:s,onCancel:i}){const l=g.useRef(null);return g.useEffect(()=>{l.current?.focus()},[]),g.useEffect(()=>{function a(c){c.key==="Escape"&&i()}return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[i]),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:Sn.toast},children:o.jsxs("div",{role:"alertdialog","aria-modal":"true","aria-label":e,onClick:a=>a.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),o.jsx("p",{className:"text-sm text-muted",children:t}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{ref:l,size:"sm",variant:"ghost",disabled:r,onClick:i,children:"Annuler"}),o.jsx(M,{size:"sm",variant:"danger",loading:r,disabled:r,onClick:()=>void s(),children:n})]})]})})}function h0({projectId:e,title:t,confirmLabel:n="Ajouter",selectionMode:r,excludeRefs:s,onSelect:i,onClose:l}){const a=Ic(e,{excludeRefs:s}),c=r==="multi",[u,h]=g.useState(()=>new Set),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useRef(null);g.useEffect(()=>{x.current?.focus()},[]),g.useEffect(()=>{function b(j){j.key==="Escape"&&l()}return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[l]);function w(b){return b&&typeof b=="object"&&"message"in b?String(b.message):String(b)}function v(b){h(j=>{const S=new Set(j);return S.has(b)?S.delete(b):S.add(b),S})}async function y(b){if(!d){f(!0),m(null);try{i(await a.resolve(b)),l()}catch(j){m(w(j)),f(!1)}}}async function _(){if(!(d||u.size===0)){f(!0),m(null);try{const b=await Promise.all(Array.from(u).map(j=>a.resolve(j)));i(b),l()}catch(b){m(w(b)),f(!1)}}}return o.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":t,style:{zIndex:Sn.floatingWindowNested},children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[o.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:t}),o.jsx(M,{ref:x,size:"sm",variant:"ghost",onClick:l,children:"Fermer"})]}),o.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:o.jsx(ie,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:a.text,onChange:b=>a.setText(b.target.value),autoFocus:!0})}),(a.error||p)&&o.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??a.error}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[a.busy&&a.rows.length===0?o.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Chargement des tickets…"})]}):a.rows.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:a.rows.map(b=>{const j=u.has(b.ref);return o.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:o.jsxs("button",{type:"button","aria-label":`${b.ref}, ${b.title}`,...c?{role:"checkbox","aria-checked":j}:{},disabled:d,onClick:()=>c?v(b.ref):void y(b.ref),className:U("flex min-h-[40px] w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-60",c&&j&&"bg-raised"),children:[c&&o.jsx("span",{"aria-hidden":"true",className:U("flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",j?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:b.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:b.title}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[o.jsx(Up,{status:b.status}),o.jsx(qp,{priority:b.priority})]})]})},b.ref)})}),a.hasMore&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:a.busy,onClick:()=>a.loadMore(),children:"Charger plus"})})]}),c&&o.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]",children:[o.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[u.size," sélectionné",u.size>1?"s":""]}),o.jsxs(M,{size:"sm",loading:d,disabled:u.size===0||d,onClick:()=>void _(),children:[n," ",u.size>0?`(${u.size})`:""]})]})]})}const Fs=U("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Yv=U("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function $s({title:e,defaultOpen:t,children:n}){const[r,s]=g.useState(t);return o.jsxs("section",{className:"border-b border-border py-2 last:border-b-0",children:[o.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>s(i=>!i),className:"flex min-h-[32px] w-full items-center justify-between text-left text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{"aria-hidden":"true",children:r?"▾":"▸"})]}),r&&o.jsx("div",{className:"mt-2 flex flex-col gap-2",children:n})]})}function t4({projectId:e,ticketRef:t,nameOf:n,assignableAgents:r,sprints:s,onBack:i,onOpenRef:l}){const a=o0(e,t),c=a.ticket,[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState("relatesTo"),[v,y]=g.useState(""),[_,b]=g.useState(!1),[j,S]=g.useState(!1),[N,D]=g.useState(!1);g.useEffect(()=>{a.deleted&&i()},[a.deleted,i]);const A=a.reloadCount,k=g.useRef(-1),R=g.useRef(null);g.useEffect(()=>{if(!c||k.current===A)return;k.current=A;const P=c.carnet??"",z=R.current;z===null||a.conflict?(h(c.title),f(c.description),m(P)):(h(Q=>Q===z.title?c.title:Q),f(Q=>Q===z.description?c.description:Q),m(Q=>Q===z.carnet?P:Q)),R.current={title:c.title,description:c.description,carnet:P}},[c,A,a.conflict]);const T=!!c&&(u!==c.title||d!==c.description),E=!!c&&p!==(c.carnet??""),O=T||E,I=r.filter(P=>!c?.assignedAgentIds.includes(P.id));function W(){O?S(!0):i()}async function G(){let P=!0;T&&(P=await a.updateFields({title:u,description:d})&&P),P&&E&&(P=await a.saveCarnet(p)&&P),S(!1),P&&i()}return o.jsxs(ke,{className:"flex flex-col",flush:!0,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:W,children:"← Tickets"}),o.jsx("code",{className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:t})]}),a.conflict&&o.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-4 py-2 text-sm text-warning",children:"Ce ticket a été modifié ailleurs et rechargé. Réappliquez votre modification."}),a.error&&!a.conflict&&o.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:a.error}),a.busy&&!c?o.jsxs("div",{className:"flex items-center gap-2 px-4 py-5 text-sm text-muted",children:[o.jsx(Ie,{size:14}),o.jsx("span",{children:"Chargement du ticket…"})]}):c?o.jsxs("div",{className:"flex flex-col px-4 py-2",children:[o.jsxs("div",{className:"flex flex-col gap-1 border-b border-border pb-3",children:[o.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),o.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[o.jsx(Up,{status:c.status}),o.jsx(qp,{priority:c.priority}),c.sprintId&&o.jsxs("span",{children:["· ",s.find(P=>P.id===c.sprintId)?.name??"Sprint"]})]})]}),o.jsxs($s,{title:"Résumé",defaultOpen:!0,children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),o.jsx("input",{"aria-label":"Titre",className:U(Fs,"w-full"),value:u,onChange:P=>h(P.target.value),disabled:a.busy})]}),o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),o.jsx("textarea",{"aria-label":"Description",className:U(Yv,"min-h-24"),value:d,onChange:P=>f(P.target.value),disabled:a.busy})]}),o.jsx("div",{children:o.jsx(M,{size:"sm",disabled:!T||a.busy,loading:a.busy&&T,onClick:()=>void a.updateFields({title:u,description:d}),children:"Enregistrer"})})]}),o.jsxs($s,{title:"Statut et priorité",defaultOpen:!0,children:[o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Statut"}),o.jsx("select",{"aria-label":"Statut",className:Fs,value:c.status,disabled:a.busy,onChange:P=>void a.updateFields({status:P.target.value}),children:Rc.map(P=>o.jsx("option",{value:P,children:Oc(P)},P))})]}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Priorité"}),o.jsx("select",{"aria-label":"Priorité",className:Fs,value:c.priority,disabled:a.busy,onChange:P=>void a.updateFields({priority:P.target.value}),children:Ni.map(P=>o.jsx("option",{value:P,children:oo(P)},P))})]}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{className:"text-muted",children:"Sprint"}),o.jsxs("select",{"aria-label":"Sprint",className:Fs,value:c.sprintId??"",disabled:a.busy,onChange:P=>void a.setSprint(P.target.value||null),children:[o.jsx("option",{value:"",children:"Sans sprint"}),s.map(P=>o.jsx("option",{value:P.id,children:P.name},P.id))]})]}),a.busy&&o.jsx(Ie,{size:12})]}),o.jsxs($s,{title:"Carnet",defaultOpen:!0,children:[o.jsx("textarea",{"aria-label":"Carnet",className:U(Yv,"min-h-32 font-mono"),value:p,onChange:P=>m(P.target.value),disabled:a.busy}),o.jsx("div",{children:o.jsx(M,{size:"sm",disabled:!E||a.busy,loading:a.busy&&E,onClick:()=>void a.saveCarnet(p),children:"Enregistrer le carnet"})})]}),o.jsxs($s,{title:"Agents assignés",defaultOpen:!1,children:[c.assignedAgentIds.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun agent assigné."}):o.jsx("ul",{className:"flex flex-wrap gap-2",children:c.assignedAgentIds.map(P=>o.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[n(P),o.jsx("button",{type:"button","aria-label":`Désassigner ${n(P)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:a.busy,onClick:()=>void a.assign(P,!1),children:"×"})]},P))}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("select",{"aria-label":"Assigner un agent",className:Fs,value:v,disabled:a.busy||I.length===0,onChange:P=>y(P.target.value),children:[o.jsx("option",{value:"",children:I.length===0?"Aucun autre agent":"Choisir un agent…"}),I.map(P=>o.jsx("option",{value:P.id,children:P.name},P.id))]}),o.jsx(M,{size:"sm",disabled:!v||a.busy,onClick:async()=>{await a.assign(v,!0)&&y("")},children:"Assigner"})]})]}),o.jsxs($s,{title:"Liens",defaultOpen:!1,children:[c.links.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun ticket lié."}):o.jsx("ul",{className:"flex flex-col gap-1",children:c.links.map(P=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"text-xs text-muted",children:Vv(P.kind)}),o.jsx("button",{type:"button",className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content hover:text-primary",onClick:()=>l(P.targetRef),children:P.targetRef}),o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:()=>void a.unlink(P.targetRef,P.kind),children:"Retirer"})]},`${P.kind}-${P.targetRef}`))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("select",{"aria-label":"Type de lien",className:Fs,value:x,disabled:a.busy,onChange:P=>w(P.target.value),children:r0.map(P=>o.jsx("option",{value:P,children:Vv(P)},P))}),o.jsx(M,{size:"sm",disabled:a.busy,onClick:()=>D(!0),children:"+ Lier"})]})]}),o.jsxs($s,{title:"Zone dangereuse",defaultOpen:!1,children:[o.jsxs("p",{className:"text-xs text-muted",children:["Le ticket ",t," sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés."]}),o.jsx("div",{children:o.jsx(M,{size:"sm",variant:"danger",disabled:a.busy,onClick:()=>b(!0),children:"Supprimer"})})]})]}):o.jsx("p",{className:"px-4 py-5 text-sm text-muted",children:"Ticket introuvable."}),N&&c&&o.jsx(h0,{projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...c.links.map(P=>P.targetRef)],onSelect:P=>{const z=Array.isArray(P)?P[0]:P;z&&a.link(z.ref,x)},onClose:()=>D(!1)}),_&&o.jsx(d0,{title:"Supprimer ce ticket ?",body:`Le ticket ${t} sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés.`,confirmLabel:"Supprimer",busy:a.busy,onCancel:()=>b(!1),onConfirm:async()=>{await a.remove()&&b(!1)}}),j&&o.jsx("div",{role:"alertdialog","aria-modal":"true","aria-label":"Modifications non enregistrées",className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",children:o.jsxs("div",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[o.jsx("h3",{className:"text-sm font-semibold text-content",children:"Des modifications ne sont pas enregistrées."}),o.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:()=>S(!1),children:"Continuer l'édition"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:a.busy,onClick:i,children:"Ignorer"}),o.jsx(M,{size:"sm",loading:a.busy,disabled:a.busy,onClick:()=>void G(),children:"Enregistrer et quitter"})]})]})})]})}function n4(e){const t=eo(e),n=g.useMemo(()=>(t.state?.agents??[]).map(i=>({id:i.agentId,name:i.name})),[t.state]),r=g.useMemo(()=>new Map(n.map(i=>[i.id,i.name])),[n]);return{agents:n,nameOf:i=>r.get(i)??`${i.slice(0,8)}…`,loaded:t.state!==null}}const Yo=U("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Xv={number:"Numéro",priority:"Priorité",status:"Statut",title:"Titre"};function r4({projectId:e,focusSprintId:t=null}){const n=$p(e),r=n4(e),[s,i]=g.useState({type:"list"}),[l,a]=g.useState(t);if(s.type==="detail")return o.jsx(t4,{projectId:e,ticketRef:s.ref,nameOf:r.nameOf,assignableAgents:r.agents,sprints:n.sprints,onBack:()=>i({type:"list"}),onOpenRef:x=>i({type:"detail",ref:x})},s.ref);if(s.type==="create")return o.jsx(e4,{sprints:n.sprints,busy:n.busy,error:n.error,onCancel:()=>i({type:"list"}),onCreate:async(x,w)=>{const v=await n.create(x);v&&(w&&await n.assignSprint(v.ref,w),i({type:"detail",ref:v.ref}))}});const c=n.list?.items??[],u=!!n.query.text||(n.query.statuses?.length??0)>0||(n.query.priorities?.length??0)>0||!!n.query.assignedAgentId||!!l,h=new Set(n.sprints.map(x=>x.id)),f=(l?n.sprints.filter(x=>x.id===l):n.sprints).map(x=>({sprint:x,tickets:c.filter(w=>w.sprintId===x.id)})).filter(x=>x.tickets.length>0),p=l?[]:c.filter(x=>!x.sprintId||!h.has(x.sprintId));function m(){n.setQuery({}),a(null)}return o.jsxs(ke,{className:"flex flex-col",title:"Tickets",actions:o.jsx(M,{size:"sm",onClick:()=>i({type:"create"}),children:"+ Ticket"}),children:[n.error&&o.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[o.jsx("span",{children:n.error}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),children:"Réessayer"})]}),l&&o.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 rounded-md border border-border bg-raised/50 px-3 py-2 text-xs text-muted",children:[o.jsxs("span",{children:["Filtré sur le sprint « ",n.sprints.find(x=>x.id===l)?.name??l," »"]}),o.jsx(M,{size:"sm",variant:"ghost",onClick:()=>a(null),children:"Voir tous les tickets"})]}),o.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[o.jsx(ie,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:n.query.text??"",onChange:x=>n.setQuery({...n.query,text:x.target.value||void 0})}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("select",{"aria-label":"Filtrer par statut",className:Yo,value:n.query.statuses?.[0]??"",onChange:x=>n.setQuery({...n.query,statuses:x.target.value?[x.target.value]:void 0}),children:[o.jsx("option",{value:"",children:"Tous les statuts"}),Rc.map(x=>o.jsx("option",{value:x,children:Oc(x)},x))]}),o.jsxs("select",{"aria-label":"Filtrer par priorité",className:Yo,value:n.query.priorities?.[0]??"",onChange:x=>n.setQuery({...n.query,priorities:x.target.value?[x.target.value]:void 0}),children:[o.jsx("option",{value:"",children:"Toutes les priorités"}),Ni.map(x=>o.jsx("option",{value:x,children:oo(x)},x))]}),o.jsxs("select",{"aria-label":"Filtrer par agent assigné",className:Yo,value:n.query.assignedAgentId??"",onChange:x=>n.setQuery({...n.query,assignedAgentId:x.target.value||void 0}),children:[o.jsx("option",{value:"",children:"Tous les agents"}),r.agents.map(x=>o.jsx("option",{value:x.id,children:x.name},x.id))]}),o.jsxs("select",{"aria-label":"Trier les tickets",className:Yo,value:n.query.sort?.field??"",onChange:x=>{const w=x.target.value,{sort:v,...y}=n.query;n.setQuery(w?{...y,sort:{field:w,direction:"asc"}}:y)},children:[o.jsx("option",{value:"",children:"Tri par défaut"}),Object.keys(Xv).map(x=>o.jsx("option",{value:x,children:Xv[x]},x))]})]})]}),n.busy&&n.list===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Ie,{size:12})," Chargement des tickets…"]}):c.length===0&&!u?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket dans ce projet."}),o.jsx(M,{size:"sm",onClick:()=>i({type:"create"}),children:"Créer un ticket"})]}):c.length===0?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond aux filtres."}),o.jsx(M,{size:"sm",variant:"ghost",onClick:m,children:"Réinitialiser les filtres"})]}):o.jsxs("div",{className:"flex flex-col gap-4","data-testid":"web-ticket-list",children:[f.map(x=>o.jsx(Qv,{heading:x.sprint.name,tickets:x.tickets,sprints:n.sprints,nameOf:r.nameOf,onOpen:w=>i({type:"detail",ref:w})},x.sprint.id)),p.length>0&&o.jsx(Qv,{heading:"Sans sprint",tickets:p,sprints:n.sprints,nameOf:r.nameOf,onOpen:x=>i({type:"detail",ref:x})})]}),n.list?.nextCursor&&o.jsx("div",{className:"mt-3 flex justify-center",children:o.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Charger plus"})})]})}function Qv({heading:e,tickets:t,sprints:n,nameOf:r,onOpen:s}){const i=l=>l?n.find(a=>a.id===l)?.name:void 0;return o.jsxs("section",{"aria-label":`Tickets — ${e}`,children:[o.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,o.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t.length})]}),o.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(l=>{const a=i(l.sprintId),c=l.assignedAgentIds.map(r).join(", ");return o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>s(l.ref),"aria-label":`${l.ref}, ${l.title}, statut ${Oc(l.status)}, priorité ${oo(l.priority)}`,className:"flex w-full min-w-0 flex-col items-start gap-0.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-raised",children:[o.jsxs("span",{className:"flex w-full min-w-0 items-baseline gap-2",children:[o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:l.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:l.title})]}),o.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[o.jsx(Up,{status:l.status}),o.jsx(qp,{priority:l.priority}),a&&o.jsxs("span",{children:["· ",a]}),c&&o.jsxs("span",{children:["· ",c]})]})]})},l.ref)})})]})}function s4({projectId:e,onViewSprintTickets:t}){const n=$p(e),r=Ic(e,{refreshOnEvents:!0}),[s,i]=g.useState(!1),[l,a]=g.useState(""),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState(null),[m,x]=g.useState(null),w=[...n.sprints].sort((y,_)=>y.order-_.order);async function v(y){y.preventDefault();const _=l.trim();if(!_)return;await n.createSprint(_)&&(a(""),i(!1))}return o.jsxs(ke,{title:"Sprints",actions:o.jsx(M,{size:"sm",onClick:()=>i(y=>!y),children:"+ Sprint"}),children:[n.error&&o.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),s&&o.jsxs("form",{onSubmit:v,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[o.jsxs("label",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-xs font-medium text-muted",children:"Nom du sprint"}),o.jsx(ie,{"aria-label":"Nom du sprint",value:l,onChange:y=>a(y.target.value),autoFocus:!0})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(!1),children:"Annuler"}),o.jsx(M,{type:"submit",size:"sm",disabled:!l.trim()||n.busy,children:"Créer"})]})]}),n.busy&&n.sprints.length===0?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Ie,{size:12})," Chargement des sprints…"]}):w.length===0?o.jsxs("div",{className:"flex flex-col items-start gap-2",children:[o.jsx("p",{className:"text-sm text-muted",children:"Aucun sprint."}),o.jsx(M,{size:"sm",onClick:()=>i(!0),children:"Créer un sprint"})]}):o.jsx("ul",{className:"flex flex-col gap-3",children:w.map((y,_)=>o.jsx(i4,{sprint:y,index:_,lastIndex:w.length-1,tickets:r.rows.filter(b=>b.sprintId===y.id),vm:n,renaming:c===y.id,renameDraft:h,onStartRename:()=>{u(y.id),d(y.name)},onRenameDraftChange:d,onCancelRename:()=>u(null),onSaveRename:async()=>{await n.renameSprint(y.id,h.trim())&&u(null)},onViewTickets:()=>t(y.id),onAddTickets:()=>x({id:y.id,name:y.name}),onRequestDelete:()=>p({id:y.id,name:y.name})},y.id))}),f&&o.jsx(d0,{title:`Supprimer le sprint « ${f.name} » ?`,body:"Les tickets de ce sprint seront conservés et passeront en « Sans sprint ».",confirmLabel:"Supprimer",busy:n.busy,onCancel:()=>p(null),onConfirm:async()=>{await n.deleteSprint(f.id),p(null)}}),m&&o.jsx(h0,{projectId:e,title:`Ajouter des tickets au sprint « ${m.name} »`,confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:r.rows.filter(y=>y.sprintId===m.id).map(y=>y.ref),onSelect:y=>{const _=Array.isArray(y)?y:[y];for(const b of _)n.assignSprint(b.ref,m.id)},onClose:()=>x(null)})]})}function i4({sprint:e,index:t,lastIndex:n,tickets:r,vm:s,renaming:i,renameDraft:l,onStartRename:a,onRenameDraftChange:c,onCancelRename:u,onSaveRename:h,onViewTickets:d,onAddTickets:f,onRequestDelete:p}){return o.jsxs("li",{className:"rounded-md border border-border p-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",e.order]}),!i&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e.name})]}),i?o.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[o.jsx(ie,{"aria-label":`Renommer le sprint ${e.name}`,value:l,onChange:m=>c(m.target.value),disabled:s.busy}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:s.busy,onClick:u,children:"Annuler"}),o.jsx(M,{size:"sm",disabled:s.busy||!l.trim()||l.trim()===e.name,onClick:()=>void h(),children:"Enregistrer"})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"mt-1 text-xs text-muted",children:[e.ticketCount," ticket",e.ticketCount>1?"s":""]}),r.length>0&&o.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:r.map(m=>o.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[o.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:m.ref}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:m.title}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Retirer ${m.ref} du sprint ${e.name}`,disabled:s.busy,onClick:()=>void s.assignSprint(m.ref,null),children:"Retirer du sprint"})]},m.ref))}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[o.jsx(M,{size:"sm",variant:"ghost",onClick:d,children:"Voir tickets"}),o.jsx(M,{size:"sm",variant:"ghost",onClick:f,children:"Ajouter tickets"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Renommer ${e.name}`,disabled:s.busy,onClick:a,children:"Renommer"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Monter ${e.name}`,disabled:s.busy||t===0,onClick:()=>void s.moveSprint(e.id,"up"),children:"Monter"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Descendre ${e.name}`,disabled:s.busy||t===n,onClick:()=>void s.moveSprint(e.id,"down"),children:"Descendre"}),o.jsx(M,{size:"sm",variant:"ghost","aria-label":`Supprimer ${e.name}`,disabled:s.busy,className:"text-danger hover:text-danger",onClick:p,children:"Supprimer"})]})]})]})}function l4(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function o4({projects:e,openId:t,onOpen:n,onCreate:r,onRefresh:s}){const[i,l]=g.useState(""),[a,c]=g.useState(""),[u,h]=g.useState(!1),[d,f]=g.useState(null),p=i.trim().length>0&&a.trim().length>0&&!u;async function m(x){if(x.preventDefault(),!!p){h(!0),f(null);try{const w=await r(i.trim(),a.trim());l(""),c(""),n(w.id)}catch(w){f(l4(w))}finally{h(!1)}}}return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Projets"}),o.jsx(M,{variant:"ghost",size:"sm",onClick:s,children:"Rafraîchir"})]}),o.jsx(ke,{title:"Nouveau projet",children:o.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-col gap-2",children:[o.jsx(ie,{"aria-label":"Nom du projet",placeholder:"Nom du projet",value:i,onChange:x=>l(x.target.value)}),o.jsx(ie,{"aria-label":"Chemin du projet",placeholder:"/chemin/absolu/du/projet",value:a,onChange:x=>c(x.target.value)}),o.jsx("p",{className:"text-xs text-muted",children:"Saisir un chemin absolu accessible depuis le serveur IdeA."}),d&&o.jsx("p",{role:"alert",className:"text-xs text-danger",children:d}),o.jsx(M,{type:"submit",variant:"primary",disabled:!p,loading:u,children:"Créer le projet"})]})}),e===null?o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[o.jsx(Ie,{size:12})," Chargement des projets…"]}):e.length===0?o.jsx("p",{className:"text-sm text-muted",children:"Aucun projet."}):o.jsx("ul",{className:"flex flex-col gap-2","data-testid":"web-project-list",children:e.map(x=>o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>n(x.id),"aria-pressed":t===x.id,className:"flex w-full flex-col items-start rounded-md border border-border bg-raised px-3 py-2 text-left transition-colors hover:border-primary aria-pressed:border-primary",children:[o.jsx("span",{className:"text-sm font-medium text-content",children:x.name}),o.jsx("span",{className:"text-xs text-faint",children:x.root})]})},x.id))})]})}function f0({title:e,entries:t,note:n,onClose:r}){const s=g.useRef(null);return g.useEffect(()=>{s.current?.focus()},[]),g.useEffect(()=>{function i(l){l.key==="Escape"&&r()}return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[r]),o.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":e,style:{zIndex:Sn.floatingWindowNested},children:[o.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[o.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:e}),o.jsx(M,{ref:s,size:"sm",variant:"ghost",onClick:r,children:"Fermer"})]}),n&&o.jsx("p",{className:"shrink-0 border-b border-border px-4 py-2 text-xs text-muted",children:n}),o.jsx("ul",{className:"min-h-0 flex-1 overflow-auto px-2 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:t.map(i=>o.jsx("li",{children:o.jsxs("button",{type:"button",disabled:i.disabled,title:i.hint,"aria-current":i.active?"true":void 0,onClick:()=>{i.disabled||i.onSelect()},className:U("flex min-h-[44px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-50 disabled:hover:bg-transparent",i.active&&"bg-raised font-medium text-content"),children:[o.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-primary",children:i.active?"●":""}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:i.label}),i.secondaryLabel&&o.jsx("span",{className:"shrink-0 text-xs text-muted",children:i.secondaryLabel})]})},i.id))})]})}function ya(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const a4=["context","work","tickets","sprints","agents","templates","skills","permissions","memory","git","projects"],Jv={context:"Contexte projet",work:"Travail",tickets:"Tickets",sprints:"Sprints",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Mémoire",git:"Git",projects:"Projets"};function c4(){const{project:e}=ue(),[t,n]=g.useState(null),[r,s]=g.useState(null),[i,l]=g.useState(null),[a,c]=g.useState("projects"),[u,h]=g.useState(null),d=t?.find(x=>x.id===i)?.root??null,f=g.useCallback(async()=>{s(null);try{n(await e.listProjects())}catch(x){s(ya(x))}},[e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async x=>{s(null),l(null);try{await e.openProject(x),l(x),c("work")}catch(w){s(ya(w))}},[e]),m=g.useCallback(async(x,w)=>{s(null);try{const v=await e.createProject(x,w);return await f(),v}catch(v){throw s(ya(v)),v}},[e,f]);return o.jsxs("div",{"data-testid":"web-workspace",className:"flex h-full flex-col gap-4 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:[o.jsx(h4,{}),o.jsx(u4,{activePanel:a,hasProject:!!i,onSelect:c}),r&&o.jsx(ke,{className:"border-danger/40",children:o.jsx("p",{className:"text-sm text-danger",children:r})}),a==="projects"?o.jsx(o4,{projects:t,openId:i,onOpen:x=>void p(x),onCreate:m,onRefresh:()=>void f()}):i?o.jsx(d4,{panel:a,projectId:i,root:d,focusSprintId:u,onViewSprintTickets:x=>{h(x),c("tickets")}}):o.jsx("p",{className:"text-sm text-muted",children:"Ouvrir un projet pour utiliser ce panneau."})]})}function u4({activePanel:e,hasProject:t,onSelect:n}){const[r,s]=g.useState(!1);return o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>s(!0),children:["Panneaux : ",Jv[e]]}),r&&o.jsx(f0,{title:"Panneaux",note:t?void 0:"Ouvrir un projet pour utiliser ce panneau.",onClose:()=>s(!1),entries:a4.map(i=>{const l=i!=="projects"&&!t;return{id:i,label:Jv[i],active:i===e,disabled:l,hint:l?"Ouvrir un projet pour utiliser ce panneau.":void 0,onSelect:()=>{n(i),s(!1)}}})})]})}function d4({panel:e,projectId:t,root:n,focusSprintId:r,onViewSprintTickets:s}){switch(e){case"context":return o.jsx(a0,{projectId:t});case"work":return o.jsx(f4,{projectId:t,root:n});case"tickets":return o.jsx(r4,{projectId:t,focusSprintId:r});case"sprints":return o.jsx(s4,{projectId:t,onViewSprintTickets:s});case"agents":return o.jsx(_w,{projectId:t,projectRoot:n??""});case"templates":return o.jsx(WS,{projectId:t});case"skills":return o.jsx(HS,{projectId:t});case"permissions":return o.jsx(QS,{projectId:t});case"memory":return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(GS,{projectId:t}),o.jsx(VS,{})]});case"git":return o.jsx(Rw,{projectId:t})}}function h4(){return XB()!=="reconnecting"?null:o.jsxs("div",{role:"status","data-testid":"web-reconnect-banner",className:"flex items-center gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:[o.jsx(Ie,{size:12}),"Connexion perdue — reconnexion en cours…"]})}function f4({projectId:e,root:t}){const n=eo(e);YB(n.refresh);const[r,s]=g.useState(null),[i,l]=g.useState(0),a=g.useCallback(()=>l(f=>f+1),[]),c=n.state?.agents??[],[u,h]=g.useState(new Set);g.useEffect(()=>{const f=new Set(c.filter(p=>(p.backgroundTasks??[]).length>0).map(p=>p.agentId));h(p=>{const m=new Set([...p].filter(x=>f.has(x)));return m.size===p.size?p:m})},[c]);const d=g.useCallback(f=>{h(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return o.jsxs(ke,{className:"mt-2",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[o.jsxs("h3",{className:"text-sm font-semibold",children:["État live",o.jsx("span",{className:"ml-2 rounded bg-canvas px-1.5 py-0.5 text-[0.6rem] uppercase text-muted",children:"read-only"})]}),o.jsx(M,{variant:"ghost",size:"sm",loading:n.busy,onClick:()=>void n.refresh(),children:"Rafraîchir"})]}),n.error&&o.jsx("p",{role:"alert",className:"mb-2 text-xs text-danger",children:n.error}),n.busy&&n.state===null?o.jsx("p",{className:"text-xs text-muted",children:"Chargement de l'état…"}):c.length===0?o.jsx("p",{className:"text-xs text-muted",children:"Aucun agent actif."}):o.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"web-workstate",children:c.map(f=>o.jsx(p4,{agent:f,open:r===f.agentId,onToggleOpen:()=>{s(p=>p===f.agentId?null:f.agentId),a()},onRefresh:n.refresh,bgExpanded:u.has(f.agentId),onToggleBgExpanded:()=>d(f.agentId)},f.agentId))}),t&&r&&o.jsxs("div",{className:"mt-3",children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-muted",children:"Agent"}),o.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{s(null),a()},children:"Fermer"})]}),o.jsx(GB,{projectId:e,agentId:r,cwd:t,refitSignal:i},r)]})]})}function p4({agent:e,open:t,onToggleOpen:n,onRefresh:r,bgExpanded:s,onToggleBgExpanded:i}){const l=e.live!==void 0,a=e.busy?.state==="busy",c=[...e.inbox??[]].sort((h,d)=>h.createdAtMs-d.createdAtMs),u=[...e.backgroundTasks??[]].sort((h,d)=>d.updatedAtMs-h.updatedAtMs||h.taskId.localeCompare(d.taskId));return o.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between sm:gap-2",children:[o.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:e.name}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-xs",children:[o.jsx("span",{className:U("rounded-full px-2 py-0.5 font-medium",l?"bg-success/15 text-success":"bg-raised text-muted"),children:l?"Live":"Offline"}),o.jsx("span",{className:U("rounded-full px-2 py-0.5 font-medium",a?"bg-warning/15 text-warning":"bg-raised text-muted"),children:a?"Busy":"Idle"}),o.jsx(M,{variant:"ghost",size:"sm","aria-pressed":t,onClick:n,children:t?"Fermer":"Ouvrir"})]})]}),c.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),o.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:c.map(h=>o.jsxs("li",{className:"flex min-w-0 items-start gap-2 text-xs text-muted",children:[o.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium",children:h.kind}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:h.body})]},h.id))})]}),u.length>0&&o.jsxs("div",{className:"mt-2",children:[o.jsxs("button",{type:"button","aria-expanded":s,"aria-controls":`web-bg-tasks-${e.agentId}`,"aria-label":s?`Masquer les background tasks de ${e.name}`:`Afficher les background tasks de ${e.name}`,onClick:i,className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-faint hover:text-muted",children:[o.jsx("span",{"aria-hidden":"true",children:s?"▾":"▸"}),"Background tasks",o.jsx("span",{className:"rounded-full bg-raised px-1.5 py-0.5 font-medium normal-case tracking-normal text-muted",children:u.length})]}),s&&o.jsx("ul",{id:`web-bg-tasks-${e.agentId}`,"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:u.map(h=>o.jsx(x4,{task:h,onRefresh:r},h.taskId))})]})]})}const m4={running:"Running",completed:"Completed",failed:"Failed",cancelled:"Cancelled",pending:"Pending",delivered:"Delivered"};function g4(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function x4({task:e,onRefresh:t}){const{workState:n}=ue(),[r,s]=g.useState(!1),[i,l]=g.useState(null),a=e.status==="running"||e.status==="pending",c=e.status==="failed"||e.status==="cancelled";async function u(h){s(!0),l(null);try{await h(e.taskId),await t()}catch(d){l(ya(d))}finally{s(!1)}}return o.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:U("shrink-0 rounded-full px-1.5 py-0.5 font-medium",g4(e.status)),children:m4[e.status]}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:e.kind})]}),o.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-1",children:[o.jsx(M,{size:"sm",variant:"ghost",disabled:!a||r,loading:r,onClick:()=>void u(h=>n.cancelBackgroundTask(h)),children:"Cancel"}),o.jsx(M,{size:"sm",variant:"ghost",disabled:!c||r,loading:r,onClick:()=>void u(h=>n.retryBackgroundTask(h)),children:"Retry"})]})]}),i&&o.jsx("p",{role:"alert",className:"mt-1 text-danger",children:i})]})}const Xo={aiProfiles:"Profils IA",devices:"Appareils"};function v4({session:e}={}){const t=e??dw(),[n,r]=g.useState(()=>t.isPaired()),[s,i]=g.useState(!1),[l,a]=g.useState(null),[c,u]=g.useState(!1);g.useEffect(()=>t.onUnauthorized(()=>{a(null),u(!1),r(!1)}),[t]);async function h(){if(!s){i(!0);try{await t.logout()}finally{cx(),i(!1),a(null),u(!1),r(!1)}}}const d=g.useCallback(()=>{t.forget(),cx(),a(null),u(!1),r(!1)},[t]);return o.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[o.jsxs("header",{"data-testid":"web-header",className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:px-6",children:[o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("h1",{className:"text-base font-semibold tracking-tight sm:text-lg",children:"IdeA"}),o.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"web"})]}),n&&o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(M,{variant:"ghost",size:"sm","aria-pressed":c,onClick:()=>u(!0),children:"Paramètres"}),o.jsx(M,{variant:"ghost",size:"sm",loading:s,onClick:()=>void h(),children:"Se déconnecter"})]})]}),o.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:n?l==="aiProfiles"?o.jsx(Zv,{title:Xo.aiProfiles,onBack:()=>a(null),children:o.jsx(Nw,{})}):l==="devices"?o.jsx(Zv,{title:Xo.devices,onBack:()=>a(null),children:o.jsx(Aw,{onSessionEnded:d})}):o.jsx(c4,{}):o.jsx(qB,{session:t,onPaired:()=>r(!0)})}),c&&o.jsx(f0,{title:"Paramètres",onClose:()=>u(!1),entries:[{id:"aiProfiles",label:Xo.aiProfiles,active:l==="aiProfiles",onSelect:()=>{a("aiProfiles"),u(!1)}},{id:"devices",label:Xo.devices,active:l==="devices",onSelect:()=>{a("devices"),u(!1)}},{id:"deployment",label:"Déploiement",active:!1,disabled:!0,secondaryLabel:"Desktop uniquement",hint:"Desktop uniquement",onSelect:()=>{}}]})]})}function Zv({title:e,onBack:t,children:n}){return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2 pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))]",children:[o.jsx(M,{variant:"ghost",size:"sm",onClick:t,children:"← Retour"}),o.jsx("span",{className:"text-sm font-medium text-content",children:e})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:o.jsx("div",{className:"mx-auto w-full max-w-xl",children:n})})]})}const p0=document.getElementById("root");if(!p0)throw new Error("missing #root element");const ey=WB(window.location.search);window.__IDEA_TRANSPORT__="http";const y4=fw()==="http";ld.createRoot(p0).render(o.jsx(L0.StrictMode,{children:o.jsx(mP,{children:y4?o.jsx(v4,{}):ey?o.jsx(HB,{panel:ey.panel}):o.jsx(zB,{})})})); diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-DmWi2DoV.js b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-DmWi2DoV.js deleted file mode 100644 index 430d736..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-DmWi2DoV.js +++ /dev/null @@ -1,128 +0,0 @@ -var h0=Object.defineProperty;var f0=(e,t,n)=>t in e?h0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var X=(e,t,n)=>f0(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const l of s.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var vo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ef(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jv={exports:{}},sc={},Zv={exports:{}},be={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ql=Symbol.for("react.element"),p0=Symbol.for("react.portal"),m0=Symbol.for("react.fragment"),g0=Symbol.for("react.strict_mode"),x0=Symbol.for("react.profiler"),v0=Symbol.for("react.provider"),_0=Symbol.for("react.context"),y0=Symbol.for("react.forward_ref"),b0=Symbol.for("react.suspense"),w0=Symbol.for("react.memo"),S0=Symbol.for("react.lazy"),Wp=Symbol.iterator;function k0(e){return e===null||typeof e!="object"?null:(e=Wp&&e[Wp]||e["@@iterator"],typeof e=="function"?e:null)}var e_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},t_=Object.assign,n_={};function _s(e,t,n){this.props=e,this.context=t,this.refs=n_,this.updater=n||e_}_s.prototype.isReactComponent={};_s.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};_s.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function r_(){}r_.prototype=_s.prototype;function tf(e,t,n){this.props=e,this.context=t,this.refs=n_,this.updater=n||e_}var nf=tf.prototype=new r_;nf.constructor=tf;t_(nf,_s.prototype);nf.isPureReactComponent=!0;var Hp=Array.isArray,i_=Object.prototype.hasOwnProperty,rf={current:null},s_={key:!0,ref:!0,__self:!0,__source:!0};function l_(e,t,n){var r,i={},s=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(s=""+t.key),t)i_.call(t,r)&&!s_.hasOwnProperty(r)&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1>>1,V=E[re];if(0>>1;rei(ee,j))Ji(W,ee)?(E[re]=W,E[J]=j,re=J):(E[re]=ee,E[ie]=j,re=ie);else if(Ji(W,j))E[re]=W,E[J]=j,re=J;else break e}}return z}function i(E,z){var j=E.sortIndex-z.sortIndex;return j!==0?j:E.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var l=Date,o=l.now();e.unstable_now=function(){return l.now()-o}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,x=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(E){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=E)r(u),z.sortIndex=z.expirationTime,t(c,z);else break;z=n(u)}}function b(E){if(x=!1,y(E),!m)if(n(c)!==null)m=!0,U(C);else{var z=n(u);z!==null&&G(b,z.startTime-E)}}function C(E,z){m=!1,x&&(x=!1,v(R),R=-1),p=!0;var j=f;try{for(y(z),d=n(c);d!==null&&(!(d.expirationTime>z)||E&&!T());){var re=d.callback;if(typeof re=="function"){d.callback=null,f=d.priorityLevel;var V=re(d.expirationTime<=z);z=e.unstable_now(),typeof V=="function"?d.callback=V:d===n(c)&&r(c),y(z)}else r(c);d=n(c)}if(d!==null)var A=!0;else{var ie=n(u);ie!==null&&G(b,ie.startTime-z),A=!1}return A}finally{d=null,f=j,p=!1}}var k=!1,N=null,R=-1,L=5,S=-1;function T(){return!(e.unstable_now()-SE||125re?(E.sortIndex=j,t(u,E),n(c)===null&&E===n(u)&&(x?(v(R),R=-1):x=!0,G(b,j-re))):(E.sortIndex=V,t(c,E),m||p||(m=!0,U(C))),E},e.unstable_shouldYield=T,e.unstable_wrapCallback=function(E){var z=f;return function(){var j=f;f=z;try{return E.apply(this,arguments)}finally{f=j}}}})(d_);u_.exports=d_;var I0=u_.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var O0=g,on=I0;function Q(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rd=Object.prototype.hasOwnProperty,B0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,qp={},Vp={};function z0(e){return rd.call(Vp,e)?!0:rd.call(qp,e)?!1:B0.test(e)?Vp[e]=!0:(qp[e]=!0,!1)}function F0(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $0(e,t,n,r){if(t===null||typeof t>"u"||F0(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function zt(e,t,n,r,i,s,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=l}var St={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){St[e]=new zt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];St[t]=new zt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){St[e]=new zt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){St[e]=new zt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){St[e]=new zt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){St[e]=new zt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){St[e]=new zt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){St[e]=new zt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){St[e]=new zt(e,5,!1,e.toLowerCase(),null,!1,!1)});var lf=/[\-:]([a-z])/g;function af(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(lf,af);St[t]=new zt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(lf,af);St[t]=new zt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(lf,af);St[t]=new zt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){St[e]=new zt(e,1,!1,e.toLowerCase(),null,!1,!1)});St.xlinkHref=new zt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){St[e]=new zt(e,1,!1,e.toLowerCase(),null,!0,!0)});function of(e,t,n,r){var i=St.hasOwnProperty(t)?St[t]:null;(i!==null?i.type!==0:r||!(2o||i[l]!==s[o]){var c=` -`+i[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=o);break}}}finally{Oc=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?el(e):""}function W0(e){switch(e.tag){case 5:return el(e.type);case 16:return el("Lazy");case 13:return el("Suspense");case 19:return el("SuspenseList");case 0:case 2:case 15:return e=Bc(e.type,!1),e;case 11:return e=Bc(e.type.render,!1),e;case 1:return e=Bc(e.type,!0),e;default:return""}}function ad(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ui:return"Fragment";case Hi:return"Portal";case id:return"Profiler";case cf:return"StrictMode";case sd:return"Suspense";case ld:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case p_:return(e.displayName||"Context")+".Consumer";case f_:return(e._context.displayName||"Context")+".Provider";case uf:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case df:return t=e.displayName||null,t!==null?t:ad(e.type)||"Memo";case Cr:t=e._payload,e=e._init;try{return ad(e(t))}catch{}}return null}function H0(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ad(t);case 8:return t===cf?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ur(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function g_(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function U0(e){var t=g_(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(l){r=""+l,s.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ca(e){e._valueTracker||(e._valueTracker=U0(e))}function x_(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=g_(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _o(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function od(e,t){var n=t.checked;return Ke({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Gp(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ur(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function v_(e,t){t=t.checked,t!=null&&of(e,"checked",t,!1)}function cd(e,t){v_(e,t);var n=Ur(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ud(e,t.type,n):t.hasOwnProperty("defaultValue")&&ud(e,t.type,Ur(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Yp(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ud(e,t,n){(t!=="number"||_o(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var tl=Array.isArray;function ns(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=ua.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sl(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var cl={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},q0=["Webkit","ms","Moz","O"];Object.keys(cl).forEach(function(e){q0.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),cl[t]=cl[e]})});function w_(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||cl.hasOwnProperty(e)&&cl[e]?(""+t).trim():t+"px"}function S_(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=w_(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var V0=Ke({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function fd(e,t){if(t){if(V0[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Q(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Q(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Q(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Q(62))}}function pd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var md=null;function hf(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var gd=null,rs=null,is=null;function Jp(e){if(e=Gl(e)){if(typeof gd!="function")throw Error(Q(280));var t=e.stateNode;t&&(t=uc(t),gd(e.stateNode,e.type,t))}}function k_(e){rs?is?is.push(e):is=[e]:rs=e}function C_(){if(rs){var e=rs,t=is;if(is=rs=null,Jp(e),t)for(e=0;e>>=0,e===0?32:31-(rk(e)/ik|0)|0}var da=64,ha=4194304;function nl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function So(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,l=n&268435455;if(l!==0){var o=l&~i;o!==0?r=nl(o):(s&=l,s!==0&&(r=nl(s)))}else l=n&~i,l!==0?r=nl(l):s!==0&&(r=nl(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,s=t&-t,i>=s||i===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Vl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-An(t),e[t]=n}function ok(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=dl),am=" ",om=!1;function q_(e,t){switch(e){case"keyup":return Ik.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function V_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var qi=!1;function Bk(e,t){switch(e){case"compositionend":return V_(t);case"keypress":return t.which!==32?null:(om=!0,am);case"textInput":return e=t.data,e===am&&om?null:e;default:return null}}function zk(e,t){if(qi)return e==="compositionend"||!yf&&q_(e,t)?(e=H_(),Qa=xf=Lr=null,qi=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=hm(n)}}function X_(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?X_(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Q_(){for(var e=window,t=_o();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_o(e.document)}return t}function bf(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Gk(e){var t=Q_(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&X_(n.ownerDocument.documentElement,n)){if(r!==null&&bf(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=fm(n,s);var l=fm(n,r);i&&l&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Vi=null,wd=null,fl=null,Sd=!1;function pm(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Sd||Vi==null||Vi!==_o(r)||(r=Vi,"selectionStart"in r&&bf(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),fl&&Pl(fl,r)||(fl=r,r=jo(wd,"onSelect"),0Yi||(e.current=Pd[Yi],Pd[Yi]=null,Yi--)}function Me(e,t){Yi++,Pd[Yi]=e.current,e.current=t}var qr={},Tt=Kr(qr),Gt=Kr(!1),xi=qr;function us(e,t){var n=e.type.contextTypes;if(!n)return qr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Yt(e){return e=e.childContextTypes,e!=null}function Eo(){ze(Gt),ze(Tt)}function bm(e,t,n){if(Tt.current!==qr)throw Error(Q(168));Me(Tt,t),Me(Gt,n)}function ly(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(Q(108,H0(e)||"Unknown",i));return Ke({},n,r)}function Po(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||qr,xi=Tt.current,Me(Tt,e),Me(Gt,Gt.current),!0}function wm(e,t,n){var r=e.stateNode;if(!r)throw Error(Q(169));n?(e=ly(e,t,xi),r.__reactInternalMemoizedMergedChildContext=e,ze(Gt),ze(Tt),Me(Tt,e)):ze(Gt),Me(Gt,n)}var rr=null,dc=!1,Jc=!1;function ay(e){rr===null?rr=[e]:rr.push(e)}function l1(e){dc=!0,ay(e)}function Gr(){if(!Jc&&rr!==null){Jc=!0;var e=0,t=Ee;try{var n=rr;for(Ee=1;e>=l,i-=l,sr=1<<32-An(t)+i|n<R?(L=N,N=null):L=N.sibling;var S=f(v,N,y[R],b);if(S===null){N===null&&(N=L);break}e&&N&&S.alternate===null&&t(v,N),_=s(S,_,R),k===null?C=S:k.sibling=S,k=S,N=L}if(R===y.length)return n(v,N),Fe&&ni(v,R),C;if(N===null){for(;RR?(L=N,N=null):L=N.sibling;var T=f(v,N,S.value,b);if(T===null){N===null&&(N=L);break}e&&N&&T.alternate===null&&t(v,N),_=s(T,_,R),k===null?C=T:k.sibling=T,k=T,N=L}if(S.done)return n(v,N),Fe&&ni(v,R),C;if(N===null){for(;!S.done;R++,S=y.next())S=d(v,S.value,b),S!==null&&(_=s(S,_,R),k===null?C=S:k.sibling=S,k=S);return Fe&&ni(v,R),C}for(N=r(v,N);!S.done;R++,S=y.next())S=p(N,v,R,S.value,b),S!==null&&(e&&S.alternate!==null&&N.delete(S.key===null?R:S.key),_=s(S,_,R),k===null?C=S:k.sibling=S,k=S);return e&&N.forEach(function(D){return t(v,D)}),Fe&&ni(v,R),C}function w(v,_,y,b){if(typeof y=="object"&&y!==null&&y.type===Ui&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case oa:e:{for(var C=y.key,k=_;k!==null;){if(k.key===C){if(C=y.type,C===Ui){if(k.tag===7){n(v,k.sibling),_=i(k,y.props.children),_.return=v,v=_;break e}}else if(k.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===Cr&&Cm(C)===k.type){n(v,k.sibling),_=i(k,y.props),_.ref=Rs(v,k,y),_.return=v,v=_;break e}n(v,k);break}else t(v,k);k=k.sibling}y.type===Ui?(_=fi(y.props.children,v.mode,b,y.key),_.return=v,v=_):(b=so(y.type,y.key,y.props,null,v.mode,b),b.ref=Rs(v,_,y),b.return=v,v=b)}return l(v);case Hi:e:{for(k=y.key;_!==null;){if(_.key===k)if(_.tag===4&&_.stateNode.containerInfo===y.containerInfo&&_.stateNode.implementation===y.implementation){n(v,_.sibling),_=i(_,y.children||[]),_.return=v,v=_;break e}else{n(v,_);break}else t(v,_);_=_.sibling}_=lu(y,v.mode,b),_.return=v,v=_}return l(v);case Cr:return k=y._init,w(v,_,k(y._payload),b)}if(tl(y))return m(v,_,y,b);if(Ps(y))return x(v,_,y,b);_a(v,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,_!==null&&_.tag===6?(n(v,_.sibling),_=i(_,y),_.return=v,v=_):(n(v,_),_=su(y,v.mode,b),_.return=v,v=_),l(v)):n(v,_)}return w}var hs=dy(!0),hy=dy(!1),Lo=Kr(null),Do=null,Ji=null,Cf=null;function jf(){Cf=Ji=Do=null}function Nf(e){var t=Lo.current;ze(Lo),e._currentValue=t}function Ld(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ls(e,t){Do=e,Cf=Ji=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Kt=!0),e.firstContext=null)}function wn(e){var t=e._currentValue;if(Cf!==e)if(e={context:e,memoizedValue:t,next:null},Ji===null){if(Do===null)throw Error(Q(308));Ji=e,Do.dependencies={lanes:0,firstContext:e}}else Ji=Ji.next=e;return t}var ci=null;function Ef(e){ci===null?ci=[e]:ci.push(e)}function fy(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Ef(t)):(n.next=i.next,i.next=n),t.interleaved=n,hr(e,r)}function hr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var jr=!1;function Pf(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function py(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function or(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function zr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ce&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,hr(e,n)}return i=r.interleaved,i===null?(t.next=t,Ef(r)):(t.next=i.next,i.next=t),r.interleaved=t,hr(e,n)}function Za(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pf(e,n)}}function jm(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=l:s=s.next=l,n=n.next}while(n!==null);s===null?i=s=t:s=s.next=t}else i=s=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ro(e,t,n,r){var i=e.updateQueue;jr=!1;var s=i.firstBaseUpdate,l=i.lastBaseUpdate,o=i.shared.pending;if(o!==null){i.shared.pending=null;var c=o,u=c.next;c.next=null,l===null?s=u:l.next=u,l=c;var h=e.alternate;h!==null&&(h=h.updateQueue,o=h.lastBaseUpdate,o!==l&&(o===null?h.firstBaseUpdate=u:o.next=u,h.lastBaseUpdate=c))}if(s!==null){var d=i.baseState;l=0,h=u=c=null,o=s;do{var f=o.lane,p=o.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var m=e,x=o;switch(f=t,p=n,x.tag){case 1:if(m=x.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=x.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Ke({},d,f);break e;case 2:jr=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,f=i.effects,f===null?i.effects=[o]:f.push(o))}else p={eventTime:p,lane:f,tag:o.tag,payload:o.payload,callback:o.callback,next:null},h===null?(u=h=p,c=d):h=h.next=p,l|=f;if(o=o.next,o===null){if(o=i.shared.pending,o===null)break;f=o,o=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(h===null&&(c=d),i.baseState=c,i.firstBaseUpdate=u,i.lastBaseUpdate=h,t=i.shared.interleaved,t!==null){i=t;do l|=i.lane,i=i.next;while(i!==t)}else s===null&&(i.shared.lanes=0);yi|=l,e.lanes=l,e.memoizedState=d}}function Nm(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=eu.transition;eu.transition={};try{e(!1),t()}finally{Ee=n,eu.transition=r}}function Ty(){return Sn().memoizedState}function u1(e,t,n){var r=$r(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ly(e))Dy(t,n);else if(n=fy(e,t,n,r),n!==null){var i=Ot();Tn(n,e,r,i),Ry(n,t,r)}}function d1(e,t,n){var r=$r(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ly(e))Dy(t,i);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var l=t.lastRenderedState,o=s(l,n);if(i.hasEagerState=!0,i.eagerState=o,Rn(o,l)){var c=t.interleaved;c===null?(i.next=i,Ef(t)):(i.next=c.next,c.next=i),t.interleaved=i;return}}catch{}finally{}n=fy(e,t,i,r),n!==null&&(i=Ot(),Tn(n,e,r,i),Ry(n,t,r))}}function Ly(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function Dy(e,t){pl=Io=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ry(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pf(e,n)}}var Oo={readContext:wn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},h1={readContext:wn,useCallback:function(e,t){return Fn().memoizedState=[e,t===void 0?null:t],e},useContext:wn,useEffect:Pm,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,to(4194308,4,jy.bind(null,t,e),n)},useLayoutEffect:function(e,t){return to(4194308,4,e,t)},useInsertionEffect:function(e,t){return to(4,2,e,t)},useMemo:function(e,t){var n=Fn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=u1.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Fn();return e={current:e},t.memoizedState=e},useState:Em,useDebugValue:Of,useDeferredValue:function(e){return Fn().memoizedState=e},useTransition:function(){var e=Em(!1),t=e[0];return e=c1.bind(null,e[1]),Fn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,i=Fn();if(Fe){if(n===void 0)throw Error(Q(407));n=n()}else{if(n=t(),xt===null)throw Error(Q(349));_i&30||vy(r,t,n)}i.memoizedState=n;var s={value:n,getSnapshot:t};return i.queue=s,Pm(yy.bind(null,r,s,e),[e]),r.flags|=2048,Ol(9,_y.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=Fn(),t=xt.identifierPrefix;if(Fe){var n=lr,r=sr;n=(r&~(1<<32-An(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ml++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[Wn]=t,e[Ll]=r,Uy(e,t,!1,!1),t.stateNode=e;e:{switch(l=pd(n,r),n){case"dialog":Oe("cancel",e),Oe("close",e),i=r;break;case"iframe":case"object":case"embed":Oe("load",e),i=r;break;case"video":case"audio":for(i=0;ims&&(t.flags|=128,r=!0,Ms(s,!1),t.lanes=4194304)}else{if(!r)if(e=Mo(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ms(s,!0),s.tail===null&&s.tailMode==="hidden"&&!l.alternate&&!Fe)return Ct(t),null}else 2*et()-s.renderingStartTime>ms&&n!==1073741824&&(t.flags|=128,r=!0,Ms(s,!1),t.lanes=4194304);s.isBackwards?(l.sibling=t.child,t.child=l):(n=s.last,n!==null?n.sibling=l:t.child=l,s.last=l)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=et(),t.sibling=null,n=Ue.current,Me(Ue,r?n&1|2:n&1),t):(Ct(t),null);case 22:case 23:return Hf(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?rn&1073741824&&(Ct(t),t.subtreeFlags&6&&(t.flags|=8192)):Ct(t),null;case 24:return null;case 25:return null}throw Error(Q(156,t.tag))}function y1(e,t){switch(Sf(t),t.tag){case 1:return Yt(t.type)&&Eo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return fs(),ze(Gt),ze(Tt),Lf(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tf(t),null;case 13:if(ze(Ue),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Q(340));ds()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ze(Ue),null;case 4:return fs(),null;case 10:return Nf(t.type._context),null;case 22:case 23:return Hf(),null;case 24:return null;default:return null}}var ba=!1,Pt=!1,b1=typeof WeakSet=="function"?WeakSet:Set,oe=null;function Zi(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ye(e,t,r)}else n.current=null}function $d(e,t,n){try{n()}catch(r){Ye(e,t,r)}}var Fm=!1;function w1(e,t){if(kd=ko,e=Q_(),bf(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||i!==0&&d.nodeType!==3||(o=l+i),d!==s||r!==0&&d.nodeType!==3||(c=l+r),d.nodeType===3&&(l+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===i&&(o=l),f===s&&++h===r&&(c=l),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Cd={focusedElem:e,selectionRange:n},ko=!1,oe=t;oe!==null;)if(t=oe,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,oe=e;else for(;oe!==null;){t=oe;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var x=m.memoizedProps,w=m.memoizedState,v=t.stateNode,_=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:Nn(t.type,x),w);v.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Q(163))}}catch(b){Ye(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,oe=e;break}oe=t.return}return m=Fm,Fm=!1,m}function ml(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,s!==void 0&&$d(t,n,s)}i=i.next}while(i!==r)}}function pc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Wd(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ky(e){var t=e.alternate;t!==null&&(e.alternate=null,Ky(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Wn],delete t[Ll],delete t[Ed],delete t[i1],delete t[s1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Gy(e){return e.tag===5||e.tag===3||e.tag===4}function $m(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Gy(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Hd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=No));else if(r!==4&&(e=e.child,e!==null))for(Hd(e,t,n),e=e.sibling;e!==null;)Hd(e,t,n),e=e.sibling}function Ud(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ud(e,t,n),e=e.sibling;e!==null;)Ud(e,t,n),e=e.sibling}var yt=null,En=!1;function _r(e,t,n){for(n=n.child;n!==null;)Yy(e,t,n),n=n.sibling}function Yy(e,t,n){if(qn&&typeof qn.onCommitFiberUnmount=="function")try{qn.onCommitFiberUnmount(lc,n)}catch{}switch(n.tag){case 5:Pt||Zi(n,t);case 6:var r=yt,i=En;yt=null,_r(e,t,n),yt=r,En=i,yt!==null&&(En?(e=yt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):yt.removeChild(n.stateNode));break;case 18:yt!==null&&(En?(e=yt,n=n.stateNode,e.nodeType===8?Qc(e.parentNode,n):e.nodeType===1&&Qc(e,n),Nl(e)):Qc(yt,n.stateNode));break;case 4:r=yt,i=En,yt=n.stateNode.containerInfo,En=!0,_r(e,t,n),yt=r,En=i;break;case 0:case 11:case 14:case 15:if(!Pt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,l=s.destroy;s=s.tag,l!==void 0&&(s&2||s&4)&&$d(n,t,l),i=i.next}while(i!==r)}_r(e,t,n);break;case 1:if(!Pt&&(Zi(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Ye(n,t,o)}_r(e,t,n);break;case 21:_r(e,t,n);break;case 22:n.mode&1?(Pt=(r=Pt)||n.memoizedState!==null,_r(e,t,n),Pt=r):_r(e,t,n);break;default:_r(e,t,n)}}function Wm(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new b1),t.forEach(function(r){var i=T1.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function jn(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=l),r&=~s}if(r=i,r=et()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*k1(r/1960))-r,10e?16:e,Dr===null)var r=!1;else{if(e=Dr,Dr=null,Fo=0,Ce&6)throw Error(Q(331));var i=Ce;for(Ce|=4,oe=e.current;oe!==null;){var s=oe,l=s.child;if(oe.flags&16){var o=s.deletions;if(o!==null){for(var c=0;cet()-$f?hi(e,0):Ff|=n),Xt(e,t)}function rb(e,t){t===0&&(e.mode&1?(t=ha,ha<<=1,!(ha&130023424)&&(ha=4194304)):t=1);var n=Ot();e=hr(e,t),e!==null&&(Vl(e,t,n),Xt(e,n))}function A1(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),rb(e,n)}function T1(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Q(314))}r!==null&&r.delete(t),rb(e,n)}var ib;ib=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Gt.current)Kt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Kt=!1,v1(e,t,n);Kt=!!(e.flags&131072)}else Kt=!1,Fe&&t.flags&1048576&&oy(t,To,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;no(e,t),e=t.pendingProps;var i=us(t,Tt.current);ls(t,n),i=Rf(null,t,r,e,i,n);var s=Mf();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Yt(r)?(s=!0,Po(t)):s=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Pf(t),i.updater=fc,t.stateNode=i,i._reactInternals=t,Rd(t,r,e,n),t=Od(null,t,r,!0,s,n)):(t.tag=0,Fe&&s&&wf(t),Mt(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(no(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=D1(r),e=Nn(r,e),i){case 0:t=Id(null,t,r,e,n);break e;case 1:t=Om(null,t,r,e,n);break e;case 11:t=Mm(null,t,r,e,n);break e;case 14:t=Im(null,t,r,Nn(r.type,e),n);break e}throw Error(Q(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),Id(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),Om(e,t,r,i,n);case 3:e:{if($y(t),e===null)throw Error(Q(387));r=t.pendingProps,s=t.memoizedState,i=s.element,py(e,t),Ro(t,r,null,n);var l=t.memoizedState;if(r=l.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){i=ps(Error(Q(423)),t),t=Bm(e,t,r,n,i);break e}else if(r!==i){i=ps(Error(Q(424)),t),t=Bm(e,t,r,n,i);break e}else for(sn=Br(t.stateNode.containerInfo.firstChild),ln=t,Fe=!0,Pn=null,n=hy(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ds(),r===i){t=fr(e,t,n);break e}Mt(e,t,r,n)}t=t.child}return t;case 5:return my(t),e===null&&Td(t),r=t.type,i=t.pendingProps,s=e!==null?e.memoizedProps:null,l=i.children,jd(r,i)?l=null:s!==null&&jd(r,s)&&(t.flags|=32),Fy(e,t),Mt(e,t,l,n),t.child;case 6:return e===null&&Td(t),null;case 13:return Wy(e,t,n);case 4:return Af(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=hs(t,null,r,n):Mt(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),Mm(e,t,r,i,n);case 7:return Mt(e,t,t.pendingProps,n),t.child;case 8:return Mt(e,t,t.pendingProps.children,n),t.child;case 12:return Mt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,s=t.memoizedProps,l=i.value,Me(Lo,r._currentValue),r._currentValue=l,s!==null)if(Rn(s.value,l)){if(s.children===i.children&&!Gt.current){t=fr(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var o=s.dependencies;if(o!==null){l=s.child;for(var c=o.firstContext;c!==null;){if(c.context===r){if(s.tag===1){c=or(-1,n&-n),c.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),Ld(s.return,n,t),o.lanes|=n;break}c=c.next}}else if(s.tag===10)l=s.type===t.type?null:s.child;else if(s.tag===18){if(l=s.return,l===null)throw Error(Q(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),Ld(l,n,t),l=s.sibling}else l=s.child;if(l!==null)l.return=s;else for(l=s;l!==null;){if(l===t){l=null;break}if(s=l.sibling,s!==null){s.return=l.return,l=s;break}l=l.return}s=l}Mt(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,ls(t,n),i=wn(i),r=r(i),t.flags|=1,Mt(e,t,r,n),t.child;case 14:return r=t.type,i=Nn(r,t.pendingProps),i=Nn(r.type,i),Im(e,t,r,i,n);case 15:return By(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),no(e,t),t.tag=1,Yt(r)?(e=!0,Po(t)):e=!1,ls(t,n),My(t,r,i),Rd(t,r,i,n),Od(null,t,r,!0,e,n);case 19:return Hy(e,t,n);case 22:return zy(e,t,n)}throw Error(Q(156,t.tag))};function sb(e,t){return L_(e,t)}function L1(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function _n(e,t,n,r){return new L1(e,t,n,r)}function qf(e){return e=e.prototype,!(!e||!e.isReactComponent)}function D1(e){if(typeof e=="function")return qf(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uf)return 11;if(e===df)return 14}return 2}function Wr(e,t){var n=e.alternate;return n===null?(n=_n(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function so(e,t,n,r,i,s){var l=2;if(r=e,typeof e=="function")qf(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case Ui:return fi(n.children,i,s,t);case cf:l=8,i|=8;break;case id:return e=_n(12,n,t,i|2),e.elementType=id,e.lanes=s,e;case sd:return e=_n(13,n,t,i),e.elementType=sd,e.lanes=s,e;case ld:return e=_n(19,n,t,i),e.elementType=ld,e.lanes=s,e;case m_:return gc(n,i,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case f_:l=10;break e;case p_:l=9;break e;case uf:l=11;break e;case df:l=14;break e;case Cr:l=16,r=null;break e}throw Error(Q(130,e==null?e:typeof e,""))}return t=_n(l,n,t,i),t.elementType=e,t.type=r,t.lanes=s,t}function fi(e,t,n,r){return e=_n(7,e,r,t),e.lanes=n,e}function gc(e,t,n,r){return e=_n(22,e,r,t),e.elementType=m_,e.lanes=n,e.stateNode={isHidden:!1},e}function su(e,t,n){return e=_n(6,e,null,t),e.lanes=n,e}function lu(e,t,n){return t=_n(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function R1(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Fc(0),this.expirationTimes=Fc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Fc(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Vf(e,t,n,r,i,s,l,o,c){return e=new R1(e,t,n,o,c),t===1?(t=1,s===!0&&(t|=8)):t=0,s=_n(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Pf(s),e}function M1(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(cb)}catch(e){console.error(e)}}cb(),c_.exports=cn;var F1=c_.exports,Xm=F1;nd.createRoot=Xm.createRoot,nd.hydrateRoot=Xm.hydrateRoot;/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var ub=Object.defineProperty,$1=Object.getOwnPropertyDescriptor,W1=(e,t)=>{for(var n in t)ub(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,r)=>{for(var i=r>1?void 0:r?$1(t,n):t,s=e.length-1,l;s>=0;s--)(l=e[s])&&(i=(r?l(t,n,i):l(i))||i);return r&&i&&ub(t,n,i),i},se=(e,t)=>(n,r)=>t(n,r,e),Qm="Terminal input",Yd={get:()=>Qm,set:e=>Qm=e},Jm="Too much output to announce, navigate to rows manually to read",Xd={get:()=>Jm,set:e=>Jm=e};function H1(e){return e.replace(/\r?\n/g,"\r")}function U1(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function q1(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function V1(e,t,n,r){if(e.stopPropagation(),e.clipboardData){let i=e.clipboardData.getData("text/plain");db(i,t,n,r)}}function db(e,t,n,r){e=H1(e),e=U1(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function hb(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,s=e.clientY-r.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${i}px`,t.style.top=`${s}px`,t.style.zIndex="1000",t.focus()}function Zm(e,t,n,r,i){hb(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Nr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function bc(e,t=0,n=e.length){let r="";for(let i=t;i65535?(s-=65536,r+=String.fromCharCode((s>>10)+55296)+String.fromCharCode(s%1024+56320)):r+=String.fromCharCode(s)}return r}var K1=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let s=e.charCodeAt(i++);56320<=s&&s<=57343?t[r++]=(this._interim-55296)*1024+s-56320+65536:(t[r++]=this._interim,t[r++]=s),this._interim=0}for(let s=i;s=n)return this._interim=l,r;let o=e.charCodeAt(s);56320<=o&&o<=57343?t[r++]=(l-55296)*1024+o-56320+65536:(t[r++]=l,t[r++]=o);continue}l!==65279&&(t[r++]=l)}return r}},G1=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,s,l,o,c=0,u=0;if(this.interim[0]){let f=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,x;for(;(x=this.interim[++m]&63)&&m<4;)p<<=6,p|=x;let w=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,v=w-m;for(;u=n)return 0;if(x=e[u++],(x&192)!==128){u--,f=!0;break}else this.interim[m++]=x,p<<=6,p|=x&63}f||(w===2?p<128?u--:t[r++]=p:w===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let h=n-4,d=u;for(;d=n)return this.interim[0]=i,r;if(s=e[d++],(s&192)!==128){d--;continue}if(c=(i&31)<<6|s&63,c<128){d--;continue}t[r++]=c}else if((i&240)===224){if(d>=n)return this.interim[0]=i,r;if(s=e[d++],(s&192)!==128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=s,r;if(l=e[d++],(l&192)!==128){d--;continue}if(c=(i&15)<<12|(s&63)<<6|l&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)===240){if(d>=n)return this.interim[0]=i,r;if(s=e[d++],(s&192)!==128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=s,r;if(l=e[d++],(l&192)!==128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=s,this.interim[2]=l,r;if(o=e[d++],(o&192)!==128){d--;continue}if(c=(i&7)<<18|(s&63)<<12|(l&63)<<6|o&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},fb="",Rr=" ",Xl=class pb{constructor(){this.fg=0,this.bg=0,this.extended=new Ho}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new pb;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Ho=class mb{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new mb(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},bn=class gb extends Xl{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Ho,this.combinedData=""}static fromCharData(t){let n=new gb;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Nr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let i=t[1].charCodeAt(1);56320<=i&&i<=57343?this.content=(r-55296)*1024+i-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},eg="di$target",Qd="di$dependencies",au=new Map;function Y1(e){return e[Qd]||[]}function vt(e){if(au.has(e))return au.get(e);let t=function(n,r,i){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");X1(t,n,i)};return t._id=e,au.set(e,t),t}function X1(e,t,n){t[eg]===t?t[Qd].push({id:e,index:n}):(t[Qd]=[{id:e,index:n}],t[eg]=t)}var Ft=vt("BufferService"),xb=vt("CoreMouseService"),Ni=vt("CoreService"),Q1=vt("CharsetService"),Xf=vt("InstantiationService"),vb=vt("LogService"),$t=vt("OptionsService"),_b=vt("OscLinkService"),J1=vt("UnicodeService"),Ql=vt("DecorationService"),Jd=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,s=new bn,l=n.getTrimmedLength(),o=-1,c=-1,u=!1;for(let h=0;hi?i.activate(m,x,f):Z1(m,x),hover:(m,x)=>i?.hover?.(m,x,f),leave:(m,x)=>i?.leave?.(m,x,f)})}u=!1,s.hasExtendedAttrs()&&s.extended.urlId?(c=h,o=s.extended.urlId):(c=-1,o=-1)}}t(r)}};Jd=Qe([se(0,Ft),se(1,$t),se(2,_b)],Jd);function Z1(e,t){if(confirm(`Do you want to navigate to ${t}? - -WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var wc=vt("CharSizeService"),mr=vt("CoreBrowserService"),Qf=vt("MouseService"),gr=vt("RenderService"),eC=vt("SelectionService"),yb=vt("CharacterJoinerService"),ws=vt("ThemeService"),bb=vt("LinkProviderService"),tC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?tg.isErrorNoTelemetry(e)?new tg(e.message+` - -`+e.stack):new Error(e.message+` - -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},nC=new tC;function lo(e){rC(e)||nC.onUnexpectedError(e)}var Zd="Canceled";function rC(e){return e instanceof iC?!0:e instanceof Error&&e.name===Zd&&e.message===Zd}var iC=class extends Error{constructor(){super(Zd),this.name=this.message}};function sC(e){return new Error(`Illegal argument: ${e}`)}var tg=class eh extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof eh)return t;let n=new eh;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},th=class wb extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,wb.prototype)}};function Zt(e,t=0){return e[e.length-(1+t)]}var lC;(e=>{function t(s){return s<0}e.isLessThan=t;function n(s){return s<=0}e.isLessThanOrEqual=n;function r(s){return s>0}e.isGreaterThan=r;function i(s){return s===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(lC||={});function aC(e,t){let n=this,r=!1,i;return function(){return r||(r=!0,t||(i=e.apply(n,arguments))),i}}var Sb;(e=>{function t(b){return b&&typeof b=="object"&&typeof b[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(b){yield b}e.single=i;function s(b){return t(b)?b:i(b)}e.wrap=s;function l(b){return b||n}e.from=l;function*o(b){for(let C=b.length-1;C>=0;C--)yield b[C]}e.reverse=o;function c(b){return!b||b[Symbol.iterator]().next().done===!0}e.isEmpty=c;function u(b){return b[Symbol.iterator]().next().value}e.first=u;function h(b,C){let k=0;for(let N of b)if(C(N,k++))return!0;return!1}e.some=h;function d(b,C){for(let k of b)if(C(k))return k}e.find=d;function*f(b,C){for(let k of b)C(k)&&(yield k)}e.filter=f;function*p(b,C){let k=0;for(let N of b)yield C(N,k++)}e.map=p;function*m(b,C){let k=0;for(let N of b)yield*C(N,k++)}e.flatMap=m;function*x(...b){for(let C of b)yield*C}e.concat=x;function w(b,C,k){let N=k;for(let R of b)N=C(N,R);return N}e.reduce=w;function*v(b,C,k=b.length){for(C<0&&(C+=b.length),k<0?k+=b.length:k>b.length&&(k=b.length);C1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function oC(...e){return $e(()=>wi(e))}function $e(e){return{dispose:aC(()=>{e()})}}var kb=class Cb{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{wi(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Cb.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};kb.DISABLE_DISPOSED_WARNING=!1;var Hr=kb,_e=class{constructor(){this._store=new Hr,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};_e.None=Object.freeze({dispose(){}});var gs=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},ar=typeof window=="object"?window:globalThis,nh=class rh{constructor(t){this.element=t,this.next=rh.Undefined,this.prev=rh.Undefined}};nh.Undefined=new nh(void 0);var We=nh,ng=class{constructor(){this._first=We.Undefined,this._last=We.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===We.Undefined}clear(){let e=this._first;for(;e!==We.Undefined;){let t=e.next;e.prev=We.Undefined,e.next=We.Undefined,e=t}this._first=We.Undefined,this._last=We.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new We(e);if(this._first===We.Undefined)this._first=n,this._last=n;else if(t){let i=this._last;this._last=n,n.prev=i,i.next=n}else{let i=this._first;this._first=n,n.next=i,i.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==We.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==We.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==We.Undefined&&e.next!==We.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===We.Undefined&&e.next===We.Undefined?(this._first=We.Undefined,this._last=We.Undefined):e.next===We.Undefined?(this._last=this._last.prev,this._last.next=We.Undefined):e.prev===We.Undefined&&(this._first=this._first.next,this._first.prev=We.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==We.Undefined;)yield e.element,e=e.next}},cC=globalThis.performance&&typeof globalThis.performance.now=="function",uC=class jb{static create(t){return new jb(t)}constructor(t){this._now=cC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},bt;(e=>{e.None=()=>_e.None;function t(D,P){return d(D,()=>{},0,void 0,!0,void 0,P)}e.defer=t;function n(D){return(P,I=null,O)=>{let U=!1,G;return G=D(E=>{if(!U)return G?G.dispose():U=!0,P.call(I,E)},null,O),U&&G.dispose(),G}}e.once=n;function r(D,P,I){return u((O,U=null,G)=>D(E=>O.call(U,P(E)),null,G),I)}e.map=r;function i(D,P,I){return u((O,U=null,G)=>D(E=>{P(E),O.call(U,E)},null,G),I)}e.forEach=i;function s(D,P,I){return u((O,U=null,G)=>D(E=>P(E)&&O.call(U,E),null,G),I)}e.filter=s;function l(D){return D}e.signal=l;function o(...D){return(P,I=null,O)=>{let U=oC(...D.map(G=>G(E=>P.call(I,E))));return h(U,O)}}e.any=o;function c(D,P,I,O){let U=I;return r(D,G=>(U=P(U,G),U),O)}e.reduce=c;function u(D,P){let I,O={onWillAddFirstListener(){I=D(U.fire,U)},onDidRemoveLastListener(){I?.dispose()}},U=new ne(O);return P?.add(U),U.event}function h(D,P){return P instanceof Array?P.push(D):P&&P.add(D),D}function d(D,P,I=100,O=!1,U=!1,G,E){let z,j,re,V=0,A,ie={leakWarningThreshold:G,onWillAddFirstListener(){z=D(J=>{V++,j=P(j,J),O&&!re&&(ee.fire(j),j=void 0),A=()=>{let W=j;j=void 0,re=void 0,(!O||V>1)&&ee.fire(W),V=0},typeof I=="number"?(clearTimeout(re),re=setTimeout(A,I)):re===void 0&&(re=0,queueMicrotask(A))})},onWillRemoveListener(){U&&V>0&&A?.()},onDidRemoveLastListener(){A=void 0,z.dispose()}},ee=new ne(ie);return E?.add(ee),ee.event}e.debounce=d;function f(D,P=0,I){return e.debounce(D,(O,U)=>O?(O.push(U),O):[U],P,void 0,!0,void 0,I)}e.accumulate=f;function p(D,P=(O,U)=>O===U,I){let O=!0,U;return s(D,G=>{let E=O||!P(G,U);return O=!1,U=G,E},I)}e.latch=p;function m(D,P,I){return[e.filter(D,P,I),e.filter(D,O=>!P(O),I)]}e.split=m;function x(D,P=!1,I=[],O){let U=I.slice(),G=D(j=>{U?U.push(j):z.fire(j)});O&&O.add(G);let E=()=>{U?.forEach(j=>z.fire(j)),U=null},z=new ne({onWillAddFirstListener(){G||(G=D(j=>z.fire(j)),O&&O.add(G))},onDidAddFirstListener(){U&&(P?setTimeout(E):E())},onDidRemoveLastListener(){G&&G.dispose(),G=null}});return O&&O.add(z),z.event}e.buffer=x;function w(D,P){return(I,O,U)=>{let G=P(new _);return D(function(E){let z=G.evaluate(E);z!==v&&I.call(O,z)},void 0,U)}}e.chain=w;let v=Symbol("HaltChainable");class _{constructor(){this.steps=[]}map(P){return this.steps.push(P),this}forEach(P){return this.steps.push(I=>(P(I),I)),this}filter(P){return this.steps.push(I=>P(I)?I:v),this}reduce(P,I){let O=I;return this.steps.push(U=>(O=P(O,U),O)),this}latch(P=(I,O)=>I===O){let I=!0,O;return this.steps.push(U=>{let G=I||!P(U,O);return I=!1,O=U,G?U:v}),this}evaluate(P){for(let I of this.steps)if(P=I(P),P===v)break;return P}}function y(D,P,I=O=>O){let O=(...z)=>E.fire(I(...z)),U=()=>D.on(P,O),G=()=>D.removeListener(P,O),E=new ne({onWillAddFirstListener:U,onDidRemoveLastListener:G});return E.event}e.fromNodeEventEmitter=y;function b(D,P,I=O=>O){let O=(...z)=>E.fire(I(...z)),U=()=>D.addEventListener(P,O),G=()=>D.removeEventListener(P,O),E=new ne({onWillAddFirstListener:U,onDidRemoveLastListener:G});return E.event}e.fromDOMEventEmitter=b;function C(D){return new Promise(P=>n(D)(P))}e.toPromise=C;function k(D){let P=new ne;return D.then(I=>{P.fire(I)},()=>{P.fire(void 0)}).finally(()=>{P.dispose()}),P.event}e.fromPromise=k;function N(D,P){return D(I=>P.fire(I))}e.forward=N;function R(D,P,I){return P(I),D(O=>P(O))}e.runAndSubscribe=R;class L{constructor(P,I){this._observable=P,this._counter=0,this._hasChanged=!1;let O={onWillAddFirstListener:()=>{P.addObserver(this)},onDidRemoveLastListener:()=>{P.removeObserver(this)}};this.emitter=new ne(O),I&&I.add(this.emitter)}beginUpdate(P){this._counter++}handlePossibleChange(P){}handleChange(P,I){this._hasChanged=!0}endUpdate(P){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function S(D,P){return new L(D,P).emitter.event}e.fromObservable=S;function T(D){return(P,I,O)=>{let U=0,G=!1,E={beginUpdate(){U++},endUpdate(){U--,U===0&&(D.reportChanges(),G&&(G=!1,P.call(I)))},handlePossibleChange(){},handleChange(){G=!0}};D.addObserver(E),D.reportChanges();let z={dispose(){D.removeObserver(E)}};return O instanceof Hr?O.add(z):Array.isArray(O)&&O.push(z),z}}e.fromObservableLight=T})(bt||={});var ih=class sh{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${sh._idPool++}`,sh.all.add(this)}start(t){this._stopWatch=new uC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};ih.all=new Set,ih._idPool=0;var dC=ih,hC=-1,Nb=class Eb{constructor(t,n,r=(Eb._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,n){let r=this.threshold;if(r<=0||n{let s=this._stacks.get(t.value)||0;this._stacks.set(t.value,s-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[r,i]of this._stacks)(!t||n{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let o=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new gC(`${l}. HINT: Stack shows most frequent listener (${o[1]}-times)`,o[0]);return(this._options?.onListenerError||lo)(c),_e.None}if(this._disposed)return _e.None;t&&(e=e.bind(t));let r=new ou(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=pC.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ou?(this._deliveryQueue??=new yC,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let s=$e(()=>{i?.(),this._removeListener(r)});return n instanceof Hr?n.add(s):Array.isArray(n)&&n.push(s),s},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*vC<=t.length){let i=0;for(let s=0;s0}},yC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},lh=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ne,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ne,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(r,t),this._onDidChangeZoomLevel.fire(r)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToFullScreen.set(r,t),this._onDidChangeFullscreen.fire(r)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};lh.INSTANCE=new lh;var Jf=lh;function bC(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}Jf.INSTANCE.onDidChangeZoomLevel;function wC(e){return Jf.INSTANCE.getZoomFactor(e)}Jf.INSTANCE.onDidChangeFullscreen;var Ss=typeof navigator=="object"?navigator.userAgent:"",ah=Ss.indexOf("Firefox")>=0,SC=Ss.indexOf("AppleWebKit")>=0,Zf=Ss.indexOf("Chrome")>=0,kC=!Zf&&Ss.indexOf("Safari")>=0;Ss.indexOf("Electron/")>=0;Ss.indexOf("Android")>=0;var cu=!1;if(typeof ar.matchMedia=="function"){let e=ar.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ar.matchMedia("(display-mode: fullscreen)");cu=e.matches,bC(ar,e,({matches:n})=>{cu&&t.matches||(cu=n)})}var ts="en",oh=!1,ch=!1,ao=!1,Ab=!1,ka,oo=ts,rg=ts,CC,tr,pi=globalThis,nn;typeof pi.vscode<"u"&&typeof pi.vscode.process<"u"?nn=pi.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(nn=process);var jC=typeof nn?.versions?.electron=="string",NC=jC&&nn?.type==="renderer";if(typeof nn=="object"){oh=nn.platform==="win32",ch=nn.platform==="darwin",ao=nn.platform==="linux",ao&&nn.env.SNAP&&nn.env.SNAP_REVISION,nn.env.CI||nn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,ka=ts,oo=ts;let e=nn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);ka=t.userLocale,rg=t.osLocale,oo=t.resolvedLanguage||ts,CC=t.languagePack?.translationsConfigFile}catch{}Ab=!0}else typeof navigator=="object"&&!NC?(tr=navigator.userAgent,oh=tr.indexOf("Windows")>=0,ch=tr.indexOf("Macintosh")>=0,(tr.indexOf("Macintosh")>=0||tr.indexOf("iPad")>=0||tr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ao=tr.indexOf("Linux")>=0,tr?.indexOf("Mobi")>=0,oo=globalThis._VSCODE_NLS_LANGUAGE||ts,ka=navigator.language.toLowerCase(),rg=ka):console.error("Unable to resolve platform.");var Tb=oh,Kn=ch,EC=ao,ig=Ab,Gn=tr,yr=oo,PC;(e=>{function t(){return yr}e.value=t;function n(){return yr.length===2?yr==="en":yr.length>=3?yr[0]==="e"&&yr[1]==="n"&&yr[2]==="-":!1}e.isDefaultVariant=n;function r(){return yr==="en"}e.isDefault=r})(PC||={});var AC=typeof pi.postMessage=="function"&&!pi.importScripts;(()=>{if(AC){let e=[];pi.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let r=0,i=e.length;r{let r=++t;e.push({id:r,callback:n}),pi.postMessage({vscodeScheduleAsyncWork:r},"*")}}return e=>setTimeout(e)})();var TC=!!(Gn&&Gn.indexOf("Chrome")>=0);Gn&&Gn.indexOf("Firefox")>=0;!TC&&Gn&&Gn.indexOf("Safari")>=0;Gn&&Gn.indexOf("Edg/")>=0;Gn&&Gn.indexOf("Android")>=0;var Ti=typeof navigator=="object"?navigator:{};ig||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ti&&Ti.clipboard&&Ti.clipboard.writeText,ig||Ti&&Ti.clipboard&&Ti.clipboard.readText;var ep=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},uu=new ep,sg=new ep,lg=new ep,LC=new Array(230),Lb;(e=>{function t(o){return uu.keyCodeToStr(o)}e.toString=t;function n(o){return uu.strToKeyCode(o)}e.fromString=n;function r(o){return sg.keyCodeToStr(o)}e.toUserSettingsUS=r;function i(o){return lg.keyCodeToStr(o)}e.toUserSettingsGeneral=i;function s(o){return sg.strToKeyCode(o)||lg.strToKeyCode(o)}e.fromUserSettings=s;function l(o){if(o>=98&&o<=113)return null;switch(o){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return uu.keyCodeToStr(o)}e.toElectronAccelerator=l})(Lb||={});var DC=class Db{constructor(t,n,r,i,s){this.ctrlKey=t,this.shiftKey=n,this.altKey=r,this.metaKey=i,this.keyCode=s}equals(t){return t instanceof Db&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",r=this.altKey?"1":"0",i=this.metaKey?"1":"0";return`K${t}${n}${r}${i}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new RC([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},RC=class{constructor(e){if(e.length===0)throw sC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t{function t(n){return n===e.None||n===e.Cancelled||n instanceof HC?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:bt.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Rb})})(WC||={});var HC=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Rb:(this._emitter||(this._emitter=new ne),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},tp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new th("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new th("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},UC=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new th("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=$e(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},qC;(e=>{async function t(r){let i,s=await Promise.all(r.map(l=>l.then(o=>o,o=>{i||(i=o)})));if(typeof i<"u")throw i;return s}e.settled=t;function n(r){return new Promise(async(i,s)=>{try{await r(i,s)}catch(l){s(l)}})}e.withAsyncBody=n})(qC||={});var ug=class pn{static fromArray(t){return new pn(n=>{n.emitMany(t)})}static fromPromise(t){return new pn(async n=>{n.emitMany(await t)})}static fromPromises(t){return new pn(async n=>{await Promise.all(t.map(async r=>n.emitOne(await r)))})}static merge(t){return new pn(async n=>{await Promise.all(t.map(async r=>{for await(let i of r)n.emitOne(i)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new ne,queueMicrotask(async()=>{let r={emitOne:i=>this.emitOne(i),emitMany:i=>this.emitMany(i),reject:i=>this.reject(i)};try{await Promise.resolve(t(r)),this.resolve()}catch(i){this.reject(i)}finally{r.emitOne=void 0,r.emitMany=void 0,r.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new pn(async r=>{for await(let i of t)r.emitOne(n(i))})}map(t){return pn.map(this,t)}static filter(t,n){return new pn(async r=>{for await(let i of t)n(i)&&r.emitOne(i)})}filter(t){return pn.filter(this,t)}static coalesce(t){return pn.filter(t,n=>!!n)}coalesce(){return pn.coalesce(this)}static async toPromise(t){let n=[];for await(let r of t)n.push(r);return n}toPromise(){return pn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};ug.EMPTY=ug.fromArray([]);var{getWindow:Un,getWindowId:VC,onDidRegisterWindow:KC}=function(){let e=new Map,t={window:ar,disposables:new Hr};e.set(ar.vscodeWindowId,t);let n=new ne,r=new ne,i=new ne;function s(l,o){return(typeof l=="number"?e.get(l):void 0)??(o?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(l){if(e.has(l.vscodeWindowId))return _e.None;let o=new Hr,c={window:l,disposables:o.add(new Hr)};return e.set(l.vscodeWindowId,c),o.add($e(()=>{e.delete(l.vscodeWindowId),r.fire(l)})),o.add(fe(l,ht.BEFORE_UNLOAD,()=>{i.fire(l)})),n.fire(c),o},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(l){return l.vscodeWindowId},hasWindow(l){return e.has(l)},getWindowById:s,getWindow(l){let o=l;if(o?.ownerDocument?.defaultView)return o.ownerDocument.defaultView.window;let c=l;return c?.view?c.view.window:ar},getDocument(l){return Un(l).document}}}(),GC=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function fe(e,t,n,r){return new GC(e,t,n,r)}var dg=function(e,t,n,r){return fe(e,t,n,r)},np,YC=class extends UC{constructor(e){super(),this.defaultTarget=e&&Un(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},hg=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){lo(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=s=>{n.set(s,!1);let l=e.get(s)??[];for(t.set(s,l),e.set(s,[]),r.set(s,!0);l.length>0;)l.sort(hg.sort),l.shift().execute();r.set(s,!1)};np=(s,l,o=0)=>{let c=VC(s),u=new hg(l,o),h=e.get(c);return h||(h=[],e.set(c,h)),h.push(u),n.get(c)||(n.set(c,!0),s.requestAnimationFrame(()=>i(c))),u}})();function XC(e){let t=e.getBoundingClientRect(),n=Un(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var ht={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},QC=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Wt(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Wt(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Wt(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Wt(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Wt(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Wt(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Wt(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Wt(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Wt(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Wt(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Wt(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Wt(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Wt(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Wt(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Wt(e){return typeof e=="number"?`${e}px`:e}function vl(e){return new QC(e)}var Mb=class{constructor(){this._hooks=new Hr,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let s=e;try{e.setPointerCapture(t),this._hooks.add($e(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{s=Un(e)}this._hooks.add(fe(s,ht.POINTER_MOVE,l=>{if(l.buttons!==n){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(fe(s,ht.POINTER_UP,l=>this.stopMonitoring(!0)))}};function JC(e,t,n){let r=null,i=null;if(typeof n.value=="function"?(r="value",i=n.value,i.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(r="get",i=n.get),!i)throw new Error("not supported");let s=`$memoize$${t}`;n[r]=function(...l){return this.hasOwnProperty(s)||Object.defineProperty(this,s,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,l)}),this[s]}}var zn;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(zn||={});var il=class Nt extends _e{constructor(){super(),this.dispatched=!1,this.targets=new ng,this.ignoreTargets=new ng,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(bt.runAndSubscribe(KC,({window:t,disposables:n})=>{n.add(fe(t.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),n.add(fe(t.document,"touchend",r=>this.onTouchEnd(t,r))),n.add(fe(t.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:ar,disposables:this._store}))}static addTarget(t){if(!Nt.isTouchDevice())return _e.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.targets.push(t);return $e(n)}static ignoreTarget(t){if(!Nt.isTouchDevice())return _e.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.ignoreTargets.push(t);return $e(n)}static isTouchDevice(){return"ontouchstart"in ar||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,i=t.targetTouches.length;r=Nt.HOLD_DELAY&&Math.abs(c.initialPageX-Zt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Zt(c.rollingPageY))<30){let h=this.newGestureEvent(zn.Contextmenu,c.initialTarget);h.pageX=Zt(c.rollingPageX),h.pageY=Zt(c.rollingPageY),this.dispatchEvent(h)}else if(i===1){let h=Zt(c.rollingPageX),d=Zt(c.rollingPageY),f=Zt(c.rollingTimestamps)-c.rollingTimestamps[0],p=h-c.rollingPageX[0],m=d-c.rollingPageY[0],x=[...this.targets].filter(w=>c.initialTarget instanceof Node&&w.contains(c.initialTarget));this.inertia(t,x,r,Math.abs(p)/f,p>0?1:-1,h,Math.abs(m)/f,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(zn.End,c.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let r=document.createEvent("CustomEvent");return r.initEvent(t,!1,!0),r.initialTarget=n,r.tapCount=0,r}dispatchEvent(t){if(t.type===zn.Tap){let n=new Date().getTime(),r=0;n-this._lastSetTapCountTime>Nt.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===zn.Change||t.type===zn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(t.initialTarget))return;let n=[];for(let r of this.targets)if(r.contains(t.initialTarget)){let i=0,s=t.initialTarget;for(;s&&s!==r;)i++,s=s.parentElement;n.push([i,r])}n.sort((r,i)=>r[0]-i[0]);for(let[r,i]of n)i.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,s,l,o,c,u){this.handle=np(t,()=>{let h=Date.now(),d=h-r,f=0,p=0,m=!0;i+=Nt.SCROLL_FRICTION*d,o+=Nt.SCROLL_FRICTION*d,i>0&&(m=!1,f=s*i*d),o>0&&(m=!1,p=c*o*d);let x=this.newGestureEvent(zn.Change);x.translationX=f,x.translationY=p,n.forEach(w=>w.dispatchEvent(x)),m||this.inertia(t,n,h,i,s,l+f,o,c,u+p)})}onTouchMove(t){let n=Date.now();for(let r=0,i=t.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(s.pageX),l.rollingPageY.push(s.pageY),l.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};il.SCROLL_FRICTION=-.005,il.HOLD_DELAY=700,il.CLEAR_TAP_COUNT_TIME=400,Qe([JC],il,"isTouchDevice",1);var ZC=il,rp=class extends _e{onclick(e,t){this._register(fe(e,ht.CLICK,n=>t(new Ca(Un(e),n))))}onmousedown(e,t){this._register(fe(e,ht.MOUSE_DOWN,n=>t(new Ca(Un(e),n))))}onmouseover(e,t){this._register(fe(e,ht.MOUSE_OVER,n=>t(new Ca(Un(e),n))))}onmouseleave(e,t){this._register(fe(e,ht.MOUSE_LEAVE,n=>t(new Ca(Un(e),n))))}onkeydown(e,t){this._register(fe(e,ht.KEY_DOWN,n=>t(new ag(n))))}onkeyup(e,t){this._register(fe(e,ht.KEY_UP,n=>t(new ag(n))))}oninput(e,t){this._register(fe(e,ht.INPUT,t))}onblur(e,t){this._register(fe(e,ht.BLUR,t))}onfocus(e,t){this._register(fe(e,ht.FOCUS,t))}onchange(e,t){this._register(fe(e,ht.CHANGE,t))}ignoreGesture(e){return ZC.ignoreTarget(e)}},fg=11,ej=class extends rp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=fg+"px",this.domNode.style.height=fg+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Mb),this._register(dg(this.bgDomNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(dg(this.domNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new YC),this._pointerdownScheduleRepeatTimer=this._register(new tp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Un(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},tj=class uh{constructor(t,n,r,i,s,l,o){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,r=r|0,i=i|0,s=s|0,l=l|0,o=o|0),this.rawScrollLeft=i,this.rawScrollTop=o,n<0&&(n=0),i+n>r&&(i=r-n),i<0&&(i=0),s<0&&(s=0),o+s>l&&(o=l-s),o<0&&(o=0),this.width=n,this.scrollWidth=r,this.scrollLeft=i,this.height=s,this.scrollHeight=l,this.scrollTop=o}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new uh(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new uh(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let r=this.width!==t.width,i=this.scrollWidth!==t.scrollWidth,s=this.scrollLeft!==t.scrollLeft,l=this.height!==t.height,o=this.scrollHeight!==t.scrollHeight,c=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:r,scrollWidthChanged:i,scrollLeftChanged:s,heightChanged:l,scrollHeightChanged:o,scrollTopChanged:c}}},nj=class extends _e{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new tj(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;t?r=new mg(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):r=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=mg.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},pg=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function du(e,t){let n=t-e;return function(r){return e+n*sj(r)}}function rj(e,t,n){return function(r){return r2.5*r){let i,s;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},aj=140,Ib=class extends rp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new lj(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Mb),this._shouldRender=!0,this.domNode=vl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(fe(this.domNode.domNode,ht.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new ej(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=vl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof n=="number"&&this.slider.setWidth(n),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(fe(this.slider.domNode,ht.POINTER_DOWN,i=>{i.button===0&&(i.preventDefault(),this._sliderPointerDown(i))})),this.onclick(this.slider.domNode,i=>{i.leftButton&&i.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,n=e.offsetY;else{let i=XC(this.domNode.domNode);t=e.pageX-i.left,n=e.pageY-i.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{let s=this._sliderOrthogonalPointerPosition(i),l=Math.abs(s-n);if(Tb&&l>aj){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(i)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Ob=class hh{constructor(t,n,r,i,s,l){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(r),this._arrowSize=Math.round(t),this._visibleSize=i,this._scrollSize=s,this._scrollPosition=l,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new hh(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,r,i,s){let l=Math.max(0,r-t),o=Math.max(0,l-2*n),c=i>0&&i>r;if(!c)return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(r*o/i))),h=(o-u)/(i-r),d=s*h;return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=hh._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,r=this._scrollPosition;return n0&&Math.abs(t.deltaY)>0)return 1;let r=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(r+=.25),n){let i=Math.abs(t.deltaX),s=Math.abs(t.deltaY),l=Math.abs(n.deltaX),o=Math.abs(n.deltaY),c=Math.max(Math.min(i,l),1),u=Math.max(Math.min(s,o),1),h=Math.max(i,l),d=Math.max(s,o);h%c===0&&d%u===0&&(r-=.5)}return Math.min(Math.max(r,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};fh.INSTANCE=new fh;var hj=fh,fj=class extends rp{constructor(e,t,n){super(),this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ne),this.onWillScroll=this._onWillScroll.event,this._options=mj(t),this._scrollable=n,this._register(this._scrollable.onScroll(i=>{this._onWillScroll.fire(i),this._onDidScroll(i),this._onScroll.fire(i)}));let r={onMouseWheel:i=>this._onMouseWheel(i),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new cj(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new oj(this._scrollable,this._options,r)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=vl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=vl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=vl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,i=>this._onMouseOver(i)),this.onmouseleave(this._listenOnDomNode,i=>this._onMouseLeave(i)),this._hideTimeout=this._register(new tp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=wi(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Kn&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new cg(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=wi(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new cg(n))};this._mouseWheelToDispose.push(fe(this._listenOnDomNode,ht.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=hj.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let i=e.deltaY*this._options.mouseWheelScrollSensitivity,s=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&s+i===0?s=i=0:Math.abs(i)>=Math.abs(s)?s=0:i=0),this._options.flipAxes&&([i,s]=[s,i]);let l=!Kn&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||l)&&!s&&(s=i,i=0),e.browserEvent&&e.browserEvent.altKey&&(s=s*this._options.fastScrollSensitivity,i=i*this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),c={};if(i){let u=gg*i,h=o.scrollTop-(u<0?Math.floor(u):Math.ceil(u));this._verticalScrollbar.writeScrollPosition(c,h)}if(s){let u=gg*s,h=o.scrollLeft-(u<0?Math.floor(u):Math.ceil(u));this._horizontalScrollbar.writeScrollPosition(c,h)}c=this._scrollable.validateScrollPosition(c),(o.scrollLeft!==c.scrollLeft||o.scrollTop!==c.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(c):this._scrollable.setScrollPositionNow(c),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?" left":"",i=t?" top":"",s=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${s}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),uj)}},pj=class extends fj{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function mj(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Kn&&(t.className+=" mac"),t}var ph=class extends _e{constructor(e,t,n,r,i,s,l,o){super(),this._bufferService=n,this._optionsService=l,this._renderService=o,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new nj({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:u=>np(r.window,u)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new pj(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(u=>{this._scrollableElement.updateOptions({handleMouseWheel:!(u&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(bt.runAndSubscribe(s.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=s.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register($e(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register($e(()=>this._styleElement.remove())),this._register(bt.runAndSubscribe(s.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${s.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${s.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${s.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(u=>this._handleScroll(u)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};ph=Qe([se(2,Ft),se(3,mr),se(4,xb),se(5,ws),se(6,$t),se(7,gr)],ph);var mh=class extends _e{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(s=>this._removeDecoration(s))),this._register($e(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};mh=Qe([se(1,Ft),se(2,mr),se(3,Ql),se(4,gr)],mh);var gj=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||"full"]&&t<=e.endBufferLine+this._linePadding[n||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},In={full:0,left:0,center:0,right:0},br={full:0,left:0,center:0,right:0},Os={full:0,left:0,center:0,right:0},Uo=class extends _e{constructor(e,t,n,r,i,s,l,o){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=s,this._themeService=l,this._coreBrowserService=o,this._colorZoneStore=new gj,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register($e(()=>this._canvas?.remove()));let c=this._canvas.getContext("2d");if(c)this._ctx=c;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);br.full=this._canvas.width,br.left=e,br.center=t,br.right=e,this._refreshDrawHeightConstants(),Os.full=1,Os.left=1,Os.center=1+br.left,Os.right=1+br.left+br.center}_refreshDrawHeightConstants(){In.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);In.left=t,In.center=t,In.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Os[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-In[e.position||"full"]/2),br[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+In[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Uo=Qe([se(2,Ft),se(3,Ql),se(4,gr),se(5,$t),se(6,ws),se(7,mr)],Uo);var K;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(K||={});var co;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(co||={});var Bb;(e=>e.ST=`${K.ESC}\\`)(Bb||={});var gh=class{constructor(e,t,n,r,i,s){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=s,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let n;t.start+=this._dataAlreadySent.length,this._isComposing?n=this._textarea.value.substring(t.start,this._compositionPosition.start):n=this._textarea.value.substring(t.start),n.length>0&&this._coreService.triggerDataEvent(n,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,"");this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};gh=Qe([se(2,Ft),se(3,$t),se(4,Ni),se(5,gr)],gh);var pt=0,mt=0,gt=0,Ge=0,xg={css:"#00000000",rgba:0},rt;(e=>{function t(i,s,l,o){return o!==void 0?`#${Jr(i)}${Jr(s)}${Jr(l)}${Jr(o)}`:`#${Jr(i)}${Jr(s)}${Jr(l)}`}e.toCss=t;function n(i,s,l,o=255){return(i<<24|s<<16|l<<8|o)>>>0}e.toRgba=n;function r(i,s,l,o){return{css:e.toCss(i,s,l,o),rgba:e.toRgba(i,s,l,o)}}e.toColor=r})(rt||={});var Be;(e=>{function t(c,u){if(Ge=(u.rgba&255)/255,Ge===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,d=u.rgba>>16&255,f=u.rgba>>8&255,p=c.rgba>>24&255,m=c.rgba>>16&255,x=c.rgba>>8&255;pt=p+Math.round((h-p)*Ge),mt=m+Math.round((d-m)*Ge),gt=x+Math.round((f-x)*Ge);let w=rt.toCss(pt,mt,gt),v=rt.toRgba(pt,mt,gt);return{css:w,rgba:v}}e.blend=t;function n(c){return(c.rgba&255)===255}e.isOpaque=n;function r(c,u,h){let d=uo.ensureContrastRatio(c.rgba,u.rgba,h);if(d)return rt.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=r;function i(c){let u=(c.rgba|255)>>>0;return[pt,mt,gt]=uo.toChannels(u),{css:rt.toCss(pt,mt,gt),rgba:u}}e.opaque=i;function s(c,u){return Ge=Math.round(u*255),[pt,mt,gt]=uo.toChannels(c.rgba),{css:rt.toCss(pt,mt,gt,Ge),rgba:rt.toRgba(pt,mt,gt,Ge)}}e.opacity=s;function l(c,u){return Ge=c.rgba&255,s(c,Ge*u/255)}e.multiplyOpacity=l;function o(c){return[c.rgba>>24&255,c.rgba>>16&255,c.rgba>>8&255]}e.toColorRGB=o})(Be||={});var He;(e=>{let t,n;try{let i=document.createElement("canvas");i.width=1,i.height=1;let s=i.getContext("2d",{willReadFrequently:!0});s&&(t=s,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function r(i){if(i.match(/#[\da-f]{3,8}/i))switch(i.length){case 4:return pt=parseInt(i.slice(1,2).repeat(2),16),mt=parseInt(i.slice(2,3).repeat(2),16),gt=parseInt(i.slice(3,4).repeat(2),16),rt.toColor(pt,mt,gt);case 5:return pt=parseInt(i.slice(1,2).repeat(2),16),mt=parseInt(i.slice(2,3).repeat(2),16),gt=parseInt(i.slice(3,4).repeat(2),16),Ge=parseInt(i.slice(4,5).repeat(2),16),rt.toColor(pt,mt,gt,Ge);case 7:return{css:i,rgba:(parseInt(i.slice(1),16)<<8|255)>>>0};case 9:return{css:i,rgba:parseInt(i.slice(1),16)>>>0}}let s=i.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(s)return pt=parseInt(s[1]),mt=parseInt(s[2]),gt=parseInt(s[3]),Ge=Math.round((s[5]===void 0?1:parseFloat(s[5]))*255),rt.toColor(pt,mt,gt,Ge);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=i,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[pt,mt,gt,Ge]=t.getImageData(0,0,1,1).data,Ge!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rt.toRgba(pt,mt,gt,Ge),css:i}}e.toColor=r})(He||={});var Rt;(e=>{function t(r){return n(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=t;function n(r,i,s){let l=r/255,o=i/255,c=s/255,u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),h=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);return u*.2126+h*.7152+d*.0722}e.relativeLuminance2=n})(Rt||={});var uo;(e=>{function t(l,o){if(Ge=(o&255)/255,Ge===1)return o;let c=o>>24&255,u=o>>16&255,h=o>>8&255,d=l>>24&255,f=l>>16&255,p=l>>8&255;return pt=d+Math.round((c-d)*Ge),mt=f+Math.round((u-f)*Ge),gt=p+Math.round((h-p)*Ge),rt.toRgba(pt,mt,gt)}e.blend=t;function n(l,o,c){let u=Rt.relativeLuminance(l>>8),h=Rt.relativeLuminance(o>>8);if(Zn(u,h)>8));if(m>8));return m>w?p:x}return p}let d=i(l,o,c),f=Zn(u,Rt.relativeLuminance(d>>8));if(f>8));return f>m?d:p}return d}}e.ensureContrastRatio=n;function r(l,o,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=o>>24&255,p=o>>16&255,m=o>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x0||p>0||m>0);)f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),m-=Math.max(0,Math.ceil(m*.1)),x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));return(f<<24|p<<16|m<<8|255)>>>0}e.reduceLuminance=r;function i(l,o,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=o>>24&255,p=o>>16&255,m=o>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x>>0}e.increaseLuminance=i;function s(l){return[l>>24&255,l>>16&255,l>>8&255,l&255]}e.toChannels=s})(uo||={});function Jr(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Zn(e,t){return e1){let h=this._getJoinedRanges(r,l,s,t,i);for(let d=0;d1){let u=this._getJoinedRanges(r,l,s,t,i);for(let h=0;h=S,G=P,E=this._workCell;if(f.length>0&&P===f[0][0]&&U){let $=f.shift(),ge=this._isCellInSelection($[0],t);for(_=$[0]+1;_<$[1];_++)U&&=ge===this._isCellInSelection(_,t);U&&=!n||s<$[0]||s>=$[1],U?(O=!0,E=new xj(this._workCell,e.translateToString(!0,$[0],$[1]),$[1]-$[0]),G=$[1]-1,I=E.getWidth()):S=$[1]}let z=this._isCellInSelection(P,t),j=n&&P===s,re=D&&P>=u&&P<=h,V=!1;this._decorationService.forEachDecorationAtCell(P,t,void 0,$=>{V=!0});let A=E.getChars()||Rr;if(A===" "&&(E.isUnderline()||E.isOverline())&&(A=" "),L=I*o-c.get(A,E.isBold(),E.isItalic()),!x)x=this._document.createElement("span");else if(w&&(z&&R||!z&&!R&&E.bg===y)&&(z&&R&&p.selectionForeground||E.fg===b)&&E.extended.ext===C&&re===k&&L===N&&!j&&!O&&!V&&U){E.isInvisible()?v+=Rr:v+=A,w++;continue}else w&&(x.textContent=v),x=this._document.createElement("span"),w=0,v="";if(y=E.bg,b=E.fg,C=E.extended.ext,k=re,N=L,R=z,O&&s>=P&&s<=G&&(s=P),!this._coreService.isCursorHidden&&j&&this._coreService.isCursorInitialized){if(T.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&T.push("xterm-cursor-blink"),T.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(i)switch(i){case"outline":T.push("xterm-cursor-outline");break;case"block":T.push("xterm-cursor-block");break;case"bar":T.push("xterm-cursor-bar");break;case"underline":T.push("xterm-cursor-underline");break}}if(E.isBold()&&T.push("xterm-bold"),E.isItalic()&&T.push("xterm-italic"),E.isDim()&&T.push("xterm-dim"),E.isInvisible()?v=Rr:v=E.getChars()||Rr,E.isUnderline()&&(T.push(`xterm-underline-${E.extended.underlineStyle}`),v===" "&&(v=" "),!E.isUnderlineColorDefault()))if(E.isUnderlineColorRGB())x.style.textDecorationColor=`rgb(${Xl.toColorRGB(E.getUnderlineColor()).join(",")})`;else{let $=E.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&E.isBold()&&$<8&&($+=8),x.style.textDecorationColor=p.ansi[$].css}E.isOverline()&&(T.push("xterm-overline"),v===" "&&(v=" ")),E.isStrikethrough()&&T.push("xterm-strikethrough"),re&&(x.style.textDecoration="underline");let ie=E.getFgColor(),ee=E.getFgColorMode(),J=E.getBgColor(),W=E.getBgColorMode(),Y=!!E.isInverse();if(Y){let $=ie;ie=J,J=$;let ge=ee;ee=W,W=ge}let B,le,je=!1;this._decorationService.forEachDecorationAtCell(P,t,void 0,$=>{$.options.layer!=="top"&&je||($.backgroundColorRGB&&(W=50331648,J=$.backgroundColorRGB.rgba>>8&16777215,B=$.backgroundColorRGB),$.foregroundColorRGB&&(ee=50331648,ie=$.foregroundColorRGB.rgba>>8&16777215,le=$.foregroundColorRGB),je=$.options.layer==="top")}),!je&&z&&(B=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,J=B.rgba>>8&16777215,W=50331648,je=!0,p.selectionForeground&&(ee=50331648,ie=p.selectionForeground.rgba>>8&16777215,le=p.selectionForeground)),je&&T.push("xterm-decoration-top");let Ie;switch(W){case 16777216:case 33554432:Ie=p.ansi[J],T.push(`xterm-bg-${J}`);break;case 50331648:Ie=rt.toColor(J>>16,J>>8&255,J&255),this._addStyle(x,`background-color:#${vg((J>>>0).toString(16),"0",6)}`);break;case 0:default:Y?(Ie=p.foreground,T.push("xterm-bg-257")):Ie=p.background}switch(B||E.isDim()&&(B=Be.multiplyOpacity(Ie,.5)),ee){case 16777216:case 33554432:E.isBold()&&ie<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ie+=8),this._applyMinimumContrast(x,Ie,p.ansi[ie],E,B,void 0)||T.push(`xterm-fg-${ie}`);break;case 50331648:let $=rt.toColor(ie>>16&255,ie>>8&255,ie&255);this._applyMinimumContrast(x,Ie,$,E,B,le)||this._addStyle(x,`color:#${vg(ie.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(x,Ie,p.foreground,E,B,le)||Y&&T.push("xterm-fg-257")}T.length&&(x.className=T.join(" "),T.length=0),!j&&!O&&!V&&U?w++:x.textContent=v,L!==this.defaultSpacing&&(x.style.letterSpacing=`${L}px`),d.push(x),P=G}return x&&w&&(x.textContent=v),d}_applyMinimumContrast(e,t,n,r,i,s){if(this._optionsService.rawOptions.minimumContrastRatio===1||yj(r.getCode()))return!1;let l=this._getContrastCache(r),o;if(!i&&!s&&(o=l.getColor(t.rgba,n.rgba)),o===void 0){let c=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);o=Be.ensureContrastRatio(i||t,s||n,c),l.setColor((i||t).rgba,(s||n).rgba,o??null)}return o?(this._addStyle(e,`color:${o.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};xh=Qe([se(1,yb),se(2,$t),se(3,mr),se(4,Ni),se(5,Ql),se(6,ws)],xh);function vg(e,t,n){for(;e.length0&&(this._flat[r]=l),l}let i=e;t&&(i+="B"),n&&(i+="I");let s=this._holey.get(i);if(s===void 0){let l=0;t&&(l|=1),n&&(l|=2),s=this._measure(e,l),s>0&&this._holey.set(i,s)}return s}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Sj=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,s=t[1]-i,l=n[1]-i,o=Math.max(s,0),c=Math.min(l,e.rows-1);if(o>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=s,this.viewportEndRow=l,this.viewportCappedStartRow=o,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function kj(){return new Sj}var hu="xterm-dom-renderer-owner-",hn="xterm-rows",Na="xterm-fg-",_g="xterm-bg-",Bs="xterm-focus",Ea="xterm-selection",Cj=1,vh=class extends _e{constructor(e,t,n,r,i,s,l,o,c,u,h,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=s,this._linkifier2=l,this._charSizeService=c,this._optionsService=u,this._bufferService=h,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Cj++,this._rowElements=[],this._selectionRenderModel=kj(),this.onRequestRedraw=this._register(new ne).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(hn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Ea),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=bj(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(m=>this._injectCss(m))),this._injectCss(this._themeService.colors),this._rowFactory=o.createInstance(xh,document),this._element.classList.add(hu+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(m=>this._handleLinkHover(m))),this._register(this._linkifier2.onHideLinkUnderline(m=>this._handleLinkLeave(m))),this._register($e(()=>{this._element.classList.remove(hu+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new wj(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let n of this._rowElements)n.style.width=`${this.dimensions.css.canvas.width}px`,n.style.height=`${this.dimensions.css.cell.height}px`,n.style.lineHeight=`${this.dimensions.css.cell.height}px`,n.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${hn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${hn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${hn} .xterm-dim { color: ${Be.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${hn}.${Bs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${hn}.${Bs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${hn}.${Bs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Ea} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Ea} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Ea} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[s,l]of e.ansi.entries())t+=`${this._terminalSelector} .${Na}${s} { color: ${l.css}; }${this._terminalSelector} .${Na}${s}.xterm-dim { color: ${Be.multiplyOpacity(l,.5).css}; }${this._terminalSelector} .${_g}${s} { background-color: ${l.css}; }`;t+=`${this._terminalSelector} .${Na}257 { color: ${Be.opaque(e.background).css}; }${this._terminalSelector} .${Na}257.xterm-dim { color: ${Be.multiplyOpacity(Be.opaque(e.background),.5).css}; }${this._terminalSelector} .${_g}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let n=this._rowElements.length;n<=t;n++){let r=this._document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Bs),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Bs),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,s=this._selectionRenderModel.viewportCappedStartRow,l=this._selectionRenderModel.viewportCappedEndRow,o=this._document.createDocumentFragment();if(n){let c=e[0]>t[0];o.appendChild(this._createSelectionElement(s,c?t[0]:e[0],c?e[0]:t[0],l-s+1))}else{let c=r===s?e[0]:0,u=s===i?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(s,c,u));let h=l-s-1;if(o.appendChild(this._createSelectionElement(s+1,0,this._bufferService.cols,h)),s!==l){let d=i===l?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(l,0,d))}}this._selectionContainer.appendChild(o)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement("div"),s=t*this.dimensions.css.cell.width,l=this.dimensions.css.cell.width*(n-t);return s+l>this.dimensions.css.canvas.width&&(l=this.dimensions.css.canvas.width-s),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${s}px`,i.style.width=`${l}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),s=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,l=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,o=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let u=c+n.ydisp,h=this._rowElements[c],d=n.lines.get(u);if(!h||!d)break;h.replaceChildren(...this._rowFactory.createRow(d,u,u===r,l,o,i,s,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${hu}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,s){n<0&&(e=0),r<0&&(t=0);let l=this._bufferService.rows-1;n=Math.max(Math.min(n,l),0),r=Math.max(Math.min(r,l),0),i=Math.min(i,this._bufferService.cols);let o=this._bufferService.buffer,c=o.ybase+o.y,u=Math.min(o.x,i-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=n;p<=r;++p){let m=p+o.ydisp,x=this._rowElements[p],w=o.lines.get(m);if(!x||!w)break;x.replaceChildren(...this._rowFactory.createRow(w,m,m===c,d,f,u,h,this.dimensions.css.cell.width,this._widthCache,s?p===n?e:0:-1,s?(p===r?t:i)-1:-1))}}};vh=Qe([se(7,Xf),se(8,wc),se(9,$t),se(10,Ft),se(11,Ni),se(12,mr),se(13,ws)],vh);var _h=class extends _e{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ne),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Nj(this._optionsService))}catch{this._measureStrategy=this._register(new jj(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};_h=Qe([se(2,$t)],_h);var zb=class extends _e{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},jj=class extends zb{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Nj=class extends zb{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Ej=class extends _e{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Pj(this._window)),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ne),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(r=>this._screenDprMonitor.setWindow(r))),this._register(bt.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(fe(this._textarea,"focus",()=>this._isFocused=!0)),this._register(fe(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Pj=class extends _e{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new gs),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register($e(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=fe(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Aj=class extends _e{constructor(){super(),this.linkProviders=[],this._register($e(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function ip(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),s=parseInt(i.getPropertyValue("padding-left")),l=parseInt(i.getPropertyValue("padding-top"));return[t.clientX-r.left-s,t.clientY-r.top-l]}function Tj(e,t,n,r,i,s,l,o,c){if(!s)return;let u=ip(e,t,n);if(u)return u[0]=Math.ceil((u[0]+(c?l/2:0))/l),u[1]=Math.ceil(u[1]/o),u[0]=Math.min(Math.max(u[0],1),r+(c?1:0)),u[1]=Math.min(Math.max(u[1],1),i),u}var yh=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return Tj(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=ip(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};yh=Qe([se(0,gr),se(1,wc)],yh);var Lj=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Fb={};W1(Fb,{getSafariVersion:()=>Rj,isChromeOS:()=>Ub,isFirefox:()=>$b,isIpad:()=>Mj,isIphone:()=>Ij,isLegacyEdge:()=>Dj,isLinux:()=>sp,isMac:()=>Vo,isNode:()=>Sc,isSafari:()=>Wb,isWindows:()=>Hb});var Sc=typeof process<"u"&&"title"in process,Jl=Sc?"node":navigator.userAgent,Zl=Sc?"node":navigator.platform,$b=Jl.includes("Firefox"),Dj=Jl.includes("Edge"),Wb=/^((?!chrome|android).)*safari/i.test(Jl);function Rj(){if(!Wb)return 0;let e=Jl.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Vo=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zl),Mj=Zl==="iPad",Ij=Zl==="iPhone",Hb=["Windows","Win16","Win32","WinCE"].includes(Zl),sp=Zl.indexOf("Linux")>=0,Ub=/\bCrOS\b/.test(Jl),qb=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Oj=class extends qb{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Bj=class extends qb{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ko=!Sc&&"requestIdleCallback"in window?Bj:Oj,zj=class{constructor(){this._queue=new Ko}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},bh=class extends _e{constructor(e,t,n,r,i,s,l,o,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=o,this._renderer=this._register(new gs),this._pausedResizeTask=new zj,this._observerDisposable=this._register(new gs),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ne),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ne),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ne),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Lj((u,h)=>this._renderRows(u,h),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Fj(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register($e(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(l.onResize(()=>this._fullRefresh())),this._register(l.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(s.onDecorationRegistered(()=>this._fullRefresh())),this._register(s.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(l.cols,l.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(l.buffer.y,l.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(u=>this._registerIntersectionObserver(u,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let n=new e.IntersectionObserver(r=>this._handleIntersectionChange(r[r.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=$e(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};bh=Qe([se(2,$t),se(3,wc),se(4,Ni),se(5,Ql),se(6,Ft),se(7,mr),se(8,ws)],bh);var Fj=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function $j(e,t,n,r){let i=n.buffer.x,s=n.buffer.y;if(!n.buffer.hasScrollback)return Uj(i,s,e,t,n,r)+kc(s,t,n,r)+qj(i,s,e,t,n,r);let l;if(s===t)return l=i>e?"D":"C",Fl(Math.abs(i-e),zl(l,r));l=s>t?"D":"C";let o=Math.abs(s-t),c=Hj(s>t?e:i,n)+(o-1)*n.cols+1+Wj(s>t?i:e);return Fl(c,zl(l,r))}function Wj(e,t){return e-1}function Hj(e,t){return t.cols-e}function Uj(e,t,n,r,i,s){return kc(t,r,i,s).length===0?"":Fl(Kb(e,t,e,t-Si(t,i),!1,i).length,zl("D",s))}function kc(e,t,n,r){let i=e-Si(e,n),s=t-Si(t,n),l=Math.abs(i-s)-Vj(e,t,n);return Fl(l,zl(Vb(e,t),r))}function qj(e,t,n,r,i,s){let l;kc(t,r,i,s).length>0?l=r-Si(r,i):l=t;let o=r,c=Kj(e,t,n,r,i,s);return Fl(Kb(e,l,n,o,c==="C",i).length,zl(c,s))}function Vj(e,t,n){let r=0,i=e-Si(e,n),s=t-Si(t,n);for(let l=0;l=0&&e0?l=r-Si(r,i):l=t,e=n&&lt?"A":"B"}function Kb(e,t,n,r,i,s){let l=e,o=t,c="";for(;(l!==n||o!==r)&&o>=0&&os.cols-1?(c+=s.buffer.translateBufferLineToString(o,!1,e,l),l=0,e=0,o++):!i&&l<0&&(c+=s.buffer.translateBufferLineToString(o,!1,0,e+1),l=s.cols-1,e=l,o--);return c+s.buffer.translateBufferLineToString(o,!1,e,l)}function zl(e,t){let n=t?"O":"[";return K.ESC+n+e}function Fl(e,t){e=Math.floor(e);let n="";for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function yg(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var fu=50,Yj=15,Xj=50,Qj=500,Jj=" ",Zj=new RegExp(Jj,"g"),wh=class extends _e{constructor(e,t,n,r,i,s,l,o,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=s,this._optionsService=l,this._renderService=o,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new bn,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ne),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ne),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=u=>this._handleMouseMove(u),this._mouseUpListener=u=>this._handleMouseUp(u),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(u=>this._handleTrim(u)),this._register(this._bufferService.buffers.onBufferActivate(u=>this._handleBufferActivate(u))),this.enable(),this._model=new Gj(this._bufferService),this._activeSelectionMode=0,this._register($e(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(u=>{u.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let i=e[0]i.replace(Zj," ")).join(Hb?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),sp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=yg(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=ip(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-fu),fu),t/=fu,t/Math.abs(t)+Math.round(t*(Yj-1)))}shouldForceSelection(e){return Vo?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Xj)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Vo&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,s=i.lines.get(e[1]);if(!s)return;let l=i.translateBufferLineToString(e[1],!1),o=this._convertViewportColToCharacterIndex(s,e[0]),c=o,u=e[0]-o,h=0,d=0,f=0,p=0;if(l.charAt(o)===" "){for(;o>0&&l.charAt(o-1)===" ";)o--;for(;c1&&(p+=_-1,c+=_-1);w>0&&o>0&&!this._isCharWordSeparator(s.loadCell(w-1,this._workCell));){s.loadCell(w-1,this._workCell);let y=this._workCell.getChars().length;this._workCell.getWidth()===0?(h++,w--):y>1&&(f+=y-1,o-=y-1),o--,w--}for(;v1&&(p+=y-1,c+=y-1),c++,v++}}c++;let m=o+u-h+f,x=Math.min(this._bufferService.cols,c-o+h+d-f-p);if(!(!t&&l.slice(o,c).trim()==="")){if(n&&m===0&&s.getCodePoint(0)!==32){let w=i.lines.get(e[1]-1);if(w&&s.isWrapped&&w.getCodePoint(this._bufferService.cols-1)!==32){let v=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(v){let _=this._bufferService.cols-v.start;m-=_,x+=_}}}if(r&&m+x===this._bufferService.cols&&s.getCodePoint(this._bufferService.cols-1)!==32){let w=i.lines.get(e[1]+1);if(w?.isWrapped&&w.getCodePoint(0)!==32){let v=this._getWordAt([0,e[1]+1],!1,!1,!0);v&&(x+=v.length)}}return{start:m,length:x}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=yg(n,this._bufferService.cols)}};wh=Qe([se(3,Ft),se(4,Ni),se(5,Qf),se(6,$t),se(7,gr),se(8,mr)],wh);var bg=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},wg=class{constructor(){this._color=new bg,this._css=new bg}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},st=Object.freeze((()=>{let e=[He.toColor("#2e3436"),He.toColor("#cc0000"),He.toColor("#4e9a06"),He.toColor("#c4a000"),He.toColor("#3465a4"),He.toColor("#75507b"),He.toColor("#06989a"),He.toColor("#d3d7cf"),He.toColor("#555753"),He.toColor("#ef2929"),He.toColor("#8ae234"),He.toColor("#fce94f"),He.toColor("#729fcf"),He.toColor("#ad7fa8"),He.toColor("#34e2e2"),He.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],s=t[n%6];e.push({css:rt.toCss(r,i,s),rgba:rt.toRgba(r,i,s)})}for(let n=0;n<24;n++){let r=8+n*10;e.push({css:rt.toCss(r,r,r),rgba:rt.toRgba(r,r,r)})}return e})()),ii=He.toColor("#ffffff"),sl=He.toColor("#000000"),Sg=He.toColor("#ffffff"),kg=sl,zs={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},eN=ii,Sh=class extends _e{constructor(e){super(),this._optionsService=e,this._contrastCache=new wg,this._halfContrastCache=new wg,this._onChangeColors=this._register(new ne),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ii,background:sl,cursor:Sg,cursorAccent:kg,selectionForeground:void 0,selectionBackgroundTransparent:zs,selectionBackgroundOpaque:Be.blend(sl,zs),selectionInactiveBackgroundTransparent:zs,selectionInactiveBackgroundOpaque:Be.blend(sl,zs),scrollbarSliderBackground:Be.opacity(ii,.2),scrollbarSliderHoverBackground:Be.opacity(ii,.4),scrollbarSliderActiveBackground:Be.opacity(ii,.5),overviewRulerBorder:ii,ansi:st.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Pe(e.foreground,ii),t.background=Pe(e.background,sl),t.cursor=Be.blend(t.background,Pe(e.cursor,Sg)),t.cursorAccent=Be.blend(t.background,Pe(e.cursorAccent,kg)),t.selectionBackgroundTransparent=Pe(e.selectionBackground,zs),t.selectionBackgroundOpaque=Be.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Pe(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Be.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Pe(e.selectionForeground,xg):void 0,t.selectionForeground===xg&&(t.selectionForeground=void 0),Be.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Be.opacity(t.selectionBackgroundTransparent,.3)),Be.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Be.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Pe(e.scrollbarSliderBackground,Be.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Pe(e.scrollbarSliderHoverBackground,Be.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Pe(e.scrollbarSliderActiveBackground,Be.opacity(t.foreground,.5)),t.overviewRulerBorder=Pe(e.overviewRulerBorder,eN),t.ansi=st.slice(),t.ansi[0]=Pe(e.black,st[0]),t.ansi[1]=Pe(e.red,st[1]),t.ansi[2]=Pe(e.green,st[2]),t.ansi[3]=Pe(e.yellow,st[3]),t.ansi[4]=Pe(e.blue,st[4]),t.ansi[5]=Pe(e.magenta,st[5]),t.ansi[6]=Pe(e.cyan,st[6]),t.ansi[7]=Pe(e.white,st[7]),t.ansi[8]=Pe(e.brightBlack,st[8]),t.ansi[9]=Pe(e.brightRed,st[9]),t.ansi[10]=Pe(e.brightGreen,st[10]),t.ansi[11]=Pe(e.brightYellow,st[11]),t.ansi[12]=Pe(e.brightBlue,st[12]),t.ansi[13]=Pe(e.brightMagenta,st[13]),t.ansi[14]=Pe(e.brightCyan,st[14]),t.ansi[15]=Pe(e.brightWhite,st[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;rs.index-l.index),r=[];for(let s of n){let l=this._services.get(s.id);if(!l)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${s.id._id}.`);r.push(l)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},rN={trace:0,debug:1,info:2,warn:3,error:4,off:5},iN="xterm.js: ",kh=class extends _e{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=rN[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;r--)this._array[this._getCyclicIndex(r+n.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;rthis._maxLength){let r=this._length+n.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+n<0)throw new Error("Cannot shift elements in list beyond index 0");if(n>0){for(let i=t-1;i>=0;i--)this.set(e+i+n,this.get(e+i));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r]}set(t,n){this._data[t*ve+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*ve+0]=t|2097152|n[2]<<22):this._data[t*ve+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*ve+0]>>22}hasWidth(t){return this._data[t*ve+0]&12582912}getFg(t){return this._data[t*ve+1]}getBg(t){return this._data[t*ve+2]}hasContent(t){return this._data[t*ve+0]&4194303}getCodePoint(t){let n=this._data[t*ve+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*ve+0]&2097152}getString(t){let n=this._data[t*ve+0];return n&2097152?this._combined[t]:n&2097151?Nr(n&2097151):""}isProtected(t){return this._data[t*ve+2]&536870912}loadCell(t,n){return Pa=t*ve,n.content=this._data[Pa+0],n.fg=this._data[Pa+1],n.bg=this._data[Pa+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*ve+0]=n.content,this._data[t*ve+1]=n.fg,this._data[t*ve+2]=n.bg}setCellFromCodepoint(t,n,r,i){i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ve+0]=n|r<<22,this._data[t*ve+1]=i.fg,this._data[t*ve+2]=i.bg}addCodepointToCell(t,n,r){let i=this._data[t*ve+0];i&2097152?this._combined[t]+=Nr(n):i&2097151?(this._combined[t]=Nr(i&2097151)+Nr(n),i&=-2097152,i|=2097152):i=n|1<<22,r&&(i&=-12582913,i|=r<<22),this._data[t*ve+0]=i}insertCells(t,n,r){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,r),n=0;--s)this.setCell(t+n+s,this.loadCell(t+s,i));for(let s=0;sthis.length){if(this._data.buffer.byteLength>=r*4)this._data=new Uint32Array(this._data.buffer,0,r);else{let i=new Uint32Array(r);i.set(this._data),this._data=i}for(let i=this.length;i=t&&delete this._combined[o]}let s=Object.keys(this._extendedAttrs);for(let l=0;l=t&&delete this._extendedAttrs[o]}}return this.length=t,r*4*pu=0;--t)if(this._data[t*ve+0]&4194303)return t+(this._data[t*ve+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ve+0]&4194303||this._data[t*ve+2]&50331648)return t+(this._data[t*ve+0]>>22);return 0}copyCellsFrom(t,n,r,i,s){let l=t._data;if(s)for(let c=i-1;c>=0;c--){for(let u=0;u=n&&(this._combined[u-n+r]=t._combined[u])}}translateToString(t,n,r,i){n=n??0,r=r??this.length,t&&(r=Math.min(r,this.getTrimmedLength())),i&&(i.length=0);let s="";for(;n>22||1}return i&&i.push(n),s}};function sN(e,t,n,r,i,s){let l=[];for(let o=0;o=o&&r0&&(w>d||h[w].getTrimmedLength()===0);w--)x++;x>0&&(l.push(o+h.length-x),l.push(x)),o+=h.length-1}return l}function lN(e,t){let n=[],r=0,i=t[r],s=0;for(let l=0;l$l(e,u,t)).reduce((c,u)=>c+u),s=0,l=0,o=0;for(;oc&&(s-=c,l++);let u=e[l].getWidth(s-1)===2;u&&s--;let h=u?n-1:n;r.push(h),o+=h}return r}function $l(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Yb=class Xb{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Xb._nextId++,this._onDispose=this.register(new ne),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),wi(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Yb._nextId=1;var cN=Yb,ut={},si=ut.B;ut[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ut.A={"#":"£"};ut.B=void 0;ut[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ut.C=ut[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ut.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ut.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ut.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ut.E=ut[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ut.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ut.H=ut[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var jg=4294967295,Ng=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=nt.clone(),this.savedCharset=si,this.markers=[],this._nullCell=bn.fromCharData([0,fb,1,0]),this._whitespaceCell=bn.fromCharData([0,Rr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ko,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Cg(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Ho),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Ho),this._whitespaceCell}getBlankLine(e,t){return new ll(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&ejg?jg:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=nt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Cg(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(nt),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+s+1?(this.ybase--,s++,this.ydisp>0&&this.ydisp--):this.lines.push(new ll(e,n)));else for(let l=this._rows;l>t;l--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),s&&(this.y+=s),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let s=0;s.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=sN(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(nt),n);if(r.length>0){let i=lN(this.lines,r);aN(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(nt),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let o=this.lines.get(l);if(!o||!o.isWrapped&&o.getTrimmedLength()<=e)continue;let c=[o];for(;o.isWrapped&&l>0;)o=this.lines.get(--l),c.unshift(o);if(!n){let y=this.ybase+this.y;if(y>=l&&y0&&(i.push({start:l+c.length+s,newLines:p}),s+=p.length),c.push(...p);let m=h.length-1,x=h[m];x===0&&(m--,x=h[m]);let w=c.length-d-1,v=u;for(;w>=0;){let y=Math.min(v,x);if(c[m]===void 0)break;if(c[m].copyCellsFrom(c[w],v-y,x-y,y,!0),x-=y,x===0&&(m--,x=h[m]),v-=y,v===0){w--;let b=Math.max(w,0);v=$l(c,b,this._cols)}}for(let y=0;y0;)this.ybase===0?this.y0){let l=[],o=[];for(let x=0;x=0;x--)if(d&&d.start>u+f){for(let w=d.newLines.length-1;w>=0;w--)this.lines.set(x--,d.newLines[w]);x++,l.push({index:u+1,amount:d.newLines.length}),f+=d.newLines.length,d=i[++h]}else this.lines.set(x,o[u--]);let p=0;for(let x=l.length-1;x>=0;x--)l[x].index+=p,this.lines.onInsertEmitter.fire(l[x]),p+=l[x].amount;let m=Math.max(0,c+s-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.linen.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},uN=class extends _e{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ne),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ng(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ng(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Qb=2,Jb=1,Ch=class extends _e{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Qb),this.rows=Math.max(e.rawOptions.rows||0,Jb),this.buffers=this._register(new uN(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,s=n.ybase+n.scrollBottom;if(n.scrollTop===0){let l=n.lines.isFull;s===n.lines.length-1?l?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(s+1,0,r.clone()),l?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let l=s-i+1;n.lines.shiftElements(i+1,l-1,-1),n.lines.set(s,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Ch=Qe([se(0,$t)],Ch);var Li={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Vo,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},dN=["normal","bold","100","200","300","400","500","600","700","800","900"],hN=class extends _e{constructor(e){super(),this._onOptionChange=this._register(new ne),this.onOptionChange=this._onOptionChange.event;let t={...Li};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(r){console.error(r)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register($e(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=n=>{if(!(n in Li))throw new Error(`No option with key "${n}"`);return this.rawOptions[n]},t=(n,r)=>{if(!(n in Li))throw new Error(`No option with key "${n}"`);r=this._sanitizeAndValidateOption(n,r),this.rawOptions[n]!==r&&(this.rawOptions[n]=r,this._onOptionChange.fire(n))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Li[e]),!fN(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Li[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=dN.includes(t)?t:Li[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function fN(e){return e==="block"||e==="underline"||e==="bar"}function al(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&al(e[r],t-1);return n}var Eg=Object.freeze({insertMode:!1}),Pg=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),jh=class extends _e{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ne),this.onData=this._onData.event,this._onUserInput=this._register(new ne),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ne),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=al(Eg),this.decPrivateModes=al(Pg)}reset(){this.modes=al(Eg),this.decPrivateModes=al(Pg)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(r=>r.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};jh=Qe([se(0,Ft),se(1,vb),se(2,$t)],jh);var Ag={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function mu(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var gu=String.fromCharCode,Tg={DEFAULT:e=>{let t=[mu(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${gu(t[0])}${gu(t[1])}${gu(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${mu(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${mu(e,!0)};${e.x};${e.y}${t}`}},Nh=class extends _e{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ne),this.onProtocolChange=this._onProtocolChange.event;for(let r of Object.keys(Ag))this.addProtocol(r,Ag[r]);for(let r of Object.keys(Tg))this.addEncoding(r,Tg[r]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Nh=Qe([se(0,Ft),se(1,Ni),se(2,$t)],Nh);var xu=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],pN=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],lt;function mN(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let i=di.extractWidth(t);i===0?r=!1:i>n&&(n=i)}return di.createPropertyValue(0,n,r)}},di=class ho{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ne,this.onChange=this._onChange.event;let t=new gN;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,r=!1){return(t&16777215)<<3|(n&3)<<1|(r?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let s=0;s=i)return n+this.wcwidth(l);let u=t.charCodeAt(s);56320<=u&&u<=57343?l=(l-55296)*1024+u-56320+65536:n+=this.wcwidth(u)}let o=this.charProperties(l,r),c=ho.extractWidth(o);ho.extractShouldJoin(o)&&(c-=ho.extractWidth(r)),n+=c,r=o}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},xN=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Lg(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Fs=2147483647,vN=256,Zb=class Eh{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>vN)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new Eh;if(!t.length)return n;for(let r=Array.isArray(t[0])?1:0;r>8,i=this._subParamsIdx[n]&255;i-r>0&&t.push(Array.prototype.slice.call(this._subParams,r,i))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Fs?Fs:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Fs?Fs:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;return r-n>0?this._subParams.subarray(n,r):null}getSubParamsAll(){let t={};for(let n=0;n>8,i=this._subParamsIdx[n]&255;i-r>0&&(t[n]=this._subParams.slice(r,i))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,i=r[n-1];r[n-1]=~i?Math.min(i*10+t,Fs):t}},$s=[],_N=class{constructor(){this._state=0,this._active=$s,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=$s}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=$s,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||$s,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,"PUT",bc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=$s,this._id=-1,this._state=0}}},en=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=bc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(n=>(this._data="",this._hitLimit=!1,n));return this._data="",this._hitLimit=!1,t}},Ws=[],yN=class{constructor(){this._handlers=Object.create(null),this._active=Ws,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Ws}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Ws,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Ws,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let n=this._active.length-1;n>=0;n--)this._active[n].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,"PUT",bc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Ws,this._ident=0}},ol=new Zb;ol.addParam(0);var Dg=class{constructor(e){this._handler=e,this._data="",this._params=ol,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ol,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=bc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=ol,this._data="",this._hitLimit=!1,n));return this._params=ol,this._data="",this._hitLimit=!1,t}},bN=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;ic),n=(o,c)=>t.slice(o,c),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let s=n(0,14),l;e.setDefault(1,0),e.addMany(r,0,2,0);for(l in s)e.addMany([24,26,153,154],l,3,0),e.addMany(n(128,144),l,3,0),e.addMany(n(144,152),l,3,0),e.add(156,l,0,0),e.add(27,l,11,1),e.add(157,l,4,8),e.addMany([152,158,159],l,0,7),e.add(155,l,11,3),e.add(144,l,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(mn,0,2,0),e.add(mn,8,5,8),e.add(mn,6,0,6),e.add(mn,11,0,11),e.add(mn,13,13,13),e}(),SN=class extends _e{constructor(e=wN){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Zb,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,n,r)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,n)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register($e(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new _N),this._dcsParser=this._register(new yN),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let i=0;is||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");n<<=8,n|=s}}if(e.final.length!==1)throw new Error("final must be a single byte");let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let i=r.indexOf(t);i!==-1&&r.splice(i,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let i=r.indexOf(t);i!==-1&&r.splice(i,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,s=0,l;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,s=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let o=this._parseStack.handlers,c=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&c>-1){for(;c>=0&&(l=o[c](this._params),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 4:if(n===!1&&c>-1){for(;c>=0&&(l=o[c](),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],l=this._dcsParser.unhook(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],l=this._oscParser.end(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,s=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let o=s;o>4){case 2:for(let f=o+1;;++f){if(f>=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=0&&(l=c[u](this._params),l!==!0);u--)if(l instanceof Promise)return this._preserveStack(3,c,u,i,o),l;u<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++o47&&r<60);o--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let h=this._escHandlers[this._collect<<8|r],d=h?h.length-1:-1;for(;d>=0&&(l=h[d](),l!==!0);d--)if(l instanceof Promise)return this._preserveStack(4,h,d,i,o),l;d<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let f=o+1;;++f)if(f>=t||(r=e[f])===24||r===26||r===27||r>127&&r=t||(r=e[f])<32||r>127&&r>4:s>>8}return r}}function vu(e,t){let n=e.toString(16),r=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function jN(e,t=16){let[n,r,i]=e;return`rgb:${vu(n,t)}/${vu(r,t)}/${vu(i,t)}`}var NN={"(":0,")":1,"*":2,"+":3,"-":1,".":2},wr=131072,Mg=10;function Ig(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Og=5e3,Bg=0,EN=class extends _e{constructor(e,t,n,r,i,s,l,o,c=new SN){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=s,this._coreMouseService=l,this._unicodeService=o,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new K1,this._utf8Decoder=new G1,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone(),this._onRequestBell=this._register(new ne),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ne),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ne),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ne),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ne),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ne),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ne),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ne),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ne),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Ph(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,h)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:h.toArray()})}),this._parser.setEscHandlerFallback(u=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(u)})}),this._parser.setExecuteHandlerFallback(u=>{this._logService.debug("Unknown EXECUTE code: ",{code:u})}),this._parser.setOscHandlerFallback((u,h,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:h,data:d})}),this._parser.setDcsHandlerFallback((u,h,d)=>{h==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:h,payload:d})}),this._parser.setPrintHandler((u,h,d)=>this.print(u,h,d)),this._parser.registerCsiHandler({final:"@"},u=>this.insertChars(u)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},u=>this.scrollLeft(u)),this._parser.registerCsiHandler({final:"A"},u=>this.cursorUp(u)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},u=>this.scrollRight(u)),this._parser.registerCsiHandler({final:"B"},u=>this.cursorDown(u)),this._parser.registerCsiHandler({final:"C"},u=>this.cursorForward(u)),this._parser.registerCsiHandler({final:"D"},u=>this.cursorBackward(u)),this._parser.registerCsiHandler({final:"E"},u=>this.cursorNextLine(u)),this._parser.registerCsiHandler({final:"F"},u=>this.cursorPrecedingLine(u)),this._parser.registerCsiHandler({final:"G"},u=>this.cursorCharAbsolute(u)),this._parser.registerCsiHandler({final:"H"},u=>this.cursorPosition(u)),this._parser.registerCsiHandler({final:"I"},u=>this.cursorForwardTab(u)),this._parser.registerCsiHandler({final:"J"},u=>this.eraseInDisplay(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},u=>this.eraseInDisplay(u,!0)),this._parser.registerCsiHandler({final:"K"},u=>this.eraseInLine(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},u=>this.eraseInLine(u,!0)),this._parser.registerCsiHandler({final:"L"},u=>this.insertLines(u)),this._parser.registerCsiHandler({final:"M"},u=>this.deleteLines(u)),this._parser.registerCsiHandler({final:"P"},u=>this.deleteChars(u)),this._parser.registerCsiHandler({final:"S"},u=>this.scrollUp(u)),this._parser.registerCsiHandler({final:"T"},u=>this.scrollDown(u)),this._parser.registerCsiHandler({final:"X"},u=>this.eraseChars(u)),this._parser.registerCsiHandler({final:"Z"},u=>this.cursorBackwardTab(u)),this._parser.registerCsiHandler({final:"`"},u=>this.charPosAbsolute(u)),this._parser.registerCsiHandler({final:"a"},u=>this.hPositionRelative(u)),this._parser.registerCsiHandler({final:"b"},u=>this.repeatPrecedingCharacter(u)),this._parser.registerCsiHandler({final:"c"},u=>this.sendDeviceAttributesPrimary(u)),this._parser.registerCsiHandler({prefix:">",final:"c"},u=>this.sendDeviceAttributesSecondary(u)),this._parser.registerCsiHandler({final:"d"},u=>this.linePosAbsolute(u)),this._parser.registerCsiHandler({final:"e"},u=>this.vPositionRelative(u)),this._parser.registerCsiHandler({final:"f"},u=>this.hVPosition(u)),this._parser.registerCsiHandler({final:"g"},u=>this.tabClear(u)),this._parser.registerCsiHandler({final:"h"},u=>this.setMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"h"},u=>this.setModePrivate(u)),this._parser.registerCsiHandler({final:"l"},u=>this.resetMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"l"},u=>this.resetModePrivate(u)),this._parser.registerCsiHandler({final:"m"},u=>this.charAttributes(u)),this._parser.registerCsiHandler({final:"n"},u=>this.deviceStatus(u)),this._parser.registerCsiHandler({prefix:"?",final:"n"},u=>this.deviceStatusPrivate(u)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},u=>this.softReset(u)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},u=>this.setCursorStyle(u)),this._parser.registerCsiHandler({final:"r"},u=>this.setScrollRegion(u)),this._parser.registerCsiHandler({final:"s"},u=>this.saveCursor(u)),this._parser.registerCsiHandler({final:"t"},u=>this.windowOptions(u)),this._parser.registerCsiHandler({final:"u"},u=>this.restoreCursor(u)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},u=>this.insertColumns(u)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},u=>this.deleteColumns(u)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},u=>this.selectProtected(u)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},u=>this.requestMode(u,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},u=>this.requestMode(u,!1)),this._parser.setExecuteHandler(K.BEL,()=>this.bell()),this._parser.setExecuteHandler(K.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(K.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(K.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(K.BS,()=>this.backspace()),this._parser.setExecuteHandler(K.HT,()=>this.tab()),this._parser.setExecuteHandler(K.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(K.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(co.IND,()=>this.index()),this._parser.setExecuteHandler(co.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(co.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new en(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new en(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new en(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new en(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new en(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new en(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new en(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new en(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new en(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new en(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new en(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new en(u=>this.restoreCursorColor(u))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let u in ut)this._parser.registerEscHandler({intermediates:"(",final:u},()=>this.selectCharset("("+u)),this._parser.registerEscHandler({intermediates:")",final:u},()=>this.selectCharset(")"+u)),this._parser.registerEscHandler({intermediates:"*",final:u},()=>this.selectCharset("*"+u)),this._parser.registerEscHandler({intermediates:"+",final:u},()=>this.selectCharset("+"+u)),this._parser.registerEscHandler({intermediates:"-",final:u},()=>this.selectCharset("-"+u)),this._parser.registerEscHandler({intermediates:".",final:u},()=>this.selectCharset("."+u)),this._parser.registerEscHandler({intermediates:"/",final:u},()=>this.selectCharset("/"+u));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(u=>(this._logService.error("Parsing error: ",u),u)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Dg((u,h)=>this.requestStatusString(u,h)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),Og))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Og} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,s=0,l=this._parseStack.paused;if(l){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>wr&&(s=this._parseStack.position+wr)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,u=>String.fromCharCode(u)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(u=>u.charCodeAt(0)):e),this._parseBuffer.lengthwr)for(let u=s;u0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let f=this._parser.precedingJoinState;for(let p=t;po){if(c){let v=d,_=this._activeBuffer.x-w;for(this._activeBuffer.x=w,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),w>0&&d instanceof ll&&d.copyCellsFrom(v,_,0,w,!1);_=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(u&&(d.insertCells(this._activeBuffer.x,i-w,this._activeBuffer.getNullCell(h)),d.getWidth(o-1)===2&&d.setCellFromCodepoint(o-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,h),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>Ig(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Dg(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new en(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(s.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=o;for(let u=1;u0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(K.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(K.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(K.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(K.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(K.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(x[x.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",x[x.SET=1]="SET",x[x.RESET=2]="RESET",x[x.PERMANENTLY_SET=3]="PERMANENTLY_SET",x[x.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:s}=this._coreMouseService,l=this._coreService,{buffers:o,cols:c}=this._bufferService,{active:u,alt:h}=o,d=this._optionsService.rawOptions,f=(x,w)=>(l.triggerDataEvent(`${K.ESC}[${t?"":"?"}${x};${w}$y`),!0),p=x=>x?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(l.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:c===132?1:0:0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i==="X10")):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!l.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i==="VT200")):m===1002?f(m,p(i==="DRAG")):m===1003?f(m,p(i==="ANY")):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(s==="SGR")):m===1015?f(m,4):m===1016?f(m,p(s==="SGR_PIXELS")):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(u===h)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Xl.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,s=0;do{if(r[s+i]=e.params[t+s],e.hasSubParams(t+s)){let l=e.getSubParams(t+s),o=0;do r[1]===5&&(i=1),r[s+o+1+i]=l[o];while(++o=2||r[1]===2&&s+i>=5)break;r[1]&&(i=1)}while(++s+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=nt.fg,e.bg=nt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777216|n-90|8):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777216|n-100|8):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=nt.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=nt.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=nt.fg&16777215,r.bg&=-67108864,r.bg|=nt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${K.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${K.ESC}[?${t};${n}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=nt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ig(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${K.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Mg&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Mg&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let r=n.shift(),i=n.shift();if(/^\d+$/.exec(r)){let s=parseInt(r);if(zg(s))if(i==="?")t.push({type:0,index:s});else{let l=Rg(i);l&&t.push({type:1,index:s,color:l})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),r,i=n.findIndex(s=>s.startsWith("id="));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let r=0;r=this._specialColors.length);++r,++t)if(n[r]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let i=Rg(n[r]);i&&this._onColor.fire([{type:1,index:this._specialColors[t],color:i}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let r=0;r=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new bn;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${K.ESC}${l}${K.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-(i.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ph=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Bg=e,e=t,t=Bg),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ph=Qe([se(0,Ft)],Ph);function zg(e){return 0<=e&&e<256}var PN=5e7,Fg=12,AN=50,TN=class extends _e{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>PN)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let r=this._writeBuffer[this._bufferOffset],i=this._action(r,t);if(i){let l=o=>performance.now()-n>=Fg?setTimeout(()=>this._innerWrite(0,o)):this._innerWrite(n,o);i.catch(o=>(queueMicrotask(()=>{throw o}),Promise.resolve(!1))).then(l);return}let s=this._callbacks[this._bufferOffset];if(s&&s(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-n>=Fg)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>AN&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Ah=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let o=t.addMarker(t.ybase+t.y),c={data:e,id:this._nextId++,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._dataByLinkId.set(c.id,c),c.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let s=t.addMarker(t.ybase+t.y),l={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(l,s)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(r=>r.line!==t)){let r=this._bufferService.buffer.addMarker(t);n.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(n,r))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Ah=Qe([se(0,Ft)],Ah);var $g=!1,LN=class extends _e{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new gs),this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onData=this._register(new ne),this.onData=this._onData.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ne),this._instantiationService=new nN,this.optionsService=this._register(new hN(e)),this._instantiationService.setService($t,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Ch)),this._instantiationService.setService(Ft,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(kh)),this._instantiationService.setService(vb,this._logService),this.coreService=this._register(this._instantiationService.createInstance(jh)),this._instantiationService.setService(Ni,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Nh)),this._instantiationService.setService(xb,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(di)),this._instantiationService.setService(J1,this.unicodeService),this._charsetService=this._instantiationService.createInstance(xN),this._instantiationService.setService(Q1,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Ah),this._instantiationService.setService(_b,this._oscLinkService),this._inputHandler=this._register(new EN(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(bt.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(bt.forward(this._bufferService.onResize,this._onResize)),this._register(bt.forward(this.coreService.onData,this._onData)),this._register(bt.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new TN((t,n)=>this._inputHandler.parse(t,n))),this._register(bt.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ne),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!$g&&(this._logService.warn("writeSync is unreliable and will be removed soon."),$g=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Qb),t=Math.max(t,Jb),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Lg.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Lg(this._bufferService),!1))),this._windowsWrappingHeuristics.value=$e(()=>{for(let t of e)t.dispose()})}}},DN={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function RN(e,t,n,r){let i={type:0,cancel:!1,key:void 0},s=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?i.key=K.ESC+"OA":i.key=K.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?i.key=K.ESC+"OD":i.key=K.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?i.key=K.ESC+"OC":i.key=K.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?i.key=K.ESC+"OB":i.key=K.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":K.DEL,e.altKey&&(i.key=K.ESC+i.key);break;case 9:if(e.shiftKey){i.key=K.ESC+"[Z";break}i.key=K.HT,i.cancel=!0;break;case 13:i.key=e.altKey?K.ESC+K.CR:K.CR,i.cancel=!0;break;case 27:i.key=K.ESC,e.altKey&&(i.key=K.ESC+K.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;s?i.key=K.ESC+"[1;"+(s+1)+"D":t?i.key=K.ESC+"OD":i.key=K.ESC+"[D";break;case 39:if(e.metaKey)break;s?i.key=K.ESC+"[1;"+(s+1)+"C":t?i.key=K.ESC+"OC":i.key=K.ESC+"[C";break;case 38:if(e.metaKey)break;s?i.key=K.ESC+"[1;"+(s+1)+"A":t?i.key=K.ESC+"OA":i.key=K.ESC+"[A";break;case 40:if(e.metaKey)break;s?i.key=K.ESC+"[1;"+(s+1)+"B":t?i.key=K.ESC+"OB":i.key=K.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=K.ESC+"[2~");break;case 46:s?i.key=K.ESC+"[3;"+(s+1)+"~":i.key=K.ESC+"[3~";break;case 36:s?i.key=K.ESC+"[1;"+(s+1)+"H":t?i.key=K.ESC+"OH":i.key=K.ESC+"[H";break;case 35:s?i.key=K.ESC+"[1;"+(s+1)+"F":t?i.key=K.ESC+"OF":i.key=K.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=K.ESC+"[5;"+(s+1)+"~":i.key=K.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=K.ESC+"[6;"+(s+1)+"~":i.key=K.ESC+"[6~";break;case 112:s?i.key=K.ESC+"[1;"+(s+1)+"P":i.key=K.ESC+"OP";break;case 113:s?i.key=K.ESC+"[1;"+(s+1)+"Q":i.key=K.ESC+"OQ";break;case 114:s?i.key=K.ESC+"[1;"+(s+1)+"R":i.key=K.ESC+"OR";break;case 115:s?i.key=K.ESC+"[1;"+(s+1)+"S":i.key=K.ESC+"OS";break;case 116:s?i.key=K.ESC+"[15;"+(s+1)+"~":i.key=K.ESC+"[15~";break;case 117:s?i.key=K.ESC+"[17;"+(s+1)+"~":i.key=K.ESC+"[17~";break;case 118:s?i.key=K.ESC+"[18;"+(s+1)+"~":i.key=K.ESC+"[18~";break;case 119:s?i.key=K.ESC+"[19;"+(s+1)+"~":i.key=K.ESC+"[19~";break;case 120:s?i.key=K.ESC+"[20;"+(s+1)+"~":i.key=K.ESC+"[20~";break;case 121:s?i.key=K.ESC+"[21;"+(s+1)+"~":i.key=K.ESC+"[21~";break;case 122:s?i.key=K.ESC+"[23;"+(s+1)+"~":i.key=K.ESC+"[23~";break;case 123:s?i.key=K.ESC+"[24;"+(s+1)+"~":i.key=K.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=K.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=K.DEL:e.keyCode===219?i.key=K.ESC:e.keyCode===220?i.key=K.FS:e.keyCode===221&&(i.key=K.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let l=DN[e.keyCode]?.[e.shiftKey?1:0];if(l)i.key=K.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){let o=e.ctrlKey?e.keyCode-64:e.keyCode+32,c=String.fromCharCode(o);e.shiftKey&&(c=c.toUpperCase()),i.key=K.ESC+c}else if(e.keyCode===32)i.key=K.ESC+(e.ctrlKey?K.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let o=e.code.slice(3,4);e.shiftKey||(o=o.toLowerCase()),i.key=K.ESC+o,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(i.key=K.US),e.key==="@"&&(i.key=K.NUL));break}return i}var Je=0,MN=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ko,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ko,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((i,s)=>this._getKey(i)-this._getKey(s)),t=0,n=0,r=new Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Je=this._search(t),Je===-1)||this._getKey(this._array[Je])!==t)return!1;do if(this._array[Je]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Je),!0;while(++Jei-s),t=0,n=new Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Je=this._search(e),!(Je<0||Je>=this._array.length)&&this._getKey(this._array[Je])===e))do yield this._array[Je];while(++Je=this._array.length)&&this._getKey(this._array[Je])===e))do t(this._array[Je]);while(++Je=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},_u=0,Wg=0,IN=class extends _e{constructor(){super(),this._decorations=new MN(e=>e?.marker.line),this._onDecorationRegistered=this._register(new ne),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ne),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register($e(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new ON(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),r=t.onDispose(()=>{r.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let s of this._decorations.getKeyIterator(t))r=s.options.x??0,i=r+(s.options.width??1),e>=r&&e{_u=i.options.x??0,Wg=_u+(i.options.width??1),e>=_u&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let i=r-this._lastRefreshMs,s=this._debounceThresholdMS-i;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},s)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Hg=20,Go=class extends _e{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=i.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let s=0;sthis._handleBoundaryFocus(s,0),this._bottomBoundaryFocusListener=s=>this._handleBoundaryFocus(s,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new zN(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(s=>this._handleResize(s.rows))),this._register(this._terminal.onRender(s=>this._refreshRows(s.start,s.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(s=>this._handleChar(s))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(s=>this._handleTab(s))),this._register(this._terminal.onKey(s=>this._handleKey(s.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(fe(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register($e(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Hg+1&&(this._liveRegion.textContent+=Xd.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let s=n.lines.get(n.ydisp+i),l=[],o=s?.translateToString(!0,void 0,void 0,l)||"",c=(n.ydisp+i+1).toString(),u=this._rowElements[i];u&&(o.length===0?(u.textContent=" ",this._rowColumns.set(u,[0,1])):(u.textContent=o,this._rowColumns.set(u,l)),u.setAttribute("aria-posinset",c),u.setAttribute("aria-setsize",r),this._alignRowWidth(u))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],i=n.getAttribute("aria-posinset"),s=t===0?"1":`${this._terminal.buffer.lines.length}`;if(i===s||e.relatedTarget!==r)return;let l,o;if(t===0?(l=n,o=this._rowElements.pop(),this._rowContainer.removeChild(o)):(l=this._rowElements.shift(),o=n,this._rowContainer.removeChild(l)),l.removeEventListener("focus",this._topBoundaryFocusListener),o.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let c=this._createAccessibilityTreeNode();this._rowElements.unshift(c),this._rowContainer.insertAdjacentElement("afterbegin",c)}else{let c=this._createAccessibilityTreeNode();this._rowElements.push(c),this._rowContainer.appendChild(c)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:o,offset:c})=>{let u=o instanceof Text?o.parentNode:o,h=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(h))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(u);if(!d)return console.warn("columns is null. Race condition?"),null;let f=c=this._terminal.cols&&(++h,f=0),{row:h,column:f}},s=i(t),l=i(n);if(!(!s||!l)){if(s.row>l.row||s.row===l.row&&s.column>=l.column)throw new Error("invalid range");this._terminal.select(s.column,s.row,(l.row-s.row)*this._terminal.cols-s.column+l.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{wi(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(fe(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(fe(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(fe(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(fe(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let r=0;r{r?.forEach(i=>{i.link.dispose&&i.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,s=>{if(this._isMouseOut)return;let l=s?.map(o=>({link:o}));this._activeProviderReplies?.set(r,l),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:l.link.range.end.x;for(let u=o;u<=c;u++){if(n.has(u)){i.splice(s--,1);break}n.add(u)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let s=0;sthis._linkAtPosition(l.link,t));s&&(n=!0,this._handleNewLink(s))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let s=0;sthis._linkAtPosition(o.link,t));if(l){n=!0,this._handleNewLink(l);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&FN(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,wi(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let r=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(r,i),this._lastMouseEvent)){let s=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);s&&this._askForLink(s,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Th=Qe([se(1,Qf),se(2,gr),se(3,Ft),se(4,bb)],Th);function FN(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var $N=class extends LN{constructor(e={}){super(e),this._linkifier=this._register(new gs),this.browser=Fb,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new gs),this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ne),this.onKey=this._onKey.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ne),this.onBell=this._onBell.event,this._onFocus=this._register(new ne),this._onBlur=this._register(new ne),this._onA11yCharEmitter=this._register(new ne),this._onA11yTabEmitter=this._register(new ne),this._onWillOpen=this._register(new ne),this._setup(),this._decorationService=this._instantiationService.createInstance(IN),this._instantiationService.setService(Ql,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Aj),this._instantiationService.setService(bb,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Jd)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(bt.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(bt.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(bt.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(bt.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register($e(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let n,r="";switch(t.index){case 256:n="foreground",r="10";break;case 257:n="background",r="11";break;case 258:n="cursor",r="12";break;default:n="ansi",r="4;"+t.index}switch(t.type){case 0:let i=Be.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${K.ESC}]${r};${jN(i)}${Bb.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(s=>s.ansi[t.index]=rt.toColor(...t.color));else{let s=n;this._themeService.modifyColors(l=>l[s]=rt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Go,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),s=this._renderService.dimensions.css.cell.width*i,l=this.buffer.y*this._renderService.dimensions.css.cell.height,o=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=o+"px",this.textarea.style.top=l+"px",this.textarea.style.width=s+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(fe(this.element,"copy",t=>{this.hasSelection()&&q1(t,this._selectionService)}));let e=t=>V1(t,this.textarea,this.coreService,this.optionsService);this._register(fe(this.textarea,"paste",e)),this._register(fe(this.element,"paste",e)),$b?this._register(fe(this.element,"mousedown",t=>{t.button===2&&Zm(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(fe(this.element,"contextmenu",t=>{Zm(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),sp&&this._register(fe(this.element,"auxclick",t=>{t.button===1&&hb(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(fe(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(fe(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(fe(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(fe(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(fe(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(fe(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(fe(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(fe(this.screenElement,"mousemove",i=>this.updateCursorStyle(i))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Yd.get()),Ub||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Ej,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(mr,this._coreBrowserService),this._register(fe(this.textarea,"focus",i=>this._handleTextAreaFocus(i))),this._register(fe(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(_h,this._document,this._helperContainer),this._instantiationService.setService(wc,this._charSizeService),this._themeService=this._instantiationService.createInstance(Sh),this._instantiationService.setService(ws,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(qo),this._instantiationService.setService(yb,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(bh,this.rows,this.screenElement)),this._instantiationService.setService(gr,this._renderService),this._register(this._renderService.onRenderedViewportChange(i=>this._onRender.fire(i))),this.onResize(i=>this._renderService.resize(i.cols,i.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(gh,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(yh),this._instantiationService.setService(Qf,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Th,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ph,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(i=>{super.scrollLines(i,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(wh,this.element,this.screenElement,r)),this._instantiationService.setService(eC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(i=>this.scrollLines(i.amount,i.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(i=>this._renderService.handleSelectionChanged(i.start,i.end,i.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(i=>{this.textarea.value=i,this.textarea.focus(),this.textarea.select()})),this._register(bt.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(mh,this.screenElement)),this._register(fe(this.element,"mousedown",i=>this._selectionService.handleMouseDown(i))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Go,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",i=>this._handleScreenReaderModeOptionChange(i))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Uo,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",i=>{!this._overviewRulerRenderer&&i&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Uo,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(vh,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(s){let l=e._mouseService.getMouseReportCoords(s,e.screenElement);if(!l)return!1;let o,c;switch(s.overrideType||s.type){case"mousemove":c=32,s.buttons===void 0?(o=3,s.button!==void 0&&(o=s.button<3?s.button:3)):o=s.buttons&1?0:s.buttons&4?1:s.buttons&2?2:3;break;case"mouseup":c=0,o=s.button<3?s.button:3;break;case"mousedown":c=1,o=s.button<3?s.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(s)===!1)return!1;let u=s.deltaY;if(u===0||e.coreMouseService.consumeWheelEvent(s,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;c=u<0?0:1,o=4;break;default:return!1}return c===void 0||o===void 0||o>4?!1:e.coreMouseService.triggerMouseEvent({col:l.col,row:l.row,x:l.x,y:l.y,button:o,action:c,ctrl:s.ctrlKey,alt:s.altKey,shift:s.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:s=>(n(s),s.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(s)),wheel:s=>(n(s),this.cancel(s,!0)),mousedrag:s=>{s.buttons&&n(s)},mousemove:s=>{s.buttons||n(s)}};this._register(this.coreMouseService.onProtocolChange(s=>{s?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(s)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),s&8?r.mousemove||(t.addEventListener("mousemove",i.mousemove),r.mousemove=i.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),s&16?r.wheel||(t.addEventListener("wheel",i.wheel,{passive:!1}),r.wheel=i.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),s&2?r.mouseup||(r.mouseup=i.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),s&4?r.mousedrag||(r.mousedrag=i.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(fe(t,"mousedown",s=>{if(s.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(s)))return n(s),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(s)})),this._register(fe(t,"wheel",s=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(s)===!1)return!1;if(!this.buffer.hasScrollback){if(s.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(s,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(s,!0);let l=K.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(s.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(l,!0),this.cancel(s,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){db(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=RN(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let r=this.rows-1;return this.scrollLines(n.type===2?-r:r),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===K.ETX||n.key===K.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(WN(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new bn)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Ug=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new UN(t)}getNullCell(){return new bn}},qN=class extends _e{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ne),this.onBufferChange=this._onBufferChange.event,this._normal=new Ug(this._core.buffers.normal,"normal"),this._alternate=new Ug(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},VN=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,r)=>t(n,r.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},KN=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},GN=["cols","rows"],On=0,YN=class extends _e{constructor(e){super(),this._core=this._register(new $N(e)),this._addonManager=this._register(new HN),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],n=(r,i)=>{this._checkReadonlyOptions(r),this._core.options[r]=i};for(let r in this._core.options){let i={get:t.bind(this,r),set:n.bind(this,r)};Object.defineProperty(this._publicOptions,r,i)}}_checkReadonlyOptions(e){if(GN.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new VN(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new KN(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new qN(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Yd.get()},set promptLabel(e){Yd.set(e)},get tooMuchOutput(){return Xd.get()},set tooMuchOutput(e){Xd.set(e)}}}_verifyIntegers(...e){for(On of e)if(On===1/0||isNaN(On)||On%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(On of e)if(On&&(On===1/0||isNaN(On)||On%1!==0||On<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var XN=2,QN=1,JN=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),i=Math.max(0,parseInt(n.getPropertyValue("width"))),s=window.getComputedStyle(this._terminal.element),l={top:parseInt(s.getPropertyValue("padding-top")),bottom:parseInt(s.getPropertyValue("padding-bottom")),right:parseInt(s.getPropertyValue("padding-right")),left:parseInt(s.getPropertyValue("padding-left"))},o=l.top+l.bottom,c=l.right+l.left,u=r-o,h=i-c-t;return{cols:Math.max(XN,Math.floor(h/e.css.cell.width)),rows:Math.max(QN,Math.floor(u/e.css.cell.height))}}};function jt(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}function Hs(e,t,n,r,i){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Zr,fn,Di,Aa;const qg="__TAURI_TO_IPC_KEY__";function ew(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}class Wl{constructor(t){Zr.set(this,void 0),fn.set(this,0),Di.set(this,[]),Aa.set(this,void 0),Hs(this,Zr,t||(()=>{})),this.id=ew(n=>{const r=n.index;if("end"in n){r==jt(this,fn,"f")?this.cleanupCallback():Hs(this,Aa,r);return}const i=n.message;if(r==jt(this,fn,"f")){for(jt(this,Zr,"f").call(this,i),Hs(this,fn,jt(this,fn,"f")+1);jt(this,fn,"f")in jt(this,Di,"f");){const s=jt(this,Di,"f")[jt(this,fn,"f")];jt(this,Zr,"f").call(this,s),delete jt(this,Di,"f")[jt(this,fn,"f")],Hs(this,fn,jt(this,fn,"f")+1)}jt(this,fn,"f")===jt(this,Aa,"f")&&this.cleanupCallback()}else jt(this,Di,"f")[r]=i})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(t){Hs(this,Zr,t)}get onmessage(){return jt(this,Zr,"f")}[(Zr=new WeakMap,fn=new WeakMap,Di=new WeakMap,Aa=new WeakMap,qg)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[qg]()}}async function F(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}var Vg;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_SUSPENDED="tauri://suspended",e.WINDOW_RESUMED="tauri://resumed",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"})(Vg||(Vg={}));async function ZN(e,t){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,t),await F("plugin:event|unlisten",{event:e,eventId:t})}async function Yo(e,t,n){var r;const i=(r=void 0)!==null&&r!==void 0?r:{kind:"Any"};return F("plugin:event|listen",{event:e,target:i,handler:ew(t)}).then(s=>async()=>ZN(e,s))}async function Kg(e={}){return typeof e=="object"&&Object.freeze(e),await F("plugin:dialog|open",{options:e})}const eE="domain://event",tE="app-exit-work-guard";class nE{async health(t){return F("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await Yo(eE,r=>{t(r.payload)})}async pickFolder(){const t=await Kg({directory:!0,multiple:!1});return t==null?null:typeof t=="string"?t:null}async pickArchiveFile(){const t=await Kg({directory:!1,multiple:!1,filters:[{name:"Plugin archive",extensions:["ideaplug","zip","vsix"]}]});return typeof t=="string"?t:null}async onAppExitWorkGuard(t){return await Yo(tE,r=>{t(r.payload)})}async confirmAppExit(){await F("confirm_app_exit")}}function Xo(e,t){let n=Promise.resolve();return{sessionId:e,write(r){const i=n.then(async()=>{Gg("start",e,r),await F("write_terminal",{request:{sessionId:e,data:Array.from(r)}}),Gg("ok",e,r)});return n=i.catch(()=>{}),i},async resize(r,i){await F("resize_terminal",{request:{sessionId:e,rows:r,cols:i}})},detach(){t.onmessage=()=>{}},async close(){await F("close_terminal",{sessionId:e})}}}function Gg(e,t,n){n.length===1&&n[0]>=32&&n[0]!==127||console.info("[terminal-write]",e,{sessionId:t,bytes:n.length,control:rE(n)})}function rE(e){return e.length===0?"":e.length>16?"":Array.from(e).map(t=>{switch(t){case 13:return"\\r";case 10:return"\\n";case 127:return"\\x7f";default:return t<32?`\\x${t.toString(16).padStart(2,"0")}`:String.fromCharCode(t)}}).join("")}class iE{async openTerminal(t,n){const r=new Wl;r.onmessage=s=>n(Uint8Array.from(s));const i=await F("open_terminal",{request:{cwd:t.cwd,rows:t.rows,cols:t.cols},onOutput:r});return Xo(i.sessionId,r)}async reattach(t,n){const r=new Wl;r.onmessage=s=>n(Uint8Array.from(s));const i=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Xo(i.sessionId,r),scrollback:Uint8Array.from(i.scrollback)}}async closeTerminal(t){await F("close_terminal",{sessionId:t})}}class sE{listAgents(t){return F("list_agents",{projectId:t})}listLiveAgents(t){return F("list_live_agents",{projectId:t})}listResumableAgents(t){return F("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return F("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return F("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return F("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,i,s){return F("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:i,cols:s}})}readContext(t,n){return F("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await F("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await F("delete_agent",{projectId:t,agentId:n})}async launchAgent(t,n,r,i){const s=new Wl;s.onmessage=c=>i(Uint8Array.from(c));const l=await F("launch_agent",{request:{projectId:t,agentId:n,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,nodeId:r.nodeId??null},onOutput:s});return{...Xo(l.sessionId,s),...l.assignedConversationId?{assignedConversationId:l.assignedConversationId}:{}}}async reattach(t,n){const r=new Wl;r.onmessage=s=>n(Uint8Array.from(s));const i=await F("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Xo(i.sessionId,r),scrollback:Uint8Array.from(i.scrollback)}}inspectConversation(t,n,r){return F("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}}class lE{async interrupt(t,n){await F("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){console.info("[input-gateway] delegationDelivered:start",{projectId:t,agentId:n,ticket:r}),await F("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}}),console.info("[input-gateway] delegationDelivered:ok",{projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){console.info("[input-gateway] setFrontAttached:start",{agentId:t,attached:n}),await F("set_front_attached",{request:{agentId:t,attached:n}}),console.info("[input-gateway] setFrontAttached:ok",{agentId:t,attached:n})}async cancelResume(t){return F("cancel_resume",{agentId:t})}async setResumeAt(t,n){await F("set_resume_at",{agentId:t,resetsAtMs:n})}}class aE{listProjects(){return F("list_projects")}createProject(t,n){return F("create_project",{request:{name:t,root:n}})}openProject(t){return F("open_project",{projectId:t})}async closeProject(t){await F("close_project",{projectId:t})}readProjectContext(t){return F("read_project_context",{projectId:t})}async updateProjectContext(t,n){await F("update_project_context",{request:{projectId:t,content:n}})}}class oE{loadLayout(t,n){return F("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return F("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return F("list_layouts",{projectId:t})}createLayout(t,n,r){return F("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return F("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return F("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return F("set_active_layout",{request:{projectId:t,layoutId:n}})}}class cE{firstRunState(){return F("first_run_state")}referenceProfiles(){return F("reference_profiles")}detectProfiles(t){return F("detect_profiles",{request:{candidates:t}})}listProfiles(){return F("list_profiles")}saveProfile(t){return F("save_profile",{request:{profile:t}})}async deleteProfile(t){await F("delete_profile",{profileId:t})}configureProfiles(t){return F("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return F("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return F("list_opencode_providers")}saveOpenCodeProviderProfile(t){return F("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class uE{listModelServers(){return F("list_model_servers")}saveModelServer(t){return F("save_model_server",{request:{config:t}})}async deleteModelServer(t){await F("delete_model_server",{serverId:t})}previewModelServerCommand(t){return F("preview_model_server_command",{config:t})}}const dE=2e3;class hE{constructor(t=dE){this.pollMs=t}getExposureSettings(){return F("get_server_exposure_settings")}async saveExposureSettings(t){await F("save_server_exposure_settings",{settings:t})}previewExposure(t){return F("preview_server_exposure_settings",{settings:t})}status(){return F("embedded_server_status")}start(){return F("embedded_server_start")}stop(){return F("embedded_server_stop")}async onStatusChanged(t){let n=!1;const r=setInterval(()=>{this.status().then(i=>{n||t(i)},()=>{})},this.pollMs);return()=>{n=!0,clearInterval(r)}}}class fE{listTemplates(){return F("list_templates")}createTemplate(t){return F("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return F("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await F("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return F("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return F("detect_agent_drift",{projectId:t})}syncAgent(t,n){return F("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class pE{listSkills(t,n){return F("list_skills",{projectId:t,scope:n})}createSkill(t){return F("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,i){return F("update_skill",{request:{projectId:t,scope:n,skillId:r,content:i}})}async deleteSkill(t,n,r){await F("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,i){await F("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:i}})}async unassignSkill(t,n,r){await F("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class mE{listMemories(t){return F("list_memories",{projectId:t})}getMemory(t,n){return F("get_memory",{projectId:t,slug:n})}createMemory(t){return F("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,i,s){return F("update_memory",{request:{projectId:t,slug:n,description:r,type:i,content:s}})}async deleteMemory(t,n){await F("delete_memory",{projectId:t,slug:n})}readIndex(t){return F("read_memory_index",{projectId:t})}resolveLinks(t,n){return F("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return F("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class gE{listEmbedderProfiles(){return F("list_embedder_profiles")}saveEmbedderProfile(t){return F("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await F("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return F("describe_embedder_engines")}}class xE{async listDevices(){return(await F("list_devices")).devices}createPairingCode(){return F("create_pairing_code")}renameDevice(t,n){return F("rename_device",{request:{deviceId:t,name:n}})}revokeDevice(t){return F("revoke_device",{request:{deviceId:t}})}revokeAllDevices(){return F("revoke_all_devices")}}class vE{status(t){return F("git_status",{projectId:t})}async stage(t,n){await F("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await F("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return F("git_commit",{request:{projectId:t,message:n}})}branches(t){return F("git_branches",{projectId:t})}async checkout(t,n){await F("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return F("git_log",{projectId:t,limit:n})}async init(t){await F("git_init",{projectId:t})}graph(t,n){return F("git_graph",{projectId:t,limit:n})}}class _E{getProjectPermissions(t){return F("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return F("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return F("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return F("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return F("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return F("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return F("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}function Ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xe(e,t=""){return typeof e=="string"?e:t}function Yn(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function yE(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function mi(e){return Array.isArray(e)?e:[]}function Yg(e){return typeof e=="string"?e:void 0}function os(e){return typeof e=="string"?e:null}function tw(e){return Ln(e)?e.kind==="agent"?{kind:"agent",agentId:Xe(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function bE(e){return e==="inProgress"?"inProgress":"queued"}function wE(e){return Ln(e)&&e.state==="busy"?{state:"busy",ticket:Xe(e.ticket,"unknown"),sinceMs:Yn(e.sinceMs,0)}:{state:"idle"}}function SE(e,t){const n=Ln(e)?e:{},r=Xe(n.taskPreview);return{ticketId:Xe(n.ticketId,`legacy-ticket-${t}`),conversationId:Xe(n.conversationId),position:Yn(n.position,t),status:bE(n.status),source:tw(n.source),requesterLabel:Xe(n.requesterLabel),taskPreview:r,taskLen:Yn(n.taskLen,r.length)}}function kE(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="completed"||t==="success"||t==="succeeded"?"completed":t==="failed"||t==="failure"?"failed":t==="cancelled"||t==="canceled"||t==="expired"?"cancelled":t==="running"||t==="started"?"running":t==="delivered"?"delivered":"pending"}function CE(e,t,n){const r=Ln(e)?e:{};return{taskId:Xe(r.taskId,`legacy-task-${t}`),ownerAgentId:Xe(r.ownerAgentId,n),projectId:Xe(r.projectId),kind:Xe(r.kind,"background"),status:kE(r.status??r.state),exitCode:yE(r.exitCode),summary:os(r.summary),stdoutTail:os(r.stdoutTail),stderrTail:os(r.stderrTail),updatedAtMs:Yn(r.updatedAtMs)}}function nw(e,t,n){const r=Ln(e)?e:{};return{id:Xe(r.id,`legacy-inbox-${t}`),agentId:Xe(r.agentId??r.agent_id,n),source:Xe(r.source,"unknown"),kind:Xe(r.kind,"message"),body:Xe(r.body),createdAtMs:Yn(r.createdAtMs??r.created_at_ms,0),...Yg(r.correlationId??r.correlation_id)?{correlationId:Yg(r.correlationId??r.correlation_id)}:{},priority:Yn(r.priority,0)}}function jE(e,t){const n=Ln(e)?e:{},r=Ln(n.live)&&n.live.kind==="structured"?"structured":"pty",i=Ln(n.live)?{nodeId:Xe(n.live.nodeId),sessionId:Xe(n.live.sessionId),kind:r}:void 0,s=Xe(n.agentId,`legacy-agent-${t}`),l=mi(n.inbox).map((c,u)=>nw(c,u,s)),o=mi(n.backgroundTasks??n.backgroundCompletions).map((c,u)=>CE(c,u,s));return{agentId:s,name:Xe(n.name,"Unnamed agent"),profileId:Xe(n.profileId,"unknown"),...i?{live:i}:{},busy:wE(n.busy),tickets:mi(n.tickets).map(SE),inboxDepth:Yn(n.inboxDepth,l.length),inbox:l,backgroundTasks:o}}function NE(e){return e==="ready"||e==="partial"||e==="unavailable"||e==="missing"?e:"missing"}function EE(e,t){const n=Ln(e)?e:{},r=Xe(n.textPreview);return{role:n.role==="response"||n.role==="toolActivity"?n.role:"prompt",source:tw(n.source),atMs:Yn(n.atMs,t),textPreview:r,textLen:Yn(n.textLen,r.length)}}function PE(e,t){const n=Ln(e)?e:{};return{conversationId:Xe(n.conversationId,`legacy-conversation-${t}`),status:NE(n.status),objectivePreview:os(n.objectivePreview),summaryPreview:os(n.summaryPreview),summaryLen:Yn(n.summaryLen,0),upTo:os(n.upTo),recentTurns:mi(n.recentTurns).map(EE)}}function lp(e){const t=Ln(e)?e:{},n=mi(t.agents).map(jE),r=mi(t.inboxItems).map((i,s)=>nw(i,s,""));for(const i of r){const s=n.find(l=>l.agentId===i.agentId);s&&(s.inbox??=[],s.inboxDepth??=0,s.inbox.some(l=>l.id===i.id)||(s.inbox.push(i),s.inboxDepth=Math.max(s.inboxDepth,s.inbox.length)))}return{agents:n,conversations:mi(t.conversations).map(PE)}}class AE{async getProjectWorkState(t){const n=await F("get_project_work_state",{projectId:t});return lp(n)}async cancelBackgroundTask(t){await F("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await F("retry_background_task",{taskId:t})}}function ap(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lh(e,t=""){return typeof e=="string"?e:t}function Xg(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function TE(e){return Array.isArray(e)?e:[]}function LE(e){return ap(e)?e.kind==="agent"?{kind:"agent",agentId:Lh(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function DE(e){return e==="response"||e==="toolActivity"?e:"prompt"}function RE(e,t){const n=ap(e)?e:{},r=Lh(n.text);return{id:Lh(n.id,`turn-${t}`),atMs:Xg(n.atMs,t),role:DE(n.role),source:LE(n.source),text:r,textLen:Xg(n.textLen,r.length)}}function rw(e){const t=ap(e)?e:{},n=t.nextAnchor;return{turns:TE(t.turns).map(RE),hasMore:t.hasMore===!0,...typeof n=="string"?{nextAnchor:n}:{}}}class ME{async readPage(t,n,r){const i=await F("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return rw(i)}}class IE{async create(t,n){return F("ticket_create",{request:{projectId:t,...n}})}async read(t,n,r=!1){return F("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}async list(t,n){const{statuses:r,priorities:i,...s}=n??{};return F("ticket_list",{request:{projectId:t,statuses:r??[],priorities:i??[],...s}})}async update(t,n,r){return F("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await F("ticket_delete",{request:{projectId:t,ref:n}})}async readCarnet(t,n){return F("ticket_read_carnet",{request:{projectId:t,ref:n}})}async updateCarnet(t,n,r,i){return F("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:i}})}async link(t,n,r,i,s){return F("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:i,expectedVersion:s}})}async unlink(t,n,r,i,s){return F("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:i,kind:s}})}async assign(t,n,r,i,s){return F("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:i,expectedVersion:s}})}async listSprints(t){return(await F("sprint_list",{request:{projectId:t}})).items}async setTicketSprint(t,n,r,i){return r===null?F("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:i}}):F("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:i}})}async createSprint(t,n){return F("sprint_create",{request:{projectId:t,name:n}})}async renameSprint(t,n,r,i){return F("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:i}})}async reorderSprints(t,n){return(await F("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await F("sprint_delete",{request:{projectId:t,sprintId:n}})}async openTicketChat(t,n,r){return F("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await F("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const i=new Wl;i.onmessage=s=>r(s),await F("agent_send",{sessionId:t,prompt:n,onReply:i})}}const OE="view-window://lifecycle";class BE{async openViewWindow(t){await F("open_view_window",{panel:t})}async closeViewWindow(t){await F("close_view_window",{panel:t})}async listOpenViewWindows(){return F("list_open_view_windows")}async onViewWindowClosed(t){return await Yo(OE,r=>{r.payload.kind==="closed"&&t({panel:r.payload.panel})})}}const zE="focused-project://changed";class FE{async setFocusedProject(t){await F("set_focused_project",{project:t})}async getFocusedProject(){return await F("get_focused_project")??null}async onFocusedProjectChanged(t){return await Yo(zE,r=>t(r.payload.project??null))}}function yu(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}class iw{read(t){const n=yu();if(!n)return null;let r;try{r=n.getItem(t)}catch{return null}if(r===null)return null;try{return JSON.parse(r)}catch{try{n.removeItem(t)}catch{}return null}}write(t,n){const r=yu();if(r)try{r.setItem(t,JSON.stringify(n))}catch{}}remove(t){const n=yu();if(n)try{n.removeItem(t)}catch{}}}class $E{listPlugins(){return F("plugin_list_plugins")}reviewPackage(t){return F("plugin_review_package",{request:{sourceKind:t.sourceKind,path:t.path}})}installFromArchive(t){return F("plugin_install_from_archive",{path:t})}installFromDirectory(t){return F("plugin_install_from_directory",{path:t})}setEnabled(t,n){return F("plugin_set_enabled",{pluginId:t,enabled:n})}uninstall(t){return F("plugin_uninstall",{pluginId:t})}listRuntimeContributions(){return F("plugin_list_runtime_contributions")}async openPluginsFolder(t){await F("plugin_open_plugins_folder",{pluginId:t??null})}}function WE(e){throw{code:"NOT_IMPLEMENTED",message:`${e} is not implemented yet (pending its lot).`}}class HE{connect(){return WE("RemoteGateway.connect")}}function UE(){return{system:new nE,agent:new sE,input:new lE,terminal:new iE,project:new aE,layout:new oE,git:new vE,remote:new HE,profile:new cE,modelServer:new uE,desktopServer:new hE,template:new fE,skill:new pE,memory:new mE,embedder:new gE,device:new xE,permission:new _E,workState:new AE,conversation:new ME,ticket:new IE,window:new BE,focusedProject:new FE,uiPreferences:new iw,plugin:new $E}}function Dh(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Ta(e=Dh()){return{root:{type:"leaf",node:{id:e,session:null}}}}function Rh(e){if(e.length===0)return[];const t=1e-6,n=e.map(i=>Number.isFinite(i)&&i>0?i:t),r=n.reduce((i,s)=>i+s,0);if(r<=0){const i=100/n.length;return n.map(()=>i)}return n.map(i=>i/r*100)}function Qg(e,t,n){const r=[...e];if(t<0||t+1>=r.length)return r;const i=r.reduce((u,h)=>u+h,0),s=n*i,l=i*.05,o=r[t]+s,c=r[t+1]-s;return o({node:Ut(r.node,t),weight:r.weight}))}};break;case"grid":n={type:"grid",node:{...e.node,cells:e.node.cells.map(r=>({...r,node:Ut(r.node,t)}))}};break}return t(n)}function Jg(e,t){let n;return Ut(e,r=>(r.type==="leaf"&&r.node.id===t&&(n=r.node.session??null),r)),n}function qE(e,t){switch(t.type){case"split":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const s={id:t.newLeaf,session:null};return{type:"split",node:{id:t.container,direction:t.direction,children:[{node:i,weight:1},{node:{type:"leaf",node:s},weight:1}]}}}return i});if(!n)throw er(t.target);return{root:r}}case"merge":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="split"&&i.node.id===t.container){const s=i.node.children[t.keepIndex];if(!s)throw La(`merge keepIndex ${t.keepIndex} out of range`);return n=!0,s.node}return i});if(!n)throw er(t.container);return{root:r}}case"resize":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="split"&&i.node.id===t.container){if(i.node.children.length!==t.weights.length)throw La("resize weight count mismatch");n=!0;const s=i.node.children.map((l,o)=>({node:l.node,weight:t.weights[o]}));return{type:"split",node:{...i.node,children:s}}}return i});if(!n)throw er(t.container);return{root:r}}case"move":{const n=Jg(e.root,t.from);if(n===void 0)throw er(t.from);if(n===null)throw La("source cell has no session");const r=Jg(e.root,t.to);if(r===void 0)throw er(t.to);if(r!==null)throw La("target cell is occupied");return{root:Ut(e.root,s=>s.type==="leaf"&&s.node.id===t.from?{type:"leaf",node:{...s.node,session:null}}:s.type==="leaf"&&s.node.id===t.to?{type:"leaf",node:{...s.node,session:n}}:s)}}case"setSession":{let n=!1;const r=Ut(e.root,i=>i.type==="leaf"&&i.node.id===t.target?(n=!0,{type:"leaf",node:{...i.node,session:t.session??null}}):i);if(!n)throw er(t.target);return{root:r}}case"setCellAgent":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const{agent:s,...l}=i.node;return{type:"leaf",node:t.agent!==null?{...l,agent:t.agent}:l}}return i});if(!n)throw er(t.target);return{root:r}}case"setCellConversation":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const{conversationId:s,...l}=i.node;return{type:"leaf",node:t.conversationId!==null?{...l,conversationId:t.conversationId}:l}}return i});if(!n)throw er(t.target);return{root:r}}case"setAgentRunning":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const{agentWasRunning:s,...l}=i.node;return{type:"leaf",node:t.running?{...l,agentWasRunning:!0}:l}}return i});if(!n)throw er(t.target);return{root:r}}}}function Qo(e){const t=[];return Ut(e.root,n=>(n.type==="leaf"&&t.push(n.node),n)),t}function VE(e,t,n){return{root:Ut(e.root,r=>r.type==="customPluginLayout"&&r.node.id===t?{type:"customPluginLayout",node:{...r.node,state:n}}:r)}}function KE(e,t){return{root:Ut(e.root,n=>n.type==="customPluginLayout"&&n.node.id===t?{type:"leaf",node:{id:t}}:n)}}function GE(e,t){return{type:"split",target:e,direction:t,newLeaf:Dh(),container:Dh()}}function er(e){return{code:"NOT_FOUND",message:`layout node ${e} not found`}}function La(e){return{code:"INVALID",message:e}}const Zg={low:0,medium:1,high:2,critical:3},ex={open:0,inProgress:1,QA:2,closed:3};function YE(e,t){return e.sort((n,r)=>{let i=0;return t.field==="number"?i=n.number-r.number:t.field==="priority"?i=Zg[n.priority]-Zg[r.priority]:t.field==="status"?i=ex[n.status]-ex[r.status]:i=n.title.localeCompare(r.title,void 0,{sensitivity:"base"})||n.title.localeCompare(r.title),(t.direction==="desc"?-i:i)||n.number-r.number})}class XE{constructor(){X(this,"listeners",new Set);X(this,"exitGuardListeners",new Set);X(this,"confirmAppExitCallCount",0)}async health(t){const n={version:"0.1.0-mock",alive:!0,timeMillis:Date.now(),correlationId:`mock-${Math.random().toString(36).slice(2,10)}`,note:t??null};return this.emit({type:"projectCreated",projectId:n.correlationId}),n}async onDomainEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(t){for(const n of this.listeners)n(t)}async pickFolder(){return"/home/user/mock-project"}async pickArchiveFile(){return"/home/user/mock-plugin.ideaplug"}async onAppExitWorkGuard(t){return this.exitGuardListeners.add(t),()=>{this.exitGuardListeners.delete(t)}}emitAppExitWorkGuard(t){for(const n of this.exitGuardListeners)n(t)}async confirmAppExit(){this.confirmAppExitCallCount+=1}}function op(e){let t="",n=!1;for(const r of e.trim())/[a-zA-Z0-9]/.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="-",n=!0);return t.replace(/^-+|-+$/g,"")}class Mh{constructor(t,n){X(this,"scrollback",[]);X(this,"sink",null);X(this,"closed",!1);this.sessionId=t,this.sink=n}emit(t){if(!this.closed){for(const n of t)this.scrollback.push(n);this.sink?.(t)}}detach(){this.sink=null}reattach(t){return this.sink=t,Uint8Array.from(this.scrollback)}}class QE{constructor(){X(this,"agents",new Map);X(this,"contexts",new Map);X(this,"sessionSeq",0);X(this,"sessions",new Map);X(this,"liveByAgent",new Map);X(this,"liveSessionByAgent",new Map);X(this,"resumable",new Map);X(this,"conversationDetails",new Map)}getAgents(t){return this.agents.has(t)||this.agents.set(t,[]),this.agents.get(t)}contextKey(t,n){return`${t}::${n}`}async listAgents(t){return structuredClone(this.getAgents(t))}async listLiveAgents(t){const n=new Set(this.getAgents(t).map(r=>r.id));return[...this.liveByAgent.entries()].filter(([r])=>n.has(r)).map(([r,i])=>({agentId:r,nodeId:i,sessionId:this.liveSessionByAgent.get(r),kind:"pty"}))}_setResumableAgents(t,n){this.resumable.set(t,n)}async listResumableAgents(t){return structuredClone(this.resumable.get(t)??[])}async attachLiveAgent(t,n,r){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const s=this.liveSessionByAgent.get(n);if(!s||!this.sessions.has(s))throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};return this.liveByAgent.set(n,r),{agentId:n,nodeId:r,sessionId:s,kind:"pty"}}async stopLiveAgent(t,n){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const i=this.liveSessionByAgent.get(n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};const s=this.sessions.get(i);return s&&(s.closed=!0),this.sessions.delete(i),this.liveSessionByAgent.delete(n),this.liveByAgent.delete(n),{agentId:n,sessionId:i,kind:"pty"}}async createAgent(t,n){const r=this.getAgents(t),i=op(n.name)||"agent",s=new Set(r.map(u=>u.contextPath));let l=`agents/${i}.md`,o=2;for(;s.has(l);)l=`agents/${i}-${o}.md`,o+=1;const c={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:n.name,contextPath:l,profileId:n.profileId,origin:{type:"scratch"},synchronized:!1,skills:[]};return r.push(c),this.contexts.set(this.contextKey(t,c.id),n.initialContent??""),structuredClone(c)}async readContext(t,n){if(!this.getAgents(t).some(i=>i.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};return this.contexts.get(this.contextKey(t,n))??""}async updateContext(t,n,r){if(!this.getAgents(t).some(s=>s.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.contexts.set(this.contextKey(t,n),r)}async deleteAgent(t,n){const r=this.getAgents(t),i=r.findIndex(s=>s.id===n);if(i===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};r.splice(i,1),this.contexts.delete(this.contextKey(t,n))}async changeAgentProfile(t,n,r,i,s){const l=this.getAgents(t),o=l.findIndex(m=>m.id===n);if(o===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};l[o]={...l[o],profileId:r};const c=structuredClone(l[o]),u=this.liveByAgent.get(n),h=this.liveSessionByAgent.get(n);if(!u||!h)return{agent:c};const d=this.sessions.get(h);d&&(d.closed=!0),this.sessions.delete(h),this.sessionSeq+=1;const f=`mock-agent-session-${this.sessionSeq}`,p=new Mh(f,()=>{});return p.detach(),this.sessions.set(f,p),this.liveSessionByAgent.set(n,f),this.liveByAgent.set(n,u),{agent:c,relaunchedSession:{sessionId:f,cwd:"/home/user/mock-project",rows:i,cols:s}}}_insertAgent(t,n,r){this.getAgents(t).push(n),this.contexts.set(this.contextKey(t,n.id),r)}_updateAgent(t,n,r,i){const s=this.getAgents(t),l=s.findIndex(o=>o.id===n);l!==-1&&(s[l]={...s[l],...r},i!==void 0&&this.contexts.set(this.contextKey(t,n),i))}_rawAgents(t){return this.getAgents(t)}_setSkills(t,n,r){const i=this.getAgents(t),s=i.findIndex(l=>l.id===n);s!==-1&&(i[s]={...i[s],skills:r})}async launchAgent(t,n,r,i){if(!this.getAgents(t).some(p=>p.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const l=this.liveByAgent.get(n);if(l!==void 0&&r.nodeId&&l!==r.nodeId)throw{code:"AGENT_ALREADY_RUNNING",message:`agent ${n} is already running in cell ${l}`};this.sessionSeq+=1;const o=`mock-agent-session-${this.sessionSeq}`,c=r.cwd;r.nodeId&&(this.liveByAgent.set(n,r.nodeId),this.liveSessionByAgent.set(n,o));const u=()=>{this.liveByAgent.get(n)===r.nodeId&&(this.liveByAgent.delete(n),this.liveSessionByAgent.delete(n))},h=new TextEncoder,d=new Mh(o,i);this.sessions.set(o,d),queueMicrotask(()=>d.emit(h.encode(`agent ${n} @ ${c}\r -`)));const f=Jo(d,()=>{this.sessions.delete(o),u()});return r.conversationId?f:{...f,assignedConversationId:`mock-conversation-${o}`}}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`agent session ${t} is not alive`};const i=r.reattach(n);return{handle:Jo(r,()=>{this.sessions.delete(t);for(const[s,l]of this.liveSessionByAgent)l===t&&(this.liveSessionByAgent.delete(s),this.liveByAgent.delete(s))}),scrollback:i}}_setConversationDetails(t,n){this.conversationDetails.set(t,n)}async inspectConversation(t,n,r){return structuredClone(this.conversationDetails.get(r)??{})}}function Jo(e,t){return{sessionId:e.sessionId,async write(n){if(e.closed)return;const r=[];for(const i of n)i===13?r.push(13,10):r.push(i);e.emit(Uint8Array.from(r))},async resize(){},detach(){e.detach()},async close(){e.closed=!0,t()}}}class JE{constructor(){X(this,"seq",0);X(this,"sessions",new Map)}async openTerminal(t,n){this.seq+=1;const r=`mock-session-${this.seq}`,i=new TextEncoder,s=new Mh(r,n);return this.sessions.set(r,s),queueMicrotask(()=>s.emit(i.encode(`mock terminal @ ${t.cwd}\r -`))),Jo(s,()=>this.sessions.delete(r))}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`terminal session ${t} is not alive`};const i=r.reattach(n);return{handle:Jo(r,()=>this.sessions.delete(t)),scrollback:i}}async closeTerminal(t){const n=this.sessions.get(t);n&&(n.closed=!0,this.sessions.delete(t))}}class ZE{constructor(){X(this,"projects",[]);X(this,"contexts",new Map)}async listProjects(){return[...this.projects]}async createProject(t,n){if(this.projects.some(i=>i.root===n))throw{code:"INVALID",message:`a project already exists at ${n} for this remote`};const r={id:`mock-project-${Math.random().toString(36).slice(2,10)}`,name:t,root:n,remote:{kind:"local"},createdAt:Date.now()};return this.projects.push(r),r}async openProject(t){const n=this.projects.find(r=>r.id===t);if(!n)throw{code:"NOT_FOUND",message:`project ${t} not found`};return n}async closeProject(){}async readProjectContext(t){if(!this.projects.some(n=>n.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};return this.contexts.get(t)??""}async updateProjectContext(t,n){if(!this.projects.some(r=>r.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};this.contexts.set(t,n)}}class e2{constructor(){X(this,"store",new Map)}getProjectLayouts(t){if(!this.store.has(t)){const n=`layout-default-${Math.random().toString(36).slice(2,8)}`;this.store.set(t,{activeId:n,layouts:[{id:n,name:"Default",kind:"terminal",tree:Ta()}]})}return this.store.get(t)}getActiveTree(t){const n=this.getProjectLayouts(t),r=n.layouts.find(i=>i.id===n.activeId);return r?r.tree:Ta()}getTree(t,n){if(!n)return this.getActiveTree(t);const i=this.getProjectLayouts(t).layouts.find(s=>s.id===n);return i?i.tree:Ta()}setTree(t,n,r){const i=this.getProjectLayouts(t),s=r??i.activeId,l=i.layouts.find(o=>o.id===s);l&&(l.tree=n)}async loadLayout(t,n){const r=this.getTree(t,n);return structuredClone(r)}async mutateLayout(t,n,r){const i=this.getTree(t,r),s=qE(i,n);return this.setTree(t,s,r),structuredClone(s)}async listLayouts(t){const n=this.getProjectLayouts(t);return{layouts:n.layouts.map(i=>({id:i.id,name:i.name,kind:i.kind})),activeId:n.activeId}}async createLayout(t,n,r="terminal"){const i=this.getProjectLayouts(t),s=`layout-${Math.random().toString(36).slice(2,10)}`;return i.layouts.push({id:s,name:n,kind:r,tree:Ta()}),{layoutId:s}}async renameLayout(t,n,r){const s=this.getProjectLayouts(t).layouts.find(l=>l.id===n);s&&(s.name=r)}async deleteLayout(t,n){const r=this.getProjectLayouts(t),i=r.layouts.findIndex(s=>s.id===n);return i!==-1&&r.layouts.splice(i,1),r.activeId===n&&r.layouts.length>0&&(r.activeId=r.layouts[0].id),{activeId:r.activeId}}async setActiveLayout(t,n){const r=this.getProjectLayouts(t);return r.layouts.some(i=>i.id===n)&&(r.activeId=n),{activeId:r.activeId}}}const t2=[{hash:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",summary:"Merge feature into main",parents:["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","dddddddddddddddddddddddddddddddddddddddd"],refs:["main","HEAD"],author:"Alice",timestamp:17172e5},{hash:"dddddddddddddddddddddddddddddddddddddddd",summary:"Implement feature (step 2)",parents:["cccccccccccccccccccccccccccccccccccccccc"],refs:["feature"],author:"Bob",timestamp:17171e5},{hash:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",summary:"Hotfix on main",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Alice",timestamp:171709e4},{hash:"cccccccccccccccccccccccccccccccccccccccc",summary:"Implement feature (step 1)",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Bob",timestamp:171708e4},{hash:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",summary:"Initial commit",parents:[],refs:["tag: v1.0"],author:"Alice",timestamp:1717e6}];class n2{constructor(){X(this,"projects",new Map)}getState(t){return this.projects.has(t)||this.projects.set(t,this._seedState()),this.projects.get(t)}_seedState(){const t=new Map;return t.set("src/main.rs",!1),t.set("README.md",!1),{files:t,branches:["main"],current:"main",log:[],commitSeq:0}}async init(t){this.projects.has(t)||this.projects.set(t,this._seedState())}async status(t){const n=this.getState(t);return Array.from(n.files.entries()).map(([r,i])=>({path:r,staged:i}))}async stage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!0)}async unstage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!1)}async commit(t,n){const r=this.getState(t);r.commitSeq+=1;const i={hash:`mock-${r.commitSeq}`,summary:n.split(` -`)[0]};for(const[s,l]of Array.from(r.files.entries()))l&&r.files.delete(s);return r.log.unshift(i),i}async branches(t){const n=this.getState(t);return{branches:[...n.branches],current:n.current}}async checkout(t,n){const r=this.getState(t);r.branches.includes(n)||r.branches.push(n),r.current=n}async log(t,n){return this.getState(t).log.slice(0,n)}async graph(t,n){return t2.slice(0,n)}}class r2{async connect(){}}class i2{constructor(){X(this,"open",new Set);X(this,"listeners",new Set)}async openViewWindow(t){this.open.add(t)}async closeViewWindow(t){this.open.delete(t)&&this.emit({panel:t})}async listOpenViewWindows(){return[...this.open].map(t=>({panel:t,label:t,visible:!0}))}async onViewWindowClosed(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}simulateOsClose(t){this.open.delete(t),this.emit({panel:t})}emit(t){for(const n of this.listeners)n(t)}}class s2{constructor(){X(this,"focused",null);X(this,"listeners",new Set)}async setFocusedProject(t){this.focused=t;for(const n of this.listeners)n(t)}async getFocusedProject(){return this.focused}async onFocusedProjectChanged(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}}const bu=[{id:"mock-claude",name:"Claude Code",command:"claude",args:[],contextInjection:{strategy:"conventionFile",target:"CLAUDE.md"},detect:"claude --version",cwdTemplate:"{projectRoot}"},{id:"mock-codex",name:"OpenAI Codex CLI",command:"codex",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"codex --version",cwdTemplate:"{projectRoot}"},{id:"mock-opencode",name:"OpenCode + llama.cpp",command:"opencode",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"opencode --version",cwdTemplate:"{projectRoot}",structuredAdapter:"openCode",opencode:{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}],l2=[{providerId:"anthropic",displayName:"Anthropic",models:["claude-sonnet-5","claude-opus-4-8","claude-haiku-4-5"]},{providerId:"openrouter",displayName:"OpenRouter",models:["openrouter/auto","qwen/qwen3-coder"]}];class a2{constructor(){X(this,"profiles",[]);X(this,"configured",!1);X(this,"cloneCounter",0)}async firstRunState(){return{isFirstRun:!this.configured,referenceProfiles:structuredClone(bu)}}async referenceProfiles(){return structuredClone(bu)}async detectProfiles(t){return t.map(n=>({profile:n,available:n.command==="claude"}))}async listProfiles(){return structuredClone(this.profiles)}async saveProfile(t){const n=this.profiles.findIndex(r=>r.id===t.id);return n>=0?this.profiles[n]=t:this.profiles.push(t),this.configured=!0,structuredClone(t)}async deleteProfile(t){this.profiles=this.profiles.filter(n=>n.id!==t)}async configureProfiles(t){return this.profiles=structuredClone(t),this.configured=!0,structuredClone(t)}async cloneOpenCodeProfileFromSeed(t={}){const n=bu.find(r=>r.structuredAdapter==="openCode");if(!n)throw new Error("no OpenCode seed profile");return this.cloneCounter+=1,structuredClone({...n,id:`mock-opencode-clone-${this.cloneCounter}`,name:t.name??`${n.name} (copy ${this.cloneCounter})`,opencode:t.opencode??n.opencode})}async listOpenCodeProviders(){return structuredClone(l2)}async saveOpenCodeProviderProfile(t){const n={...structuredClone(t.profile),opencode:void 0,opencodeProvider:{providerId:t.providerId,model:t.model,apiKeyRef:`mock-secret-${t.profile.id}`,custom:t.custom}},r=this.profiles.findIndex(i=>i.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}}class o2{constructor(){X(this,"servers",[]);X(this,"inUse",new Set)}async listModelServers(){return structuredClone(this.servers)}async saveModelServer(t){const n=this.servers.findIndex(r=>r.id===t.id);return n>=0?this.servers[n]=structuredClone(t):this.servers.push(structuredClone(t)),structuredClone(t)}async deleteModelServer(t){if(this.inUse.has(t))throw{code:"model_server_in_use",message:"A profile still references this server."};this.servers=this.servers.filter(n=>n.id!==t)}async previewModelServerCommand(t){if(!t.modelSource)throw{code:"INVALID",message:"model.source missing"};const n=t.binaryPath&&t.binaryPath.trim().length>0?t.binaryPath:"llama-server",r=[];t.modelSource.type==="localPath"?r.push("--model",t.modelSource.path):r.push("-hf",t.modelSource.repo),r.push("--port",String(t.port),"--host",t.host),t.gpuLayers!==void 0&&r.push("-ngl",String(t.gpuLayers)),t.contextSize!==void 0&&r.push("-c",String(t.contextSize)),t.jinja&&r.push("--jinja"),r.push(...t.args);const i=[n,...r].map(s=>/\s/.test(s)?`'${s}'`:s).join(" ");return{command:n,args:r,display:i}}markInUse(t){this.inUse.add(t)}}const c2={mode:"localOnly",autoStart:!1,port:17373,trustedProxies:[]},u2=["192.168.1.42","10.0.0.17"];function Ri(e){throw{code:"INVALID",message:e}}class d2{constructor(){X(this,"settings",structuredClone(c2));X(this,"current",{state:"stopped"});X(this,"handlers",new Set)}async getExposureSettings(){return structuredClone(this.settings)}async saveExposureSettings(t){this.validate(t),this.settings=structuredClone(t)}async previewExposure(t){this.validate(t);const n=[];t.mode==="remoteProxyOtherMachine"&&t.trustedProxies.length===0&&n.push({code:"missingTrustedProxy",message:"Add the IP address or CIDR of the reverse proxy that connects to this server."});const r=t.mode==="remoteProxyOtherMachine"?t.lanBindAddress:"127.0.0.1",i=t.mode!=="localOnly"&&r?`http://${r}:${t.port}`:void 0;return{candidateLanAddresses:[...u2],upstreamUrl:i,warnings:n}}async status(){return structuredClone(this.current)}async start(){this.validate(this.settings);const t=await this.previewExposure(this.settings);return this.emit({state:"running",localUrl:`http://127.0.0.1:${this.settings.port}`,publicUrl:this.settings.mode==="localOnly"?void 0:this.settings.publicOrigin,upstreamUrl:t.upstreamUrl}),structuredClone(this.current)}async stop(){return this.emit({state:"stopped"}),structuredClone(this.current)}async onStatusChanged(t){return this.handlers.add(t),()=>this.handlers.delete(t)}setStatus(t){this.emit(t)}emit(t){this.current=t;for(const n of this.handlers)n(structuredClone(t))}validate(t){if(t.mode!=="localOnly"){const n=t.publicOrigin;n||Ri("remote exposure requires publicOrigin"),n.startsWith("https://")||Ri("remote exposure requires publicOrigin to start with https://"),n.includes("*")&&Ri("publicOrigin must be exact, not a wildcard"),n.endsWith("/")&&Ri("publicOrigin must not end with '/'")}t.mode==="remoteProxyOtherMachine"&&(t.lanBindAddress||Ri("remoteProxyOtherMachine requires lanBindAddress"),t.trustedProxies.length===0&&Ri("remoteProxyOtherMachine requires at least one trustedProxies entry"))}}class h2{constructor(t){X(this,"templates",[]);X(this,"seq",0);this.agentGateway=t}async listTemplates(){return structuredClone(this.templates)}async createTemplate(t){this.seq+=1;const n={id:`mock-template-${this.seq}`,name:t.name,contentMd:t.content,version:1,defaultProfileId:t.defaultProfileId};return this.templates.push(n),structuredClone(n)}async updateTemplate(t,n){const r=this.templates.findIndex(i=>i.id===t);if(r===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};return this.templates[r]={...this.templates[r],contentMd:n,version:this.templates[r].version+1},structuredClone(this.templates[r])}async deleteTemplate(t){const n=this.templates.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};this.templates.splice(n,1)}async createAgentFromTemplate(t,n,r){const i=this.templates.find(f=>f.id===n);if(!i)throw{code:"NOT_FOUND",message:`template ${n} not found`};const s=r?.synchronized??!0,l=r?.name??i.name,o=op(l)||"agent",c=new Set(this.agentGateway._rawAgents(t).map(f=>f.contextPath));let u=`agents/${o}.md`,h=2;for(;c.has(u);)u=`agents/${o}-${h}.md`,h+=1;const d={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:l,contextPath:u,profileId:i.defaultProfileId,origin:{type:"fromTemplate",templateId:n,syncedTemplateVersion:i.version},synchronized:s,skills:[]};return this.agentGateway._insertAgent(t,d,i.contentMd),structuredClone(d)}async detectDrift(t){const n=this.agentGateway._rawAgents(t),r=[];for(const i of n){if(!i.synchronized||i.origin.type!=="fromTemplate")continue;const{templateId:s,syncedTemplateVersion:l}=i.origin,o=this.templates.find(c=>c.id===s);o&&o.version>l&&r.push({agentId:i.id,from:l,to:o.version})}return r}async syncAgent(t,n){const i=this.agentGateway._rawAgents(t).find(o=>o.id===n);if(!i||!i.synchronized||i.origin.type!=="fromTemplate")return{synced:!1,version:null};const{templateId:s}=i.origin,l=this.templates.find(o=>o.id===s);return l?(this.agentGateway._updateAgent(t,n,{origin:{type:"fromTemplate",templateId:s,syncedTemplateVersion:l.version}},l.contentMd),{synced:!0,version:l.version}):{synced:!1,version:null}}}class f2{constructor(t){X(this,"global",[]);X(this,"byProject",new Map);X(this,"seq",0);this.agentGateway=t}bucket(t,n){if(n==="global")return this.global;let r=this.byProject.get(t);return r||(r=[],this.byProject.set(t,r)),r}async listSkills(t,n){return structuredClone(this.bucket(t,n))}async createSkill(t){this.seq+=1;const n={id:`mock-skill-${this.seq}`,name:t.name,contentMd:t.content,scope:t.scope};return this.bucket(t.projectId,t.scope).push(n),structuredClone(n)}async updateSkill(t,n,r,i){const s=this.bucket(t,n),l=s.findIndex(o=>o.id===r);if(l===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};return s[l]={...s[l],contentMd:i},structuredClone(s[l])}async deleteSkill(t,n,r){const i=this.bucket(t,n),s=i.findIndex(l=>l.id===r);if(s===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};i.splice(s,1)}async assignSkill(t,n,r,i){const s=this.agentGateway._rawAgents(t).find(l=>l.id===n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};s.skills.some(l=>l.skillId===r)||this.agentGateway._setSkills(t,n,[...s.skills,{skillId:r,scope:i}])}async unassignSkill(t,n,r){const i=this.agentGateway._rawAgents(t).find(s=>s.id===n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.agentGateway._setSkills(t,n,i.skills.filter(s=>s.skillId!==r))}}class p2{constructor(){X(this,"byProject",new Map)}bucket(t){let n=this.byProject.get(t);return n||(n=new Map,this.byProject.set(t,n)),n}notFound(t,n){return{code:"NOT_FOUND",message:`memory ${t} not found in project ${n}`}}async listMemories(t){return structuredClone([...this.bucket(t).values()])}async getMemory(t,n){const r=this.bucket(t).get(n);if(!r)throw this.notFound(n,t);return structuredClone(r)}async createMemory(t){const n={name:t.name,description:t.description,type:t.type,content:t.content};return this.bucket(t.projectId).set(op(t.name),n),structuredClone(n)}async updateMemory(t,n,r,i,s){const l=this.bucket(t),o=l.get(n);if(!o)throw this.notFound(n,t);const c={...o,description:r,type:i,content:s};return l.set(n,c),structuredClone(c)}async deleteMemory(t,n){if(!this.bucket(t).delete(n))throw this.notFound(n,t)}async readIndex(t){return[...this.bucket(t).entries()].map(([n,r])=>({slug:n,title:r.name,hook:r.description,type:r.type}))}async resolveLinks(t,n){const r=this.bucket(t),i=r.get(n);if(!i)throw this.notFound(n,t);const s=new Set;for(const l of i.content.matchAll(/\[\[([^\]]+)\]\]/g)){const o=l[1].trim();o!==n&&r.has(o)&&s.add(o)}return[...s]}async recall(t,n,r){const i=await this.readIndex(t),s=Math.max(0,Math.floor(r/16));return i.slice(0,s)}}class m2{constructor(t,n=[]){X(this,"profiles",new Map);X(this,"engines");this.engines={recommendedOnnx:[{id:"e5-small",displayName:"E5 Small (multilingual)",dimension:384,approxSizeMb:120,recommended:!0},{id:"bge-small",displayName:"BGE Small",dimension:384,approxSizeMb:130,recommended:!1}],ollamaDetected:!1,onnxCachedModels:[],vectorHttpEnabled:!0,vectorOnnxEnabled:!0,...t};for(const r of n)this.profiles.set(r.id,r)}async listEmbedderProfiles(){return structuredClone([...this.profiles.values()])}async saveEmbedderProfile(t){if(!t.id.trim()||!t.name.trim())throw{code:"INVALID",message:"embedder profile id/name must not be empty"};if(t.dimension<=0)throw{code:"INVALID",message:"embedder profile dimension must be > 0"};return this.profiles.set(t.id,structuredClone(t)),structuredClone(t)}async deleteEmbedderProfile(t){this.profiles.delete(t)}async describeEmbedderEngines(){return structuredClone(this.engines)}}class g2{constructor(){X(this,"interrupts",[]);X(this,"delivered",[]);X(this,"frontAttached",[]);X(this,"cancelledResumes",[]);X(this,"resumeArmings",[]);X(this,"cancelResumeResult",!0)}async interrupt(t,n){this.interrupts.push({projectId:t,agentId:n})}async delegationDelivered(t,n,r){this.delivered.push({projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){this.frontAttached.push({agentId:t,attached:n})}async cancelResume(t){return this.cancelledResumes.push(t),this.cancelResumeResult}async setResumeAt(t,n){this.resumeArmings.push({agentId:t,resetsAtMs:n})}}class x2{constructor(){X(this,"devices",[]);X(this,"issued",0);X(this,"_issuedCodes",[])}_setDevices(t){this.devices=structuredClone(t)}async listDevices(){return structuredClone(this.devices)}async createPairingCode(){const t=(268435456+this.issued++).toString(16).toUpperCase().slice(0,8);this._issuedCodes.push(t);const n=600;return{code:t,expiresAtMs:Date.now()+n*1e3,ttlSeconds:n}}async renameDevice(t,n){const r=this.devices.find(i=>i.deviceId===t);if(!r)throw{code:"NOT_FOUND",message:`unknown device ${t}`};r.name=n}async revokeDevice(t){this.devices=this.devices.filter(n=>n.deviceId!==t)}async revokeAllDevices(){this.devices=[]}}class v2{constructor(){X(this,"docs",new Map);X(this,"mcpCatalogue",{readOnlyTools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read","idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"],writeActionTools:["idea_ask_agent","idea_run_in_background","idea_launch_agent","idea_stop_agent","idea_update_context","idea_context_propose","idea_memory_write","idea_workstate_set","idea_create_skill","idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]});X(this,"mcpDocs",new Map)}doc(t){return this.docs.has(t)||this.docs.set(t,{version:1,agents:[]}),this.docs.get(t)}async getProjectPermissions(t){return structuredClone(this.doc(t))}async updateProjectPermissions(t,n){const r=this.doc(t);return n?r.projectDefaults=structuredClone(n):delete r.projectDefaults,structuredClone(r)}async updateAgentPermissions(t,n,r){const i=this.doc(t),s=(i.agents??[]).filter(l=>l.agentId!==n);return r&&s.push({agentId:n,permissions:structuredClone(r)}),i.agents=s,structuredClone(i)}async resolveAgentPermissions(t,n){const r=this.doc(t),i=r.projectDefaults,s=r.agents?.find(l=>l.agentId===n)?.permissions;return!i&&!s?null:{rules:[...i?.rules??[],...s?.rules??[]],fallback:S2(i?.fallback,s?.fallback)}}mcpDoc(t){return this.mcpDocs.has(t)||this.mcpDocs.set(t,{version:1,catalogue:this.mcpCatalogue,projectDefault:null,agents:[]}),this.mcpDocs.get(t)}async getMcpToolPermissions(t){return structuredClone(this.mcpDoc(t))}async updateProjectMcpToolPermissions(t,n){const r=this.mcpDoc(t);return r.projectDefault=n?structuredClone(n):null,structuredClone(r)}async updateAgentMcpToolPermissions(t,n,r){const i=this.mcpDoc(t);return i.agents=i.agents.filter(s=>s.agentId!==n),r&&i.agents.push({agentId:n,policy:structuredClone(r)}),structuredClone(i)}}class _2{constructor(){X(this,"states",new Map)}_setProjectWorkState(t,n){this.states.set(t,lp(n))}async getProjectWorkState(t){return structuredClone(this.states.get(t)??{agents:[],conversations:[]})}async cancelBackgroundTask(t){}async retryBackgroundTask(t){}}class y2{constructor(){X(this,"threads",new Map)}key(t,n){return`${t}::${n}`}_setTurns(t,n,r){this.threads.set(this.key(t,n),r.map(i=>structuredClone(i)))}async readPage(t,n,r){const i=this.threads.get(this.key(t,n))??[],s=i.length,l=r?.limit,o=Math.min(Math.max(l&&l>0?l:50,1),200),c=r?.direction??"backward",u=r?.anchor;let h,d,f;if(u===void 0)c==="forward"?(h=0,d=Math.min(o,s),f=d0);else{const x=i.findIndex(w=>w.id===u);x===-1?(h=0,d=0,f=!1):c==="forward"?(h=x+1,d=Math.min(h+o,s),f=d0)}const p=i.slice(h,d).map(x=>structuredClone(x)),m=p.at(-1);return{turns:p,hasMore:f,...m?{nextAnchor:m.id}:{}}}}class b2{constructor(t){X(this,"tickets",new Map);X(this,"carnets",new Map);X(this,"counters",new Map);X(this,"sprints",new Map);X(this,"sprintCounters",new Map);X(this,"chatSessions",new Map);X(this,"chatCounter",0);this.system=t}_seedTicket(t,n){const r=structuredClone(n);return r.sprintId===void 0&&(r.sprintId=null),this.projectTickets(t).set(r.ref,r),this.counters.set(t,Math.max(this.counters.get(t)??0,r.number)),structuredClone(r)}_seedSprint(t,n){const r={status:"planned",ticketCount:0,version:1,...n};return this.projectSprints(t).set(r.id,r),structuredClone(r)}projectSprints(t){let n=this.sprints.get(t);return n||(n=new Map,this.sprints.set(t,n)),n}recountSprints(t){const n=this.projectSprints(t),r=new Map;for(const i of this.projectTickets(t).values())i.sprintId&&r.set(i.sprintId,(r.get(i.sprintId)??0)+1);for(const i of n.values())i.ticketCount=r.get(i.id)??0}projectTickets(t){let n=this.tickets.get(t);return n||(n=new Map,this.tickets.set(t,n)),n}projectCarnets(t){let n=this.carnets.get(t);return n||(n=new Map,this.carnets.set(t,n)),n}require(t,n){const r=this.projectTickets(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`ticket ${n} not found`};return r}guard(t,n){if(t.version!==n)throw{code:"INVALID",message:`issue version conflict: expected ${n}, actual ${t.version}`}}async create(t,n){const r=(this.counters.get(t)??0)+1;this.counters.set(t,r);const i=Date.now(),s={id:`mock-ticket-${t}-${r}`,ref:`#${r}`,number:r,title:n.title,description:n.description??"",status:n.status??"open",priority:n.priority??"medium",sprintId:null,links:[],assignedAgentIds:[...n.assignedAgentIds??[]],createdBy:{kind:"user"},updatedBy:{kind:"user"},createdAt:i,updatedAt:i,version:1};return this.projectTickets(t).set(s.ref,s),this.system?.emit({type:"issueCreated",issueId:s.id,issueRef:s.ref}),structuredClone(s)}async read(t,n,r=!1){const i=structuredClone(this.require(t,n));return r&&(i.carnet=this.projectCarnets(t).get(n)??""),i}async list(t,n){const r=n??{},i=r.text?.trim().toLowerCase(),s=r.statuses??[],l=r.priorities??[];let o=[...this.projectTickets(t).values()].filter(d=>s.length===0||s.includes(d.status)).filter(d=>l.length===0||l.includes(d.priority)).filter(d=>!r.assignedAgentId||d.assignedAgentIds.includes(r.assignedAgentId)).filter(d=>!i||d.title.toLowerCase().includes(i)||d.description.toLowerCase().includes(i));o=r.sort?YE(o,r.sort):o.sort((d,f)=>f.number-d.number);const c=Number.parseInt(r.cursor??"0",10)||0,u=Math.min(Math.max(r.limit??100,1),500),h=Math.min(o.length,c+u);return{items:o.slice(c,h).map(d=>({ref:d.ref,path:`.ideai/tickets/${d.number}.md`,title:d.title,status:d.status,priority:d.priority,sprintId:d.sprintId??null,assignedAgentIds:[...d.assignedAgentIds],updatedAt:d.updatedAt})),...hc.targetRef===r&&c.kind===i)||l.links.push({targetRef:r,kind:i}),this.bump(l),this.system?.emit({type:"issueLinked",issueRef:n,target:r,kind:i,version:l.version}),structuredClone(l)}async unlink(t,n,r,i,s){const l=this.require(t,n);return this.guard(l,i),l.links=l.links.filter(o=>o.targetRef!==r||s!==void 0&&o.kind!==s),this.bump(l),this.system?.emit({type:"issueUnlinked",issueRef:n,target:r,kind:s??"relatesTo",version:l.version}),structuredClone(l)}async assign(t,n,r,i,s){const l=this.require(t,n);this.guard(l,s);const o=l.assignedAgentIds.includes(r);return i&&!o&&l.assignedAgentIds.push(r),!i&&o&&(l.assignedAgentIds=l.assignedAgentIds.filter(c=>c!==r)),this.bump(l),this.system?.emit({type:i?"issueAgentAssigned":"issueAgentUnassigned",issueRef:n,agentId:r,version:l.version}),structuredClone(l)}async listSprints(t){return this.recountSprints(t),[...this.projectSprints(t).values()].sort((n,r)=>n.order-r.order).map(n=>structuredClone(n))}async setTicketSprint(t,n,r,i){const s=this.require(t,n);if(this.guard(s,i),r!==null&&!this.projectSprints(t).has(r))throw{code:"NOT_FOUND",message:`sprint ${r} not found`};const l=s.sprintId??null;return s.sprintId=r,this.bump(s),this.recountSprints(t),this.system?.emit({type:"issueSprintChanged",issueRef:n,from:l,to:r,version:s.version}),structuredClone(s)}async createSprint(t,n){const r=this.projectSprints(t),i=(this.sprintCounters.get(t)??0)+1;this.sprintCounters.set(t,i);const s=r.size===0?1:Math.max(...[...r.values()].map(o=>o.order))+1,l={id:`mock-sprint-${t}-${i}`,order:s,name:n,status:"planned",ticketCount:0,version:1};return r.set(l.id,l),this.system?.emit({type:"sprintCreated",sprintId:l.id,order:l.order}),structuredClone(l)}async renameSprint(t,n,r,i){const s=this.requireSprint(t,n);return this.guardSprint(s,i),s.name=r,s.version+=1,this.system?.emit({type:"sprintRenamed",sprintId:n,name:r,version:s.version}),structuredClone(s)}async reorderSprints(t,n){const r=this.projectSprints(t);for(const s of n)this.requireSprint(t,s);const i=[...r.values()].filter(s=>!n.includes(s.id)).sort((s,l)=>s.order-l.order).map(s=>s.id);return[...n,...i].forEach((s,l)=>{const o=r.get(s);o&&(o.order=l+1,this.system?.emit({type:"sprintReordered",sprintId:s,order:o.order,version:o.version}))}),this.listSprints(t)}async deleteSprint(t,n){this.requireSprint(t,n);for(const r of this.projectTickets(t).values())r.sprintId===n&&(r.sprintId=null,this.bump(r),this.system?.emit({type:"issueSprintChanged",issueRef:r.ref,from:n,to:null,version:r.version}));this.projectSprints(t).delete(n),this.system?.emit({type:"sprintDeleted",sprintId:n})}async openTicketChat(t,n,r){this.require(t,n);const i=`mock-ticket-chat-${++this.chatCounter}`;return this.chatSessions.set(n,i),this.system?.emit({type:"ticketAssistantOpened",issueRef:n,profileId:r}),{sessionId:i,requester:"ticket-assistant",issueRef:n}}async closeTicketChat(t,n){this.chatSessions.delete(n)&&this.system?.emit({type:"ticketAssistantClosed",issueRef:n})}async sendTicketChat(t,n,r){if(![...this.chatSessions.values()].includes(t))throw{code:"NOT_FOUND",message:`chat session ${t} not found`};const i=`Assistant: reçu « ${n} ».`,s=[{kind:"textDelta",text:"Assistant: reçu "},{kind:"textDelta",text:`« ${n} ».`},{kind:"final",content:i}];for(const l of s)await Promise.resolve(),r(l)}requireSprint(t,n){const r=this.projectSprints(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`sprint ${n} not found`};return r}guardSprint(t,n){if(t.version!==n)throw{code:"INVALID",message:`sprint version conflict: expected ${n}, actual ${t.version}`}}}class w2{constructor(){X(this,"store",new Map)}read(t){const n=this.store.get(t);if(n===void 0)return null;try{return JSON.parse(n)}catch{return this.store.delete(t),null}}write(t,n){try{this.store.set(t,JSON.stringify(n))}catch{}}remove(t){this.store.delete(t)}}function S2(e,t){const n={allow:0,ask:1,deny:2},r=e??t??"ask";return t&&n[t]>=n[r]?t:r}class k2{constructor(){X(this,"plugins",[]);X(this,"seq",0)}summaryFor(t){return{topLevelMenus:0,menuItems:0,layouts:0,mcpServers:0}}_seedPlugin(t){this.plugins.push(t)}async listPlugins(){return structuredClone(this.plugins)}async reviewPackage(t){this.seq+=1;const n=t.path.split("/").pop()??t.path;return{id:`mock.plugin.${this.seq}`,displayName:n.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",description:`Reviewed from ${t.sourceKind}: ${t.path}`,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`),issues:[],installable:!0}}async install(t,n){this.seq+=1;const r=n.split("/").pop()??n,i={id:`mock.plugin.${this.seq}`,displayName:r.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",sourceKind:t,sourceLabel:n,lifecycleState:"enabled",enabled:!0,pendingUninstall:!1,restartRequired:!0,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`)};return this.plugins.push(i),{plugin:structuredClone(i),restartRequired:!0}}installFromArchive(t){return this.install("archive",t)}installFromDirectory(t){return this.install("directory",t)}async setEnabled(t,n){const r=this.plugins.find(s=>s.id===t);if(!r)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};const i=n?"enabled":"disabled";return r.enabled=n,r.lifecycleState=i,r.restartRequired=!0,structuredClone(r)}async uninstall(t){const n=this.plugins.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};return this.plugins.splice(n,1),{pluginId:t,restartRequired:!0}}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){}}function C2(){const e=new QE,t=new XE;return{system:t,agent:e,input:new g2,terminal:new JE,project:new ZE,layout:new e2,git:new n2,remote:new r2,profile:new a2,modelServer:new o2,desktopServer:new d2,template:new h2(e),skill:new f2(e),memory:new p2,embedder:new m2,device:new x2,permission:new v2,workState:new _2,conversation:new y2,ticket:new b2(t),window:new i2,focusedProject:new s2,uiPreferences:new w2,plugin:new k2}}function sw(){const e=globalThis.fetch;return typeof e=="function"?e.bind(globalThis):e}function j2(e,t){if(e&&typeof e=="object"){const n=e,r=typeof n.code=="string"?n.code:void 0,i=typeof n.message=="string"?n.message:void 0;if(r||i)return{code:r??"ERROR",message:i??t}}return{code:"TRANSPORT_ERROR",message:t}}class N2{constructor(t){X(this,"baseUrl");X(this,"token");X(this,"fetchImpl");X(this,"onUnauthorized");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.onUnauthorized=t.onUnauthorized,this.fetchImpl=t.fetchImpl??sw()}invoke(t,n={}){return this.request("POST","/api/invoke",{command:t,args:n},`command '${t}'`)}async request(t,n,r,i=`${t} ${n}`){const s={"Content-Type":"application/json"};this.token&&(s.Authorization=`Bearer ${this.token}`);let l;try{l=await this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:s,body:r===void 0?void 0:JSON.stringify(r),credentials:"same-origin"})}catch(c){throw{code:"TRANSPORT_ERROR",message:`HTTP request for ${i} failed: ${String(c)}`}}if(!l.ok){l.status===401&&this.onUnauthorized?.();let c;try{c=await l.json()}catch{c=void 0}throw j2(c,`${i} failed (HTTP ${l.status})`)}let o;try{o=await l.json()}catch{o=void 0}return o}}function E2(e){let t="";for(let n=0;nlw(s.bytesBase64)),n=t.reduce((s,l)=>s+l.length,0),r=new Uint8Array(n);let i=0;for(const s of t)r.set(s,i),i+=s.length;return r}class aw{constructor(t){X(this,"wsUrl");X(this,"token");X(this,"socketFactory");X(this,"reconnectBaseMs");X(this,"reconnectMaxMs");X(this,"setTimeoutImpl");X(this,"clearTimeoutImpl");X(this,"onReconnectFailed");X(this,"socket",null);X(this,"opening",null);X(this,"disposed",!1);X(this,"everConnected",!1);X(this,"connState","connecting");X(this,"reconnectAttempt",0);X(this,"reconnectHandle",null);X(this,"outputSinks",new Map);X(this,"terminals",new Map);X(this,"pending",new Map);X(this,"domainEventHandler",null);X(this,"connListeners",new Set);this.wsUrl=t.wsUrl.replace(/\/+$/,""),this.token=t.token,this.socketFactory=t.socketFactory??(n=>new WebSocket(n)),this.reconnectBaseMs=t.reconnectBaseMs??500,this.reconnectMaxMs=t.reconnectMaxMs??1e4,this.setTimeoutImpl=t.setTimeoutImpl??((n,r)=>setTimeout(n,r)),this.clearTimeoutImpl=t.clearTimeoutImpl??(n=>clearTimeout(n)),this.onReconnectFailed=t.onReconnectFailed}getConnectionState(){return this.connState}onConnectionStateChange(t){return this.connListeners.add(t),()=>this.connListeners.delete(t)}setConnState(t){if(this.connState!==t){this.connState=t;for(const n of this.connListeners)n(t)}}setDomainEventHandler(t){this.domainEventHandler=t}clearDomainEventHandler(){this.domainEventHandler=null}setOutputSink(t,n){this.outputSinks.set(t,n)}removeOutputSink(t){this.outputSinks.delete(t)}async ensureConnected(){if(!this.socket)return this.opening?this.opening:this.connect()}connect(){return this.setConnState(this.everConnected?"reconnecting":"connecting"),this.opening=new Promise((t,n)=>{const r=this.token?`${this.wsUrl}${tx}?token=${encodeURIComponent(this.token)}`:`${this.wsUrl}${tx}`,i=this.socketFactory(r);i.onopen=()=>{this.socket=i,this.opening=null,this.everConnected=!0,this.reconnectAttempt=0,this.setConnState("connected"),t()},i.onerror=s=>{this.opening=null,n(s)},i.onclose=()=>this.handleSocketClosed(),i.onmessage=s=>this.handleMessage(s.data)}),this.opening}handleSocketClosed(){if(this.socket=null,this.opening=null,this.rejectAllPending({code:"WS_CLOSED",message:"socket closed"}),this.disposed){this.setConnState("closed");return}if(this.setConnState("reconnecting"),this.terminals.size>0)for(const t of this.terminals.values())t.onData(wu("déconnecté — reconnexion…"));this.needsReconnect()&&this.scheduleReconnect()}needsReconnect(){return this.terminals.size>0||this.domainEventHandler!==null}scheduleReconnect(){if(this.disposed||this.reconnectHandle)return;const t=Math.min(this.reconnectMaxMs,this.reconnectBaseMs*2**this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectHandle=this.setTimeoutImpl(()=>{this.reconnectHandle=null,this.reconnectNow()},t)}async reconnectNow(){if(!this.disposed)try{await this.connect(),await this.reattachAll()}catch{this.onReconnectFailed?.(),this.needsReconnect()&&this.scheduleReconnect()}}async reattachAll(){for(const[t,n]of this.terminals)try{const i=(await this.send("terminal.attach",{sessionId:t,lastSeq:n.lastSeq})).payload;n.onData(wu("reconnecté"));const s=ix(i);s.length>0&&n.onData(s),typeof i.nextSeq=="number"&&(n.lastSeq=Math.max(0,i.nextSeq-1))}catch{}}openTerminal(t){return this.attachInternal("terminal.open",{cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}launchAgent(t){return this.attachInternal("agent.launch",{projectId:t.projectId,agentId:t.agentId,nodeId:t.nodeId??null,rows:t.rows,cols:t.cols,conversationId:t.conversationId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}attachTerminal(t){return this.attachInternal("terminal.attach",{sessionId:t.sessionId,rows:t.rows,cols:t.cols,lastSeq:t.lastSeq??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:t.lastSeq??0},t.sessionId)}async attachInternal(t,n,r,i){const l=(await this.send(t,n)).payload,o=i??l.session.sessionId;return typeof l.nextSeq=="number"&&(r.lastSeq=Math.max(0,l.nextSeq-1)),this.terminals.set(o,r),this.setOutputSink(o,r.onData),{sessionId:o,scrollback:ix(l),assignedConversationId:l.assignedConversationId,status:l.status}}async detachTerminal(t){this.removeTerminal(t),await this.sendFireAndForget("terminal.detach",{sessionId:t})}async closeTerminalSession(t){this.removeTerminal(t),await this.send("terminal.close",{sessionId:t})}removeTerminal(t){this.terminals.delete(t),this.outputSinks.delete(t)}async send(t,n){await this.ensureConnected();const r=this.socket;if(!r)throw{code:"WS_CLOSED",message:"socket not connected"};const i=rx(),s={id:i,kind:t,payload:n},l=new Promise((o,c)=>{this.pending.set(i,{resolve:o,reject:c})});return r.send(JSON.stringify(s)),l}async sendFireAndForget(t,n){await this.ensureConnected();const i={id:rx(),kind:t,payload:n};this.socket?.send(JSON.stringify(i))}static encodeInput(t){return E2(t)}disconnect(){this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disconnected"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null;const t=this.socket;t&&(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close()),this.socket=null,this.opening=null,this.everConnected=!1,this.reconnectAttempt=0,this.setConnState("closed")}dispose(){this.disposed=!0,this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disposed"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null,this.socket?.close(),this.socket=null,this.opening=null,this.setConnState("closed")}rejectAllPending(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}switch(n.kind){case"terminal.output":{const r=n.payload,i=this.terminals.get(r.sessionId);i&&typeof r.seq=="number"&&(i.lastSeq=r.seq);const s=this.outputSinks.get(r.sessionId);s&&s(lw(r.bytesBase64));return}case"terminal.status":{const r=n.payload;this.handleStatus(r);return}case"event.domain":{this.domainEventHandler?.(n.payload);return}}if(n.replyTo){const r=this.pending.get(n.replyTo);r&&(this.pending.delete(n.replyTo),n.kind==="error"?r.reject(n.payload):r.resolve(n))}}handleStatus(t){const n=this.terminals.get(t.sessionId);if(n)if(t.status==="exited"||t.status==="closed"){const r=t.exitCode;n.onData(wu(r==null?"session terminée":`session terminée (code ${r})`)),n.onStatus?.(t.status,t.exitCode),this.removeTerminal(t.sessionId)}else n.onStatus?.(t.status,t.exitCode)}}const Su="idea.web.paired";function A2(){const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n),removeItem:t=>void e.delete(t)}}function T2(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return A2()}function L2(){return typeof window<"u"&&window.location?window.location.origin:"http://localhost"}const D2={invalidOrExpired:"Code invalide ou expiré.",invalidName:"Nom d'appareil invalide (1 à 40 caractères). Le code reste valable.",rateLimited:"Trop de tentatives. Réessayez dans quelques minutes avec un nouveau code.",pairingFailed:"Échec de l'appairage."};function R2(e,t){const n=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;let r;return n==="invalid_or_expired"?r="invalidOrExpired":n==="invalid_name"?r="invalidName":n==="rate_limited"||t===429?r="rateLimited":t===401||t===403?r="invalidOrExpired":r="pairingFailed",{code:r,message:D2[r]}}class M2{constructor(t={}){X(this,"baseUrl");X(this,"fetchImpl");X(this,"store");X(this,"unauthorizedHandlers",new Set);this.baseUrl=(t.baseUrl??L2()).replace(/\/+$/,""),this.fetchImpl=t.fetchImpl??sw(),this.store=t.store??T2()}isPaired(){return this.store.getItem(Su)==="1"}markPaired(){this.store.setItem(Su,"1")}forget(){this.store.removeItem(Su)}async logout(){try{await this.fetchImpl(`${this.baseUrl}/api/logout`,{method:"POST",credentials:"same-origin"})}catch{}finally{this.forget()}}async pair(t,n){let r;try{r=await this.fetchImpl(`${this.baseUrl}/api/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,name:n})})}catch(i){throw{code:"TRANSPORT_ERROR",message:`Impossible de joindre le serveur : ${String(i)}`}}if(!r.ok){let i;try{i=await r.json()}catch{i=void 0}throw R2(i,r.status)}this.markPaired()}notifyUnauthorized(){this.forget();for(const t of this.unauthorizedHandlers)t()}onUnauthorized(t){return this.unauthorizedHandlers.add(t),()=>this.unauthorizedHandlers.delete(t)}}let ku=null;function ow(){return ku||(ku=new M2),ku}let cp=null;function I2(e){cp=e}function Ih(){return cp}function sx(){cp?.disconnect()}class O2{constructor(t){this.http=t}async listDevices(){return(await this.http.request("GET","/api/devices")).devices}createPairingCode(){return this.http.request("POST","/api/pairing-code")}renameDevice(t,n){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/rename`,{name:n})}revokeDevice(t){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/revoke`)}revokeAllDevices(){return this.http.request("POST","/api/devices/revoke-all")}}class B2{constructor(t){this.http=t}listProjects(){return this.http.invoke("list_projects")}createProject(t,n){return this.http.invoke("create_project",{request:{name:t,root:n}})}openProject(t){return this.http.invoke("open_project",{projectId:t})}async closeProject(t){await this.http.invoke("close_project",{projectId:t})}readProjectContext(t){return this.http.invoke("read_project_context",{projectId:t})}async updateProjectContext(t,n){await this.http.invoke("update_project_context",{request:{projectId:t,content:n}})}}class z2{constructor(t){this.http=t}loadLayout(t,n){return this.http.invoke("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return this.http.invoke("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return this.http.invoke("list_layouts",{projectId:t})}createLayout(t,n,r){return this.http.invoke("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return this.http.invoke("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return this.http.invoke("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return this.http.invoke("set_active_layout",{request:{projectId:t,layoutId:n}})}}class F2{constructor(t){this.http=t}status(t){return this.http.invoke("git_status",{projectId:t})}async stage(t,n){await this.http.invoke("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await this.http.invoke("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return this.http.invoke("git_commit",{request:{projectId:t,message:n}})}branches(t){return this.http.invoke("git_branches",{projectId:t})}async checkout(t,n){await this.http.invoke("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return this.http.invoke("git_log",{projectId:t,limit:n})}async init(t){await this.http.invoke("git_init",{projectId:t})}graph(t,n){return this.http.invoke("git_graph",{projectId:t,limit:n})}}class $2{constructor(t){this.http=t}firstRunState(){return this.http.invoke("first_run_state")}referenceProfiles(){return this.http.invoke("reference_profiles")}detectProfiles(t){return this.http.invoke("detect_profiles",{request:{candidates:t}})}listProfiles(){return this.http.invoke("list_profiles")}saveProfile(t){return this.http.invoke("save_profile",{request:{profile:t}})}async deleteProfile(t){await this.http.invoke("delete_profile",{profileId:t})}configureProfiles(t){return this.http.invoke("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return this.http.invoke("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return this.http.invoke("list_opencode_providers")}saveOpenCodeProviderProfile(t){return this.http.invoke("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class W2{constructor(t){this.http=t}listModelServers(){return this.http.invoke("list_model_servers")}saveModelServer(t){return this.http.invoke("save_model_server",{request:{config:t}})}async deleteModelServer(t){await this.http.invoke("delete_model_server",{serverId:t})}previewModelServerCommand(t){return this.http.invoke("preview_model_server_command",{config:t})}}class H2{constructor(t){this.http=t}listTemplates(){return this.http.invoke("list_templates")}createTemplate(t){return this.http.invoke("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return this.http.invoke("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await this.http.invoke("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return this.http.invoke("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return this.http.invoke("detect_agent_drift",{projectId:t})}syncAgent(t,n){return this.http.invoke("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class U2{constructor(t){this.http=t}listSkills(t,n){return this.http.invoke("list_skills",{projectId:t,scope:n})}createSkill(t){return this.http.invoke("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,i){return this.http.invoke("update_skill",{request:{projectId:t,scope:n,skillId:r,content:i}})}async deleteSkill(t,n,r){await this.http.invoke("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,i){await this.http.invoke("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:i}})}async unassignSkill(t,n,r){await this.http.invoke("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class q2{constructor(t){this.http=t}listMemories(t){return this.http.invoke("list_memories",{projectId:t})}getMemory(t,n){return this.http.invoke("get_memory",{projectId:t,slug:n})}createMemory(t){return this.http.invoke("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,i,s){return this.http.invoke("update_memory",{request:{projectId:t,slug:n,description:r,type:i,content:s}})}async deleteMemory(t,n){await this.http.invoke("delete_memory",{projectId:t,slug:n})}readIndex(t){return this.http.invoke("read_memory_index",{projectId:t})}resolveLinks(t,n){return this.http.invoke("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return this.http.invoke("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class V2{constructor(t){this.http=t}listEmbedderProfiles(){return this.http.invoke("list_embedder_profiles")}saveEmbedderProfile(t){return this.http.invoke("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await this.http.invoke("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return this.http.invoke("describe_embedder_engines")}}class K2{constructor(t){this.http=t}getProjectPermissions(t){return this.http.invoke("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return this.http.invoke("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return this.http.invoke("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return this.http.invoke("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return this.http.invoke("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return this.http.invoke("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return this.http.invoke("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}class G2{constructor(t){this.http=t}async getProjectWorkState(t){const n=await this.http.invoke("get_project_work_state",{projectId:t});return lp(n)}async cancelBackgroundTask(t){await this.http.invoke("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await this.http.invoke("retry_background_task",{taskId:t})}}class Y2{constructor(t){this.http=t}async readPage(t,n,r){const i=await this.http.invoke("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return rw(i)}}class X2{constructor(t){this.http=t}async interrupt(t,n){await this.http.invoke("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){await this.http.invoke("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}})}async setFrontAttached(t,n){await this.http.invoke("set_front_attached",{request:{agentId:t,attached:n}})}async cancelResume(t){return this.http.invoke("cancel_resume",{agentId:t})}async setResumeAt(t,n){await this.http.invoke("set_resume_at",{agentId:t,resetsAtMs:n})}}function ot(e){throw{code:"UNSUPPORTED_ON_WEB",message:`${e} is not available in the web client (desktop-only).`}}class Q2{openViewWindow(){return ot("Detaching a panel into an OS window")}closeViewWindow(){return ot("Closing a detached OS window")}listOpenViewWindows(){return Promise.resolve([])}onViewWindowClosed(t){return Promise.resolve(()=>{})}}class J2{setFocusedProject(t){return Promise.resolve()}getFocusedProject(){return Promise.resolve(null)}onFocusedProjectChanged(t){return Promise.resolve(()=>{})}}class Z2{connect(){return ot("Remote (SSH/WSL) connection")}}class eP{async getExposureSettings(){return ot("Embedded server settings")}async saveExposureSettings(t){return ot("Embedded server settings")}async previewExposure(t){return ot("Embedded server settings")}async status(){return ot("Embedded server status")}async start(){return ot("Starting the embedded server")}async stop(){return ot("Stopping the embedded server")}onStatusChanged(t){return Promise.resolve(()=>{})}}class tP{async listPlugins(){return ot("Plugin management")}async reviewPackage(t){return ot("Plugin management")}async installFromArchive(t){return ot("Plugin management")}async installFromDirectory(t){return ot("Plugin management")}async setEnabled(t,n){return ot("Plugin management")}async uninstall(t){return ot("Plugin management")}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){return ot("Plugin management")}}function Zo(e,t,n){return{sessionId:e,...n?{assignedConversationId:n}:{},async write(r){await t.sendFireAndForget("terminal.input",{sessionId:e,bytesBase64:aw.encodeInput(r)})},async resize(r,i){await t.sendFireAndForget("terminal.resize",{sessionId:e,rows:r,cols:i})},detach(){t.detachTerminal(e)},async close(){await t.closeTerminalSession(e)}}}class nP{constructor(t,n){this.http=t,this.ws=n}health(t){return this.http.invoke("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await this.ws.ensureConnected(),this.ws.setDomainEventHandler(t),()=>this.ws.clearDomainEventHandler()}pickFolder(){return ot("Native folder picker")}pickArchiveFile(){return ot("Native file picker")}onAppExitWorkGuard(t){return Promise.resolve(()=>{})}confirmAppExit(){return ot("Confirming an app exit")}}class rP{constructor(t){this.ws=t}async openTerminal(t,n){const r=await this.ws.openTerminal({cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null,onData:n});return Zo(r.sessionId,this.ws)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:Zo(r.sessionId,this.ws),scrollback:r.scrollback}}async closeTerminal(t){await this.ws.closeTerminalSession(t)}}class iP{constructor(t,n){this.http=t,this.ws=n}listAgents(t){return this.http.invoke("list_agents",{projectId:t})}listLiveAgents(t){return this.http.invoke("list_live_agents",{projectId:t})}listResumableAgents(t){return this.http.invoke("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return this.http.invoke("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return this.http.invoke("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return this.http.invoke("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,i,s){return this.http.invoke("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:i,cols:s}})}readContext(t,n){return this.http.invoke("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await this.http.invoke("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await this.http.invoke("delete_agent",{projectId:t,agentId:n})}inspectConversation(t,n,r){return this.http.invoke("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}async launchAgent(t,n,r,i){const s=await this.ws.launchAgent({projectId:t,agentId:n,nodeId:r.nodeId??null,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,onData:i});return Zo(s.sessionId,this.ws,s.assignedConversationId)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:Zo(r.sessionId,this.ws),scrollback:r.scrollback}}}class sP{constructor(t,n){this.http=t,this.ws=n}create(t,n){return this.http.invoke("ticket_create",{request:{projectId:t,...n}})}read(t,n,r=!1){return this.http.invoke("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}list(t,n){const{statuses:r,priorities:i,...s}=n??{};return this.http.invoke("ticket_list",{request:{projectId:t,statuses:r??[],priorities:i??[],...s}})}update(t,n,r){return this.http.invoke("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await this.http.invoke("ticket_delete",{request:{projectId:t,ref:n}})}readCarnet(t,n){return this.http.invoke("ticket_read_carnet",{request:{projectId:t,ref:n}})}updateCarnet(t,n,r,i){return this.http.invoke("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:i}})}link(t,n,r,i,s){return this.http.invoke("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:i,expectedVersion:s}})}unlink(t,n,r,i,s){return this.http.invoke("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:i,kind:s}})}assign(t,n,r,i,s){return this.http.invoke("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:i,expectedVersion:s}})}async listSprints(t){return(await this.http.invoke("sprint_list",{request:{projectId:t}})).items}setTicketSprint(t,n,r,i){return r===null?this.http.invoke("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:i}}):this.http.invoke("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:i}})}createSprint(t,n){return this.http.invoke("sprint_create",{request:{projectId:t,name:n}})}renameSprint(t,n,r,i){return this.http.invoke("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:i}})}async reorderSprints(t,n){return(await this.http.invoke("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await this.http.invoke("sprint_delete",{request:{projectId:t,sprintId:n}})}openTicketChat(t,n,r){return this.http.invoke("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await this.http.invoke("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const s=(await this.ws.send("chat.send",{sessionId:t,prompt:n})).payload;s&&s.chunk&&r(s.chunk)}}function lP(e){const t=typeof window<"u"&&window.location?window.location.origin:"http://localhost",n=e.baseUrl??t,r=e.wsUrl??n.replace(/^http(s?):\/\//,(i,s)=>`ws${s}://`);return{baseUrl:n,wsUrl:r}}function aP(e={}){const{baseUrl:t,wsUrl:n}=lP(e),r=ow();let i;const s=new N2({baseUrl:t,token:e.token,onUnauthorized:()=>{r.notifyUnauthorized(),i?.disconnect()}});return i=new aw({wsUrl:n,token:e.token,onReconnectFailed:()=>{s.invoke("health",{request:null}).catch(()=>{})}}),I2(i),{system:new nP(s,i),agent:new iP(s,i),input:new X2(s),terminal:new rP(i),project:new B2(s),layout:new z2(s),git:new F2(s),remote:new Z2,profile:new $2(s),modelServer:new W2(s),desktopServer:new eP,template:new H2(s),skill:new U2(s),memory:new q2(s),embedder:new V2(s),device:new O2(s),permission:new K2(s),workState:new G2(s),conversation:new Y2(s),ticket:new sP(s,i),window:new Q2,focusedProject:new J2,uiPreferences:new iw,plugin:new tP}}function oP(e){return"http"}const cw=g.createContext(null);function uw(){return oP()}function cP(){switch(uw()){case"mock":return C2();case"http":return aP();case"tauri":return UE()}}function uP({children:e,gateways:t}){const n=g.useMemo(()=>t??cP(),[t]);return a.jsx(cw.Provider,{value:n,children:e})}function he(){const e=g.useContext(cw);if(!e)throw new Error("useGateways must be used within a ");return e}function up({cwd:e,open:t,reattach:n,sessionId:r,onSessionId:i,agentMode:s=!1,portal:l,onReady:o,refitSignal:c}){const{terminal:u}=he(),h=g.useRef(null),[d,f]=g.useState(null),p=g.useRef(t);p.current=t;const m=g.useRef(n);m.current=n;const x=g.useRef(r);x.current=r;const w=g.useRef(i);w.current=i;const v=g.useRef(u);v.current=u;const _=g.useRef(s);_.current=s;const y=g.useRef(l);y.current=l;const b=g.useRef(o);b.current=o;const C=g.useRef(null);return g.useEffect(()=>{const k=h.current,N=v.current,R=p.current??N?.openTerminal.bind(N),L=m.current??N?.reattach.bind(N);if(!k||!R)return;f(null);const S=new YN({convertEol:!1,cursorBlink:!0,fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'}),T=new JN;S.loadAddon(T);try{S.open(k)}catch{S.dispose();return}try{T.fit()}catch{}let D=!1,P=null;const I=new TextEncoder;let O="";const U=S.onData(B=>{const le=y.current;_.current&&le&&(le.onHumanData(B),le.isSuspended())||(P?P.write(I.encode(B)):O+=B)});b.current?.({send:B=>{D||S.input(B)},focus:()=>{D||S.focus()}});const G=B=>{D||S.write(B)},E=B=>{if(D){B.detach();return}P=B,_.current&&y.current?.bindHandle(B),O&&(B.write(I.encode(O)),O="")},z=B=>{if(!D){if(dP(B)==="AGENT_ALREADY_RUNNING"){S.write(`\r -\x1B[2mCellule disponible — l'agent est en cours dans une autre cellule.\x1B[0m\r -`);return}f(`Échec du lancement de l'agent : ${lx(B)}`),S.write(`\r -\x1B[31mfailed to open terminal: ${lx(B)}\x1B[0m\r -`)}},j=x.current;j&&L?L(j,G).then(({handle:B,scrollback:le})=>{if(D){B.detach();return}le.length>0&&S.write(le),E(B)}).catch(()=>{D||R({cwd:e,rows:S.rows,cols:S.cols},G).then(B=>{w.current?.(B.sessionId),E(B)}).catch(z)}):R({cwd:e,rows:S.rows,cols:S.cols},G).then(B=>{w.current?.(B.sessionId),E(B)}).catch(z);let re=0,V=S.rows,A=S.cols;const ie=8;let ee=0;const J=()=>{if(re=0,!D){if(k.clientWidth===0||k.clientHeight===0){ee{re&&cancelAnimationFrame(re),re=requestAnimationFrame(J)},Y=new ResizeObserver(W);return Y.observe(k),C.current=W,()=>{D=!0,C.current=null,re&&cancelAnimationFrame(re),Y.disconnect(),U.dispose(),y.current?.unbindHandle(),P&&P.detach(),S.dispose()}},[e]),g.useEffect(()=>{c!==void 0&&C.current?.()},[c]),a.jsxs("div",{"data-testid":"terminal-view",style:{position:"relative",width:"100%",height:"100%",minHeight:"16rem"},children:[a.jsx("div",{ref:h,style:{width:"100%",height:"100%"}}),d&&a.jsx("div",{role:"alert","data-testid":"terminal-error",style:{position:"absolute",top:0,left:0,right:0,padding:"0.5rem 0.75rem",background:"rgba(120, 20, 20, 0.92)",color:"#fff",fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:3},children:d})]})}function lx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function dP(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function hP({agentWasRunning:e,details:t,onResume:n,onNewConversation:r}){const i=e?"en cours":"clot";return a.jsx("div",{"data-testid":"resume-conversation-popup",role:"dialog","aria-label":"Reprise de conversation",style:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)"},children:a.jsxs("div",{style:{minWidth:260,maxWidth:360,padding:"16px 18px",background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:6,boxShadow:"0 8px 24px rgba(0, 0, 0, 0.5)",fontSize:13},children:[a.jsx("p",{style:{margin:"0 0 8px",fontWeight:600},children:"Reprise de conversation"}),a.jsxs("p",{style:{margin:"0 0 6px"},children:["Statut :"," ",a.jsx("span",{"data-testid":"resume-status",children:i})]}),t?.lastTopic&&a.jsxs("p",{style:{margin:"0 0 6px"},"data-testid":"resume-last-topic",children:["Dernier sujet : ",t.lastTopic]}),t?.tokenCount!==void 0&&a.jsxs("p",{style:{margin:"0 0 10px"},"data-testid":"resume-token-count",children:["Tokens : ",t.tokenCount]}),a.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[a.jsx("button",{type:"button",onClick:n,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Reprendre la dernière conversation"}),a.jsx("button",{type:"button",onClick:r,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Nouvelle conversation"})]})]})})}const Cu="\r",ax=350,fP=2e3,pP=512,mP=8,gP="[write-portal]",Ar=new TextEncoder;function xP(e){if(e.length===0)return!1;for(const t of e){const n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function vP(e,t){const{system:n,input:r}=he(),[i,s]=g.useState(!1),l=g.useRef(0),o=g.useRef([]),c=g.useRef(null),u=g.useRef(!1),h=g.useRef(!1),d=g.useRef(null),f=g.useRef(null),p=g.useRef(r);p.current=r;const m=g.useRef(t);m.current=t;const x=g.useRef(e);x.current=e;const w=g.useRef(()=>{});w.current=()=>{const y=c.current&&d.current?d.current:null,b=f.current;b!==y&&(b&&(Ze("front-attached:set",{agent:b,attached:!1}),p.current?.setFrontAttached(b,!1).catch(C=>{Ze("front-attached:set-failed",{agent:b,attached:!1,error:ju(C)})})),y&&(Ze("front-attached:set",{agent:y,attached:!0}),p.current?.setFrontAttached(y,!0).catch(C=>{Ze("front-attached:set-failed",{agent:y,attached:!0,error:ju(C)})})),f.current=y)};const v=g.useRef(()=>{});return v.current=()=>{if(h.current)return;const y=o.current[0];if(!y||l.current>0)return;const b=c.current;if(!b)return;const C=m.current,k=x.current;if(!C)return;h.current=!0;const N=Date.now();u.current=!0,s(!0),(async()=>{let R=!1;try{Ze("inject:start",{agent:C,ticket:y.ticket,textBytes:Ar.encode(y.text).byteLength,queue:o.current.length,submitSequence:fo(y.submitSequence),submitDelayMs:y.submitDelayMs??ax}),await Promise.resolve();const L=l.current;L>0&&(Ze("inject:erase-human-window",{agent:C,ticket:y.ticket,count:L}),await b.write(Ar.encode("".repeat(L))),l.current=0),await _P(b,y.text,y.ticket);const S=y.submitDelayMs??ax;Ze("inject:before-submit-delay",{agent:C,ticket:y.ticket,delay:S}),await Oh(S);const T=yP(y.submitSequence,y.ticket);Ze("inject:submit-write:start",{agent:C,ticket:y.ticket,submitSequence:fo(T),submitBytes:Ar.encode(T).byteLength}),await b.write(Ar.encode(T)),Ze("inject:submit-write:ok",{agent:C,ticket:y.ticket}),o.current.shift(),R=!0;try{Ze("inject:ack:start",{agent:C,ticket:y.ticket}),await p.current.delegationDelivered(k,C,y.ticket),Ze("inject:ack:ok",{agent:C,ticket:y.ticket})}catch{Ze("inject:ack:failed",{agent:C,ticket:y.ticket})}}catch(L){Ze("inject:failed",{agent:C,ticket:y.ticket,error:ju(L)})}finally{const L=Date.now()-N,S=fP-L;S>0&&await Oh(S),u.current=!1,s(!1),h.current=!1,o.current.length>0&&R&&v.current()}})()},g.useEffect(()=>{if(!n||!t){d.current=null,w.current();return}let y,b=!1;const C=t;return n.onDomainEvent(k=>{k.type==="delegationReady"&&k.agentId===C&&(o.current.push({ticket:k.ticket,text:k.text,submitSequence:k.submitSequence,submitDelayMs:k.submitDelayMs}),Ze("event:delegation-ready",{agent:C,ticket:k.ticket,textBytes:Ar.encode(k.text).byteLength,queue:o.current.length,submitSequence:fo(k.submitSequence),submitDelayMs:k.submitDelayMs}),v.current())}).then(k=>{b?k():(y=k,d.current=C,Ze("event:subscribed",{agent:C}),w.current())}),()=>{b=!0,y?.(),d.current===C&&(d.current=null,Ze("event:unsubscribed",{agent:C})),f.current===C?(p.current?.setFrontAttached(C,!1).catch(()=>{}),f.current=null):w.current()}},[n,t]),{portal:g.useMemo(()=>({onHumanData(y){if(y==="\r"||y===` -`||y===""){l.current=0,v.current();return}xP(y)&&(l.current+=1)},isSuspended(){return u.current},bindHandle(y){c.current=y,Ze("handle:bound",{agent:m.current,sessionId:y.sessionId}),w.current(),v.current()},unbindHandle(){Ze("handle:unbound",{agent:m.current,sessionId:c.current?.sessionId}),c.current=null,w.current()}}),[]),overlay:i}}function Oh(e){return new Promise(t=>setTimeout(t,e))}async function _P(e,t,n){const r=bP(t,pP);for(let i=0;i0?e:(Ze("inject:empty-submit-sequence-defaulted",{ticket:t,defaultSubmitSequence:fo(Cu)}),Cu)}function bP(e,t){if(e.length===0)return[""];const n=[];let r="",i=0;for(const s of e){const l=Ar.encode(s).byteLength;r.length>0&&i+l>t&&(n.push(r),r="",i=0),r+=s,i+=l}return r.length>0&&n.push(r),n}function fo(e){return e==null?"":e.length===0?"":[...e].map(t=>{switch(t){case"\r":return"\\r";case` -`:return"\\n";case"":return"\\x7f";default:{const n=t.codePointAt(0);return n<32?`\\x${n.toString(16).padStart(2,"0")}`:t}}}).join("")}function ju(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Ze(e,t){console.info(gP,e,t)}function wP(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function ea(e){const{workState:t,system:n}=he(),[r,i]=g.useState(null),[s,l]=g.useState(null),[o,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{i(await t.getProjectWorkState(e))}catch(h){l(wP(h))}finally{c(!1)}},[e,t]);return g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let h,d=!1;return n.onDomainEvent(f=>{(f.type==="agentLaunched"||f.type==="agentExited"||f.type==="agentBusyChanged"||f.type==="delegationReady"||f.type==="orchestratorRequestProcessed"||f.type==="backgroundTaskChanged"||f.type==="agentInboxChanged"||f.type==="agentWakeChanged")&&u()}).then(f=>{d?f():h=f}),()=>{d=!0,h?.()}},[u,n]),{state:r,error:s,busy:o,refresh:u}}const SP=50;function dw(){return{byTarget:{},nextSeq:1}}function kP(e,t,n=SP){const{target:r,ticketId:i}=t,s={...t,seq:e.nextSeq},l=e.byTarget[r]??{},c=[...l[i]??[],s],u=c.length>n?c.slice(c.length-n):c;return{byTarget:{...e.byTarget,[r]:{...l,[i]:u}},nextSeq:e.nextSeq+1}}function CP(e,t){if(!(t in e.byTarget))return e;const{[t]:n,...r}=e.byTarget;return{byTarget:r,nextSeq:e.nextSeq}}function hw(e,t){return e.atMs-t.atMs||e.seq-t.seq}function jP(e,t){const n=e.byTarget[t];return n?Object.values(n).flat().sort(hw):[]}function NP(e,t,n){const r=[];for(const i of Object.values(e.byTarget))for(const[s,l]of Object.entries(i))if(!(n!==void 0&&s!==n))for(const o of l)o.requester===t&&r.push(o);return r.sort(hw)}const EP=()=>{},PP=dw(),AP={},TP={index:PP,busy:AP,seedBusy:EP},dp=g.createContext(null);function LP({children:e}){const{system:t}=he(),[n,r]=g.useState(dw),[i,s]=g.useState({}),l=g.useCallback((c,u)=>{s(h=>c in h?h:{...h,[c]:u})},[]);g.useEffect(()=>{if(!t)return;let c,u=!1;return t.onDomainEvent(h=>{if(h.type==="agentAnnouncement")r(d=>kP(d,{requester:h.requester,target:h.target,ticketId:h.ticketId,text:h.text,atMs:h.atMs}));else if(h.type==="agentBusyChanged"){const{agentId:d,busy:f}=h;s(p=>({...p,[d]:f})),f||r(p=>CP(p,d))}}).then(h=>{u?h():c=h}).catch(()=>{}),()=>{u=!0,c?.()}},[t]);const o=g.useMemo(()=>({index:n,busy:i,seedBusy:l}),[n,i,l]);return a.jsx(dp.Provider,{value:o,children:e})}function hp(){return g.useContext(dp)??TP}function DP(){return g.useContext(dp)!==null}function fw(e){const{index:t,busy:n}=hp();return g.useMemo(()=>({announcements:jP(t,e),active:n[e]===!0}),[t,n,e])}function RP(e,t){const{workState:n}=he(),{seedBusy:r}=hp(),i=DP();g.useEffect(()=>{if(!i||!n)return;let s=!1;return n.getProjectWorkState(e).then(l=>{if(s)return;const o=l.agents.find(c=>c.agentId===t);o&&r(t,o.busy.state==="busy")}).catch(()=>{}),()=>{s=!0}},[i,n,e,t,r])}function MP(e,t){const{index:n}=hp();return g.useMemo(()=>NP(n,e,t),[n,e,t])}function q(...e){return e.filter(Boolean).join(" ")}function Re({size:e=16,className:t,label:n="Loading"}){return a.jsx("span",{role:"status","aria-label":n,className:q("inline-block animate-spin rounded-full border-2 border-current border-t-transparent",t),style:{width:e,height:e}})}const IP="inline-flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors select-none disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none",OP={sm:"h-7 px-2.5 text-xs",md:"h-9 px-3.5 text-sm"},BP={primary:"bg-primary text-on-primary hover:bg-primary-hover",secondary:"bg-raised text-content border border-border hover:border-border-strong",ghost:"text-muted hover:text-content hover:bg-raised",danger:"bg-danger text-white hover:brightness-110"},M=g.forwardRef(function({variant:t="secondary",size:n="md",loading:r=!1,disabled:i,className:s,children:l,...o},c){return a.jsxs("button",{ref:c,type:o.type??"button",disabled:i||r,className:q(IP,OP[n],BP[t],s),...o,children:[r&&a.jsx(Re,{size:n==="sm"?12:14}),l]})}),zP={sm:"h-6 w-6 text-xs",md:"h-8 w-8 text-sm"},ir=g.forwardRef(function({size:t="md",className:n,children:r,...i},s){return a.jsx("button",{ref:s,type:i.type??"button",className:q("inline-flex items-center justify-center rounded-md text-muted transition-colors","hover:bg-raised hover:text-content focus-visible:outline-none","disabled:opacity-50 disabled:cursor-not-allowed",zP[t],n),...i,children:r})}),ce=g.forwardRef(function({invalid:t=!1,className:n,...r},i){return a.jsx("input",{ref:i,"aria-invalid":t||void 0,className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border placeholder:text-faint outline-none transition-colors",t?"border-danger":"border-border focus:border-primary","disabled:opacity-50 disabled:cursor-not-allowed",n),...r})});function qt({label:e,hint:t,error:n,hideLabel:r,className:i,children:s}){const l=g.useId(),o=`${l}-msg`,c=n??t;return a.jsxs("div",{className:q("flex flex-col gap-1",i),children:[a.jsx("label",{htmlFor:l,className:q("text-xs font-medium text-muted",r&&"sr-only"),children:e}),s({id:l,describedBy:c?o:void 0}),c&&a.jsx("p",{id:o,role:n?"alert":void 0,className:q("text-xs",n?"text-danger":"text-faint"),children:c})]})}function we({title:e,actions:t,flush:n,className:r,children:i,...s}){const l=e!=null||t!=null;return a.jsxs("section",{className:q("rounded-lg border border-border bg-surface",r),...s,children:[l&&a.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-2.5",children:[typeof e=="string"?a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}):e,t]}),a.jsx("div",{className:q(!n&&"p-4"),children:i})]})}function FP({items:e,value:t,onSelect:n,onClose:r,className:i}){return a.jsx("div",{role:"tablist",className:q("flex flex-wrap items-stretch gap-1",i),children:e.map(s=>{const l=s.id===t;return a.jsxs("div",{className:q("group flex items-center gap-1 rounded-md border px-1 transition-colors",l?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[a.jsx("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>n(s.id),className:q("px-2 py-1 text-sm focus-visible:outline-none",l?"font-semibold text-content":"text-muted hover:text-content"),children:s.label}),r&&a.jsx(ir,{size:"sm","aria-label":`close ${s.label}`,onClick:()=>r(s.id),className:"opacity-60 group-hover:opacity-100",children:"×"})]},s.id)})})}const $P={start:"justify-start",between:"justify-between",end:"justify-end"};function pw({justify:e="start",className:t,children:n,...r}){return a.jsx("div",{role:"toolbar",className:q("flex items-center gap-2",$P[e],t),...r,children:n})}const kn={menuDropdown:40,floatingWindow:50,floatingWindowNested:60,toast:70},WP={sm:"max-w-sm",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"},ox='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',Us=[];function Bh({open:e,title:t,onClose:n,size:r="md",children:i}){return e?a.jsx(HP,{title:t,onClose:n,size:r,children:i}):null}function HP({title:e,onClose:t,size:n,children:r}){const i=g.useRef(null),s=g.useRef(t);return s.current=t,g.useEffect(()=>{const l=document.activeElement,o=i.current,c={};Us.push(c);const u=()=>Us[Us.length-1]===c;(o?.querySelector(ox)??o)?.focus();function d(f){if(!u())return;if(f.key==="Escape"){f.preventDefault(),s.current();return}if(f.key!=="Tab"||!o)return;const p=Array.from(o.querySelectorAll(ox));if(p.length===0){f.preventDefault(),o.focus();return}const m=p[0],x=p[p.length-1],w=document.activeElement;f.shiftKey&&w===m?(f.preventDefault(),x.focus()):!f.shiftKey&&w===x&&(f.preventDefault(),m.focus())}return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d);const f=Us.indexOf(c);f>=0&&Us.splice(f,1),l?.focus?.()}},[]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:kn.floatingWindow},onMouseDown:l=>{l.target===l.currentTarget&&t()},children:a.jsxs("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":e,tabIndex:-1,className:q("flex max-h-[80vh] w-full flex-col overflow-hidden rounded-lg","border border-border bg-surface shadow-xl outline-none",WP[n??"md"]),children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:e}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`close ${e}`,onClick:t,children:"Close"})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})})}function UP({menus:e,className:t}){const[n,r]=g.useState(null),[i,s]=g.useState(null),l=g.useRef(null);function o(){r(null),s(null)}return g.useEffect(()=>{if(n===null)return;function c(h){l.current?.contains(h.target)||o()}function u(h){h.key==="Escape"&&o()}return document.addEventListener("mousedown",c),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("keydown",u)}},[n]),a.jsx("div",{ref:l,className:q("flex shrink-0 items-center gap-0.5 border-b border-border bg-surface px-2 py-1",t),children:e.map(c=>{const u=n===c.id;return a.jsxs("div",{className:"relative",children:[a.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":u,onClick:()=>{s(null),r(h=>h===c.id?null:c.id)},className:q("rounded px-2.5 py-1 text-sm transition-colors",u?"bg-raised text-content":"text-muted hover:bg-raised hover:text-content"),children:c.label}),u&&a.jsx("div",{role:"menu","aria-label":c.label,style:{zIndex:kn.menuDropdown},className:q("absolute left-0 top-full mt-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:c.items.map(h=>{const d=(h.submenu?.length??0)>0,f=d&&i===h.id;return a.jsxs("div",{className:"relative",onMouseEnter:()=>s(d?h.id:null),children:[a.jsxs("button",{type:"button",disabled:h.disabled,"aria-haspopup":d?"menu":void 0,"aria-expanded":d?f:void 0,onClick:()=>{if(d){s(p=>p===h.id?null:h.id);return}h.onSelect(),o()},className:q("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[a.jsx("span",{children:h.label}),d?a.jsx("span",{"aria-hidden":!0,className:"text-muted",children:h.active?"● ▸":"▸"}):h.active&&a.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]}),f&&a.jsx("div",{role:"menu","aria-label":h.label,style:{zIndex:kn.floatingWindowNested},className:q("absolute left-full top-0 ml-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:h.submenu.map(p=>a.jsxs("button",{type:"button",disabled:p.disabled,onClick:()=>{p.onSelect(),o()},className:q("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[a.jsx("span",{children:p.label}),p.active&&a.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]},p.id))})]},h.id)})})]},c.id)})})}const qP=240,VP=720;function cx({side:e,width:t,onResize:n,minWidth:r=qP,maxWidth:i=VP,"aria-label":s,children:l}){const o=g.useRef(null);function c(p){return Math.min(i,Math.max(r,p))}function u(p){p.preventDefault(),p.currentTarget.setPointerCapture?.(p.pointerId),o.current={startX:p.clientX,startWidth:t}}function h(p){const m=o.current;if(!m)return;const x=p.clientX-m.startX,w=e==="left"?x:-x;n(c(m.startWidth+w))}function d(p){if(!o.current)return;const m=p.clientX-o.current.startX,x=e==="left"?m:-m;o.current=null,n(c(t+x))}const f=a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":`resize ${e} dock`,onPointerDown:u,onPointerMove:h,onPointerUp:d,className:"shrink-0 cursor-col-resize bg-border hover:bg-border-strong",style:{flex:"0 0 4px",touchAction:"none"}});return a.jsxs("aside",{"aria-label":s??`${e} dock`,className:q("flex h-full shrink-0 bg-surface",e==="left"?"flex-row border-r border-border":"flex-row-reverse border-l border-border"),style:{width:t},children:[a.jsx("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:l}),f]})}function KP(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleTimeString()}catch{return""}}function GP({projectId:e,agentId:t}){RP(e,t);const{announcements:n,active:r}=fw(t),i=g.useRef(null);return g.useEffect(()=>{const s=i.current;s&&(s.scrollTop=s.scrollHeight)},[n]),r?a.jsxs("div",{"data-testid":"target-announcements-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-[4] flex flex-col bg-canvas/85 backdrop-blur-sm",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-surface/80 px-4 py-2",children:[a.jsx(Re,{size:14}),a.jsx("span",{className:"text-sm font-medium text-content",children:"Un agent est en train de lui parler…"})]}),a.jsx("div",{ref:i,className:"flex flex-1 flex-col justify-end gap-1.5 overflow-hidden px-6 py-4",children:n.map(s=>{const l=KP(s.atMs);return a.jsxs("div",{className:"flex items-baseline gap-2 text-sm text-muted",children:[l&&a.jsx("span",{className:"shrink-0 text-xs text-faint",children:l}),a.jsx("span",{className:"whitespace-pre-wrap break-words text-content/90",children:s.text})]},s.seq)})})]}):null}function YP({requester:e,ticketId:t,limit:n=3}){const r=MP(e,t);if(r.length===0)return null;const i=r.slice(Math.max(0,r.length-n));return a.jsxs("div",{"data-testid":"announcements-preview",className:"flex flex-col gap-1 rounded-md border border-primary/25 bg-primary/5 px-2.5 py-1.5",children:[a.jsxs("span",{className:"flex items-center gap-1.5 text-[0.65rem] font-medium uppercase tracking-wide text-primary",children:[a.jsx("span",{"aria-hidden":!0,className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-primary"}),"En attente d'un agent"]}),a.jsx("ul",{className:"flex flex-col gap-0.5",children:i.map(s=>a.jsx("li",{className:"truncate text-xs text-muted",title:s.text,children:s.text},s.seq))})]})}class XP{constructor(t,n){X(this,"handlers",new Map);this.pluginId=t,this.declaredCommandIds=n}register(t,n){if(!this.declaredCommandIds.has(t))throw new Error(`plugin "${this.pluginId}" tried to register command "${t}" which is not declared by any menu item in its manifest`);return this.handlers.set(t,n),{dispose:()=>{this.handlers.get(t)===n&&this.handlers.delete(t)}}}async run(t,...n){const r=this.handlers.get(t);r&&await r(...n)}has(t){return this.handlers.has(t)}}class QP{constructor(t,n){X(this,"components",new Map);this.pluginId=t,this.declaredLayoutTypes=n}register(t){if(!this.declaredLayoutTypes.has(t.type))throw new Error(`plugin "${this.pluginId}" tried to register layout type "${t.type}" which is not declared in its manifest`);return this.components.set(t.type,t.component),{dispose:()=>{this.components.get(t.type)===t.component&&this.components.delete(t.type)}}}get(t){return this.components.get(t)}}class JP{constructor(t){this.pluginId=t}get ownerPluginId(){return this.pluginId}}class fp{constructor(){X(this,"loaded",new Map)}add(t){this.loaded.set(t.pluginId,t)}async remove(t){const n=this.loaded.get(t);if(n)try{await n.dispose()}finally{this.loaded.delete(t)}}get(t){return this.loaded.get(t)}list(){return[...this.loaded.values()]}topLevelMenus(){return this.list().flatMap(t=>t.contributes.menus.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,menu:n})))}menuItems(){return this.list().flatMap(t=>t.contributes.menuItems.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,item:n})))}layoutComponent(t,n){return this.loaded.get(t)?.layouts.get(n)}layoutContributions(){return this.list().flatMap(t=>t.contributes.layouts.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,layout:n})))}async runCommand(t,n,...r){await this.loaded.get(t)?.commands.run(n,...r)}}function ZP(e){return typeof e=="object"&&e!==null&&"activate"in e&&typeof e.activate=="function"}async function eA(e,t){try{const n=await import(e.bundleUrl);if(!ZP(n))return{failure:{pluginId:e.id,reason:'bundle does not export an "activate(ctx)" function'}};const r=new Set(e.contributes.menuItems.map(d=>d.command)),i=new Set(e.contributes.layouts.map(d=>d.type)),s=new XP(e.id,r),l=new QP(e.id,i),o=new JP(e.id),c={pluginId:e.id,pluginDisplayName:e.displayName,version:e.version,commands:s,layouts:l,menu:o,...t},u=await n.activate(c);return{plugin:{pluginId:e.id,displayName:e.displayName,contributes:e.contributes,commands:s,layouts:l,menu:o,dispose:async()=>{try{await u.dispose?.()}catch{}}}}}catch(n){return{failure:{pluginId:e.id,reason:n instanceof Error?n.message:String(n)}}}}async function tA(e,t){const n=new fp,r=[],i=await Promise.all(e.map(s=>eA(s,t)));for(const s of i)"failure"in s?r.push(s.failure):n.add(s.plugin);return{registry:n,failures:r}}const nA=new Set(["projectOpen","gitRepository","agentSelected","terminalFocused","layoutCellFocused"]);function rA(e){const t=[];let n=0;for(;n=this.tokens.length}}function sA(e,t){if(e===void 0||e.trim()==="")return{ok:!0,value:!0};const n=rA(e);if(!n)return{ok:!1,reason:`invalid "when" expression: ${e}`};try{const r=new iA(n),i=r.parseOr(t);if(!r.finished())throw new Error("unexpected trailing tokens");return{ok:!0,value:i}}catch(r){const i=r instanceof Error?r.message:String(r);return{ok:!1,reason:`invalid "when" expression "${e}": ${i}`}}}const lA={registry:new fp,failures:[],loading:!1},mw=g.createContext(lA);function aA({children:e,value:t}){const n=he(),[r,i]=g.useState(t??{registry:new fp,failures:[],loading:!0});return g.useEffect(()=>{if(t)return;let s=!1;return n.plugin.listRuntimeContributions().then(l=>tA(l.plugins,{project:n.project,git:n.git,terminal:n.terminal,agents:n.agent,system:n.system})).then(l=>{s||i({registry:l.registry,failures:l.failures,loading:!1})}).catch(()=>{s||i(l=>({...l,loading:!1}))}),()=>{s=!0}},[]),a.jsx(mw.Provider,{value:r,children:e})}function pp(){return g.useContext(mw)}function ux({title:e,body:t,confirmLabel:n,danger:r=!1,busy:i=!1,onConfirm:s,onCancel:l}){const o=g.useRef(null);return g.useEffect(()=>{o.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.floatingWindow},onClick:l,children:a.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-md flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"whitespace-pre-line text-sm text-muted",children:t}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{ref:o,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),a.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:i,onClick:()=>void s(),children:n})]})]})})}function ei(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function oA(){const{plugin:e,system:t}=he(),[n,r]=g.useState([]),[i,s]=g.useState(null),[l,o]=g.useState(!1),c=g.useCallback(async()=>{o(!0),s(null);try{r(await e.listPlugins())}catch(y){s(ei(y))}finally{o(!1)}},[e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async y=>{o(!0),s(null);try{return await e.reviewPackage(y)}catch(b){return s(ei(b)),null}finally{o(!1)}},[e]),h=g.useCallback(y=>u({sourceKind:"archive",path:y}),[u]),d=g.useCallback(y=>u({sourceKind:"directory",path:y}),[u]),f=g.useCallback(async y=>{o(!0),s(null);try{const b=await e.installFromArchive(y);return r(C=>[...C.filter(k=>k.id!==b.plugin.id),b.plugin]),!0}catch(b){return s(ei(b)),!1}finally{o(!1)}},[e]),p=g.useCallback(async y=>{o(!0),s(null);try{const b=await e.installFromDirectory(y);return r(C=>[...C.filter(k=>k.id!==b.plugin.id),b.plugin]),!0}catch(b){return s(ei(b)),!1}finally{o(!1)}},[e]),m=g.useCallback(async(y,b)=>{o(!0),s(null);try{const C=await e.setEnabled(y,b);r(k=>k.map(N=>N.id===y?C:N))}catch(C){s(ei(C))}finally{o(!1)}},[e]),x=g.useCallback(async y=>{o(!0),s(null);try{await e.uninstall(y),r(b=>b.filter(C=>C.id!==y))}catch(b){s(ei(b))}finally{o(!1)}},[e]),w=g.useCallback(async y=>{try{await e.openPluginsFolder(y)}catch(b){s(ei(b))}},[e]),v=g.useCallback(()=>t.pickArchiveFile(),[t]),_=g.useCallback(()=>t.pickFolder(),[t]);return{plugins:n,error:i,busy:l,refresh:c,reviewArchive:h,reviewDirectory:d,installFromArchive:f,installFromDirectory:p,setEnabled:m,uninstall:x,openPluginsFolder:w,pickArchiveFile:v,pickDirectory:_}}const cA={enabled:"Activé",disabled:"Désactivé","pending-enable":"Activation en attente","pending-disable":"Désactivation en attente","pending-uninstall":"Désinstallation en attente",invalid:"Invalide"};function uA(){const e=oA(),[t,n]=g.useState(null),[r,i]=g.useState(null),[s,l]=g.useState(null);async function o(){l(null);const d=await e.pickArchiveFile();if(!d)return;const f=await e.reviewArchive(d);if(!f){l("La revue du paquet a échoué.");return}i({sourceKind:"archive",path:d,review:f})}async function c(){l(null);const d=await e.pickDirectory();if(!d)return;const f=await e.reviewDirectory(d);if(!f){l("La revue du paquet a échoué.");return}i({sourceKind:"directory",path:d,review:f})}async function u(){if(!r)return;(r.sourceKind==="archive"?await e.installFromArchive(r.path):await e.installFromDirectory(r.path))&&i(null)}async function h(){t&&(t.kind==="disable"?await e.setEnabled(t.plugin.id,!1):await e.uninstall(t.plugin.id),n(null))}return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:"Plugins"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{size:"sm",onClick:()=>void o(),disabled:e.busy,children:"Installer depuis une archive…"}),a.jsx(M,{size:"sm",variant:"secondary",onClick:()=>void c(),disabled:e.busy,children:"Installer depuis un dossier…"})]})]}),(e.error||s)&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error??s}),e.plugins.length===0?a.jsx(we,{children:a.jsx("p",{className:"text-sm text-muted",children:"Aucun plugin installé."})}):a.jsx("ul",{className:"flex flex-col gap-2",children:e.plugins.map(d=>a.jsx("li",{children:a.jsxs(we,{className:"flex items-center justify-between gap-4",children:[a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:d.displayName}),a.jsxs("span",{className:"text-xs text-faint",children:["v",d.version]}),d.publisher&&a.jsxs("span",{className:"text-xs text-faint",children:["· ",d.publisher]}),a.jsx("span",{className:"rounded bg-raised px-1.5 py-0.5 text-[0.65rem] uppercase text-muted",children:"full-trust"})]}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted",children:[a.jsx("span",{"aria-label":"plugin state",className:d.lifecycleState==="invalid"?"text-danger":void 0,children:cA[d.lifecycleState]}),d.restartRequired&&a.jsx("span",{className:"text-warning",children:"Redémarrage requis"}),d.sourceLabel&&a.jsxs("span",{children:["· ",d.sourceLabel]})]}),d.error&&a.jsx("p",{className:"text-xs text-danger",role:"alert",children:d.error})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[d.enabled?a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>n({kind:"disable",plugin:d}),disabled:e.busy,children:"Désactiver"}):a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.setEnabled(d.id,!0),disabled:e.busy,children:"Activer"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.openPluginsFolder(d.id),disabled:e.busy,children:"Ouvrir le dossier"}),a.jsx(M,{size:"sm",variant:"danger",onClick:()=>n({kind:"uninstall",plugin:d}),disabled:e.busy,children:"Désinstaller"})]})]})},d.id))}),r&&a.jsx(ux,{title:`Installer "${r.review.displayName}" ?`,body:dA(r.review),confirmLabel:r.review.installable?"Installer":"Corriger avant d'installer",busy:e.busy,danger:!r.review.installable,onConfirm:()=>{r.review.installable?u():i(null)},onCancel:()=>i(null)}),t&&a.jsx(ux,{title:t.kind==="disable"?`Désactiver "${t.plugin.displayName}" ?`:`Désinstaller "${t.plugin.displayName}" ?`,body:t.kind==="disable"?"Ses contributions seront masquées immédiatement ; un redémarrage sera peut-être nécessaire pour purger complètement le plugin.":"Le plugin, ses fichiers et ses contributions seront supprimés après redémarrage.",confirmLabel:t.kind==="disable"?"Désactiver":"Désinstaller",danger:t.kind==="uninstall",busy:e.busy,onConfirm:()=>void h(),onCancel:()=>n(null)})]})}function dA(e){const{contributionSummary:t}=e;return[`Éditeur : ${e.publisher??"inconnu"}`,`Version : ${e.version}`,e.description??null,"Confiance : full-trust — ce plugin peut exécuter du code arbitraire dans IdeA.",`Contributions : ${t.topLevelMenus} menu(s), ${t.menuItems} item(s), ${t.layouts} layout(s), ${t.mcpServers} serveur(s) MCP.`,...e.issues.map(r=>`${r.severity==="error"?"Erreur":"Avertissement"} : ${r.message}`)].filter(r=>!!r).join(` -`)}function hA(e){return e.topLevelMenus().map(({pluginId:t,pluginDisplayName:n,menu:r})=>({id:`plugin:${r.id}`,pluginId:t,pluginDisplayName:n,label:r.label,icon:r.icon,order:r.order??0})).sort((t,n)=>t.order-n.order||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.label.localeCompare(n.label))}function fA(e,t,n){return e.menuItems().filter(({item:r})=>r.targetMenuId===t).map(({pluginId:r,pluginDisplayName:i,item:s})=>{const l=sA(s.when,n);return{id:s.id,pluginId:r,pluginDisplayName:i,targetMenuId:s.targetMenuId,label:s.label,command:s.command,enabled:l.ok?l.value:!1,disabledReason:l.ok?void 0:l.reason,groupLabel:i,order:s.order??0,iconUrl:s.icon}}).sort((r,i)=>r.order-i.order||r.pluginDisplayName.localeCompare(i.pluginDisplayName)||r.label.localeCompare(i.label))}function pA(e,t){const n=g.useMemo(()=>(s,l)=>e.runCommand(s,l),[e]),r=g.useMemo(()=>s=>fA(e,s,t).map(l=>({id:l.id,label:`${l.label} · ${l.pluginDisplayName}`,disabled:!l.enabled,onSelect:()=>{n(l.pluginId,l.command)}})),[e,t,n]);return{topLevelMenus:g.useMemo(()=>hA(e).map(s=>({id:s.id,label:s.label,items:r(s.id)})),[e,r]),itemsFor:r,runCommand:n}}function mA(e,t,n){const r=e.get(t.pluginId);if(!r){const l=n?.find(o=>o.id===t.pluginId);return l&&!l.enabled?"plugin-disabled":"plugin-missing"}return!r.contributes.layouts.some(l=>l.type===t.layoutType)||!r.layouts.get(t.layoutType)?"incompatible":"available"}const gA={"plugin-disabled":"Le plugin fournisseur est désactivé.","plugin-missing":"Le plugin fournisseur n'est pas installé.",incompatible:"Le plugin fournisseur ne déclare plus ce type de layout."};function xA({cell:e,availability:t,providerDisplayName:n,onOpenPlugins:r,onChooseAnotherLayout:i}){return a.jsxs(we,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[a.jsx("p",{className:"text-sm font-semibold text-content",children:"Layout indisponible"}),a.jsx("p",{className:"text-xs text-muted",children:gA[t]}),a.jsxs("p",{className:"text-xs text-faint",children:["Fourni par « ",n??e.pluginId," »"]}),a.jsxs("div",{className:"mt-2 flex gap-2",children:[a.jsx(M,{size:"sm",variant:"secondary",onClick:r,children:"Ouvrir Plugins"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:i,children:"Choisir un autre layout"})]})]})}function vA({projectId:e,cell:t,installedPlugins:n,onStateChange:r,onOpenPlugins:i,onChooseAnotherLayout:s}){const{registry:l}=pp(),o=he(),c=mA(l,t,n);if(c!=="available"){const h=l.get(t.pluginId)?.displayName??n?.find(d=>d.id===t.pluginId)?.displayName;return a.jsx(xA,{cell:t,availability:c,providerDisplayName:h,onOpenPlugins:i,onChooseAnotherLayout:s})}const u=l.layoutComponent(t.pluginId,t.layoutType);return a.jsx(u,{projectId:e,nodeId:t.id,layoutType:t.layoutType,state:t.state,setState:r,availability:"available",gateways:{project:o.project,git:o.git,terminal:o.terminal,agents:o.agent,system:o.system}})}function _A(e){return e.layoutContributions().map(({pluginId:t,pluginDisplayName:n,layout:r})=>({pluginId:t,pluginDisplayName:n,layout:r})).sort((t,n)=>(t.layout.order??0)-(n.layout.order??0)||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.layout.label.localeCompare(n.layout.label))}function yA({registry:e,onSelect:t}){const n=_A(e);return n.length===0?null:a.jsxs("div",{role:"group","aria-label":"Layouts plugins",children:[a.jsx("p",{className:"px-3 pt-2 text-[0.65rem] font-semibold uppercase tracking-wide text-faint",children:"Layouts plugins"}),n.map(r=>a.jsxs("button",{type:"button",role:"menuitem","aria-label":`create ${r.layout.label} layout`,onClick:()=>t(r),className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm text-content hover:bg-raised",children:[a.jsx("span",{children:r.layout.label}),a.jsx("span",{className:"text-xs text-faint",children:r.pluginDisplayName})]},`${r.pluginId}:${r.layout.type}`))]})}function dx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function bA(e){const{template:t}=he(),[n,r]=g.useState([]),[i,s]=g.useState(!1),[l,o]=g.useState(null),c=g.useCallback(async()=>{s(!0),o(null);try{const d=await t.detectDrift(e);r(d)}catch(d){o(dx(d))}finally{s(!1)}},[t,e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async(d,f)=>{s(!0),o(null);try{await t.syncAgent(e,d),f&&await f();const p=await t.detectDrift(e);r(p)}catch(p){o(dx(p))}finally{s(!1)}},[t,e]);return{driftByAgentId:new Map(n.map(d=>[d.agentId,d])),driftBusy:i,driftError:l,refreshDrift:c,syncAgent:u}}function Bn(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function wA(e){const{agent:t,profile:n,system:r,terminal:i,input:s}=he(),[l,o]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState([]),[w,v]=g.useState(null),[_,y]=g.useState(!1),[b,C]=g.useState(null),[k,N]=g.useState({}),[R,L]=g.useState({}),[S,T]=g.useState({}),[D,P]=g.useState({}),I=g.useCallback(async()=>{y(!0),v(null);try{const[ee,J]=await Promise.all([t.listAgents(e),n.listProfiles()]);o(ee),p(J)}catch(ee){v(Bn(ee))}finally{y(!1)}},[t,n,e]),O=g.useCallback(async()=>{try{x(await t.listLiveAgents(e))}catch{x([])}},[t,e]);g.useEffect(()=>{I()},[I]),g.useEffect(()=>{O()},[O]),g.useEffect(()=>{if(!r)return;let ee,J=!1;return r.onDomainEvent(W=>{if((W.type==="agentLaunched"||W.type==="agentExited"||W.type==="agentProfileChanged")&&(I(),O()),W.type==="agentLaunched"&&P(Y=>{if(!(W.agentId in Y))return Y;const{[W.agentId]:B,...le}=Y;return le}),W.type==="orchestratorRequestProcessed"&&W.source!==void 0){const{requesterId:Y,source:B}=W;N(le=>le[Y]===B?le:{...le,[Y]:B})}switch(W.type){case"agentRateLimited":L(Y=>({...Y,[W.agentId]:{limitedUntil:W.resetsAtMs,resumeFireAt:Y[W.agentId]?.resumeFireAt,suspected:!1}}));break;case"agentResumeScheduled":L(Y=>({...Y,[W.agentId]:{...Y[W.agentId],resumeFireAt:W.fireAtMs}}));break;case"agentResumeCancelled":L(Y=>{const B=Y[W.agentId];if(!B)return Y;const{resumeFireAt:le,...je}=B;return{...Y,[W.agentId]:je}});break;case"agentResumed":L(Y=>{if(!(W.agentId in Y))return Y;const{[W.agentId]:B,...le}=Y;return le});break;case"agentRateLimitSuspected":L(Y=>({...Y,[W.agentId]:{...Y[W.agentId],limitedUntil:W.resetsAtMs,suspected:!0}}));break;case"modelServerStatusChanged":T(Y=>({...Y,[W.serverId]:W.status}));break;case"agentLaunchFailed":P(Y=>({...Y,[W.agentId]:{cause:W.cause,code:W.code,message:W.message}}));break}}).then(W=>{J?W():ee=W}),()=>{J=!0,ee?.()}},[r,I,O]);const U=g.useCallback(async(ee,J,W)=>{y(!0),v(null);try{const Y=await t.createAgent(e,{name:ee,profileId:J,initialContent:W});o(B=>[...B,Y])}catch(Y){v(Bn(Y))}finally{y(!1)}},[t,e]),G=g.useCallback(async ee=>{y(!0),v(null);try{const J=await t.readContext(e,ee);u(ee),d(J)}catch(J){v(Bn(J))}finally{y(!1)}},[t,e]),E=g.useCallback(async ee=>{if(c){y(!0),v(null);try{await t.updateContext(e,c,ee),d(ee)}catch(J){v(Bn(J))}finally{y(!1)}}},[t,e,c]),z=g.useCallback(async(ee,J,W,Y)=>{y(!0),v(null);try{const{agent:B,relaunchedSession:le}=await t.changeAgentProfile(e,ee,J,W,Y);return o(je=>je.map(Ie=>Ie.id===B.id?B:Ie)),O(),le}catch(B){v(Bn(B));return}finally{y(!1)}},[t,e,O]),j=g.useCallback(async ee=>{y(!0),v(null);try{await t.deleteAgent(e,ee),o(J=>J.filter(W=>W.id!==ee)),u(J=>J===ee?null:J),c===ee&&d(""),C(J=>J===ee?null:J)}catch(J){v(Bn(J))}finally{y(!1)}},[t,e,c]),re=g.useCallback(async(ee,J,W)=>{v(null);try{const Y=await t.launchAgent(e,ee,J,W);return C(ee),O(),Y}catch(Y){throw v(Bn(Y)),Y}},[t,e,O]),V=g.useCallback(async ee=>{const J=ee??b,W=J?m.find(Y=>Y.agentId===J):null;if(C(Y=>Y===J||!J?null:Y),W?.sessionId)try{await i?.closeTerminal(W.sessionId),x(Y=>Y.filter(B=>B.agentId!==J))}catch(Y){v(Bn(Y)),await O()}},[m,O,b,i]),A=g.useCallback(async ee=>{L(J=>{const W=J[ee];if(!W?.resumeFireAt)return J;const{resumeFireAt:Y,...B}=W;return{...J,[ee]:B}});try{return await s?.cancelResume(ee)??!1}catch(J){return v(Bn(J)),!1}},[s]),ie=g.useCallback(async(ee,J)=>{try{await s?.setResumeAt(ee,J)}catch(W){v(Bn(W))}},[s]);return{agents:l,selectedAgentId:c,context:h,profiles:f,liveAgents:m,delegationSourceByRequester:k,limitByAgent:R,modelServerStatusByServer:S,launchFailureByAgent:D,error:w,busy:_,runningAgentId:b,refresh:I,refreshLiveAgents:O,createAgent:U,selectAgent:G,saveContext:E,changeAgentProfile:z,deleteAgent:j,launchAgent:re,stopAgent:V,cancelResume:A,setResumeAt:ie}}function gw(e,t,n){if(!e)return;const r=t.find(i=>i.id===e.profileId)?.opencode?.localModelServerId;return r?n[r]:void 0}function SA(e){if(!e)return null;switch(e.state){case"downloading":return"Téléchargement du modèle…";case"starting":case"probing":return"Chargement du serveur…";default:return null}}function Nu(e){if(!Number.isFinite(e)||e<=0)return"0 o";const t=["o","Ko","Mo","Go","To"];let n=e,r=0;for(;n>=1e3&&r{t&&t.listProfiles().then(i).catch(()=>{})},[t]);return g.useEffect(()=>{o()},[o]),g.useEffect(()=>{if(!n)return;let u,h=!1;return n.onDomainEvent(d=>{d.type==="modelServerStatusChanged"?l(f=>({...f,[d.serverId]:d.status})):d.type==="agentProfileChanged"&&o()}).then(d=>{h?d():u=d}),()=>{h=!0,u?.()}},[n,o]),{statusForAgent:g.useCallback(u=>gw(u,r,s),[r,s])}}function jA(e,t){const n=/^(\d{1,2}):(\d{2})$/.exec(e.trim());if(!n)return null;const r=Number(n[1]),i=Number(n[2]);if(r>23||i>59)return null;const s=new Date(t);return s.setHours(r,i,0,0),s.getTime()}function NA(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function EA(e){const t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function PA({state:e,onCancelResume:t,onSetResumeAt:n,busy:r=!1}){const{limitedUntil:i,resumeFireAt:s,suspected:l}=e,[o,c]=g.useState(()=>Date.now());g.useEffect(()=>{if(s===void 0)return;const m=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(m)},[s]);const[u,h]=g.useState(""),d=l===!0&&i===void 0&&s===void 0;function f(m){m.preventDefault();const x=jA(u,Date.now());x!==null&&(n(x),h(""))}const p=i!==void 0?`limité jusqu'à ${NA(i)}`:"limité";return a.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[a.jsx("span",{"aria-label":"session limit",title:l?"Limite de session détectée sans heure fiable":"Limite de session atteinte",className:q("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:p}),d&&a.jsxs("form",{onSubmit:f,className:"flex items-center gap-2","aria-label":"resume time form",children:[a.jsx("span",{className:"text-xs text-muted",role:"note",children:"heure inconnue"}),a.jsx(ce,{type:"time","aria-label":"resume time",value:u,disabled:r,onChange:m=>h(m.target.value),className:"h-8 w-28 text-xs"}),a.jsx(M,{type:"submit",size:"sm",variant:"primary","aria-label":"schedule resume",disabled:r||u.trim()==="",children:"Programmer la reprise"})]}),s!==void 0&&a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsxs("span",{"aria-label":"resume countdown",className:"text-xs text-muted",children:["reprise dans ",EA(s-o)]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel resume",disabled:r,onClick:t,children:"Annuler la reprise"})]})]})}function AA(e){switch(e.state){case"notConfigured":return null;case"probing":return{label:"vérification du serveur…",tone:"bg-muted/20 text-muted",role:"status"};case"starting":return{label:"démarrage du serveur…",tone:"bg-warning/20 text-warning",role:"status"};case"downloading":return{label:"téléchargement du modèle…",tone:"bg-warning/20 text-warning",role:"status"};case"ready":return e.reused?{label:"serveur prêt (réutilisé)",tone:"bg-success/20 text-success"}:{label:"serveur prêt",tone:"bg-success/20 text-success"};case"failed":return null}}function TA({status:e,failure:t}){const[n,r]=g.useState(!1),i=t||(e?.state==="failed"?{code:e.code,message:e.message}:null);if(i)return a.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[a.jsxs("span",{role:"alert","aria-label":"model server launch failed",className:q("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:["Échec du lancement : ",i.message]}),a.jsx("button",{type:"button","aria-label":"toggle launch failure detail",onClick:()=>r(l=>!l),className:"text-xs text-muted underline hover:text-content",children:"Détails"}),n&&a.jsxs("span",{"aria-label":"launch failure detail",className:"text-xs text-faint",children:["code ",i.code,i.cause?` · cause ${i.cause}`:""]})]});if(!e)return null;const s=AA(e);return s?a.jsx("span",{role:s.role,"aria-label":"model server status",className:q("rounded-full px-2 py-0.5 text-xs font-medium",s.tone),children:s.label}):null}function xw({projectId:e,projectRoot:t=""}){const n=wA(e),r=bA(e),i=he(),s=i.template??null,[l,o]=g.useState(""),[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState(!1);!m&&s&&(x(!0),s.listTemplates().then(p).catch(()=>{}));const w=i.skill??null,[v,_]=g.useState([]),[y,b]=g.useState(!1),[C,k]=g.useState("");async function N(){if(w)try{const[B,le]=await Promise.all([w.listSkills(e,"global"),w.listSkills(e,"project")]);_([...le,...B])}catch{}}!y&&w&&(b(!0),N());async function R(){if(!w||!n.selectedAgentId||!C)return;const B=v.find(le=>le.id===C);B&&(await w.assignSkill(e,n.selectedAgentId,B.id,B.scope),k(""),await n.refresh())}async function L(B){!w||!n.selectedAgentId||(await w.unassignSkill(e,n.selectedAgentId,B),await n.refresh())}const[S,T]=g.useState(n.context),[D,P]=g.useState(n.context);n.context!==D&&(P(n.context),T(n.context));const[I,O]=g.useState(null),[U,G]=g.useState({}),[E,z]=g.useState({}),[j,re]=g.useState(null);async function V(){if(!j)return;const{agentId:B,profileId:le}=j;re(null);const je=await n.changeAgentProfile(B,le,24,80);je&&B===I&&z(Ie=>({...Ie,[B]:je.sessionId}))}const A=l.trim().length>0&&!n.busy;async function ie(B){if(B.preventDefault(),!!A){if(h&&s)await s.createAgentFromTemplate(e,h,{name:l.trim(),synchronized:!0}),await n.refresh();else{const le=c.trim()||"";await n.createAgent(l.trim(),le)}o(""),u(""),d("")}}function ee(B){G(le=>({...le,[B]:le[B]??crypto.randomUUID()})),O(B)}function J(B){n.stopAgent(B),O(null)}const W=n.agents.find(B=>B.id===n.selectedAgentId)??null,Y=h!=="";return a.jsxs(we,{title:"Agents",className:"flex flex-col gap-0",children:[n.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),a.jsxs("form",{onSubmit:B=>void ie(B),className:"flex flex-col gap-3 border-b border-border p-4",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"agent-name-input",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(ce,{id:"agent-name-input","aria-label":"agent name",placeholder:"My agent",value:l,onChange:B=>o(B.target.value),className:"w-full"})]}),a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"agent-template-select",className:"text-xs font-medium text-muted",children:"Template"}),a.jsxs("select",{id:"agent-template-select","aria-label":"agent template",value:h,onChange:B=>d(B.target.value),className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:n.busy,children:[a.jsx("option",{value:"",children:"(none / from scratch)"}),f.map(B=>a.jsx("option",{value:B.id,children:B.name},B.id))]})]}),!Y&&a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsxs("label",{htmlFor:"agent-profile-select",className:"text-xs font-medium text-muted",children:["Profile",n.profiles.length===0&&a.jsx("span",{className:"ml-1 text-faint",children:"(no profiles configured — you can still enter an id)"})]}),n.profiles.length>0?a.jsxs("select",{id:"agent-profile-select","aria-label":"agent profile",value:c,onChange:B=>u(B.target.value),className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"",children:"— select profile —"}),n.profiles.map(B=>a.jsx("option",{value:B.id,children:B.name},B.id))]}):a.jsx(ce,{id:"agent-profile-select","aria-label":"agent profile",placeholder:"profile-id (optional)",value:c,onChange:B=>u(B.target.value),className:"min-w-32"})]}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"create agent",disabled:!A,loading:n.busy,className:"self-end",children:"Create"})]}),a.jsx("div",{className:"p-4",children:n.agents.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.agents.map(B=>{const le=B.id===n.selectedAgentId,je=B.id===I,Ie=n.liveAgents.find(dt=>dt.agentId===B.id),$=n.profiles.find(dt=>dt.id===B.profileId)?.name??B.profileId,ge=r.driftByAgentId.get(B.id),de=n.delegationSourceByRequester[B.id],Ne=n.limitByAgent[B.id],_t=gw(B,n.profiles,n.modelServerStatusByServer),Xr=n.launchFailureByAgent[B.id];return a.jsxs("li",{className:q("flex flex-col gap-2 py-3 first:pt-0 last:pb-0",le&&"rounded-md bg-raised px-2"),children:[a.jsxs("button",{type:"button",onClick:()=>void n.selectAgent(B.id),className:"flex min-w-0 flex-col items-start gap-0.5 text-left","aria-pressed":le,children:[a.jsxs("span",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:[a.jsx("span",{className:"font-medium text-content",children:B.name}),ge&&a.jsx("span",{"aria-label":"update available",className:"rounded-full bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary",children:"update available"}),de&&a.jsx("span",{"aria-label":`delegation source ${de}`,title:de==="mcp"?"Last delegation arrived via the MCP server":"Last delegation arrived via .ideai/requests",className:"rounded-full bg-raised px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-muted",children:de})]}),a.jsx("span",{className:"text-xs text-muted",children:$}),Ie&&a.jsxs("span",{className:"block w-full min-w-0 truncate text-xs text-primary",children:["running in IdeA · ",Ie.sessionId??Ie.nodeId]})]}),Ne&&a.jsx(PA,{state:Ne,busy:n.busy,onCancelResume:()=>void n.cancelResume(B.id),onSetResumeAt:dt=>void n.setResumeAt(B.id,dt)}),a.jsx(TA,{status:_t,failure:Xr}),a.jsx(YP,{requester:B.id}),a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.profiles.length>0&&a.jsxs("select",{"aria-label":`profile for ${B.name}`,value:B.profileId,disabled:n.busy,onChange:dt=>{const vr=dt.target.value;vr&&vr!==B.profileId&&re({agentId:B.id,profileId:vr})},className:q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[n.profiles.every(dt=>dt.id!==B.profileId)&&a.jsx("option",{value:B.profileId,children:B.profileId}),n.profiles.map(dt=>a.jsx("option",{value:dt.id,children:dt.name},dt.id))]}),ge&&a.jsx(M,{size:"sm",variant:"primary","aria-label":`sync ${B.name}`,disabled:n.busy||r.driftBusy,onClick:()=>void r.syncAgent(B.id,n.refresh),children:"Sync"}),je||Ie?a.jsx(M,{size:"sm",variant:"ghost","aria-label":`stop ${B.name}`,onClick:()=>J(B.id),className:"text-danger hover:text-danger",children:"Stop"}):a.jsx(M,{size:"sm",variant:"primary","aria-label":`launch ${B.name}`,disabled:n.busy||I!==null,onClick:()=>ee(B.id),children:"Launch"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete ${B.name}`,disabled:n.busy,onClick:()=>void n.deleteAgent(B.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},B.id)})})}),I!==null&&a.jsx("div",{className:"border-t border-border p-4",children:a.jsx("div",{className:"h-96 overflow-hidden rounded-lg border border-border bg-surface",children:a.jsx(up,{cwd:t,open:(B,le)=>n.launchAgent(I,{...B,nodeId:U[I]},le),reattach:(B,le)=>i.agent.reattach(B,le),sessionId:E[I]??null,onSessionId:B=>z(le=>({...le,[I]:B}))},I)})}),W&&w&&a.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[a.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Skills — ",W.name]}),W.skills.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No skills assigned."}):a.jsx("ul",{className:"flex flex-wrap gap-1.5",children:W.skills.map(B=>{const le=v.find(je=>je.id===B.skillId)?.name??B.skillId;return a.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[a.jsx("span",{children:le}),a.jsx("button",{type:"button","aria-label":`unassign ${le}`,disabled:n.busy,onClick:()=>void L(B.skillId),className:"text-faint hover:text-danger",children:"✕"})]},B.skillId)})}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs("select",{"aria-label":"skill to assign",value:C,onChange:B=>k(B.target.value),disabled:n.busy,className:q("h-9 min-w-0 flex-1 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"",children:"— assign a skill —"}),v.filter(B=>!W.skills.some(le=>le.skillId===B.id)).map(B=>a.jsxs("option",{value:B.id,children:[B.name," (",B.scope,")"]},B.id))]}),a.jsx(M,{variant:"primary","aria-label":"assign skill",disabled:n.busy||!C,onClick:()=>void R(),children:"Assign"})]})]}),W&&a.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Context — ",W.name]}),a.jsx("code",{className:"text-xs text-muted",children:W.contextPath})]}),a.jsx("textarea",{"aria-label":"agent context",value:S,onChange:B=>T(B.target.value),rows:10,className:q("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:n.busy}),a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.busy&&a.jsx(Re,{size:14}),a.jsx(M,{variant:"primary",disabled:n.busy,onClick:()=>void n.saveContext(S),children:"Save"})]})]}),j&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm profile change",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsx("h4",{className:"text-sm font-semibold text-content",children:"Changer le moteur IA"}),a.jsx("p",{className:"mt-2 text-sm text-muted",children:"Changer le moteur abandonne l'historique de conversation (le contexte et la mémoire sont conservés). Continuer ?"}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx(M,{variant:"ghost","aria-label":"cancel profile change",disabled:n.busy,onClick:()=>re(null),children:"Annuler"}),a.jsx(M,{variant:"primary","aria-label":"confirm profile change",loading:n.busy,disabled:n.busy,onClick:()=>void V(),children:"Continuer"})]})]})})]})}function Eu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function vw(e,t){const{layout:n,terminal:r}=he(),[i,s]=g.useState(null),[l,o]=g.useState(0),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=g.useCallback(L=>{s(L),o(S=>S+1)},[]);g.useEffect(()=>{if(!e||!n){s(null);return}let L=!1;return d(!0),n.loadLayout(e,t).then(S=>{L||f(S)}).catch(S=>{L||u(Eu(S))}).finally(()=>{L||d(!1)}),()=>{L=!0}},[n,e,t,f]);const p=g.useCallback(async L=>{if(!(!e||!n)){d(!0),u(null);try{f(await n.mutateLayout(e,L,t))}catch(S){u(Eu(S))}finally{d(!1)}}},[n,e,t,f]),m=g.useCallback(async L=>{if(!(!e||!n||L.length===0)){d(!0),u(null);try{let S=null;for(const T of L)S=await n.mutateLayout(e,T,t);S&&f(S)}catch(S){u(Eu(S))}finally{d(!1)}}},[n,e,t,f]),x=g.useCallback((L,S)=>p(GE(L,S)),[p]),w=g.useCallback(async(L,S)=>{await p({type:"merge",container:L,keepIndex:S})},[p]),v=g.useCallback((L,S)=>p({type:"resize",container:L,weights:S}),[p]),_=g.useCallback((L,S)=>p({type:"move",from:L,to:S}),[p]),y=g.useCallback((L,S)=>p({type:"setSession",target:L,session:S}),[p]),b=g.useCallback(async(L,S)=>{const T=i?Qo(i).find(I=>I.id===L):void 0,D=T?.agent??null,P=T?.session??null;if(S!==D&&(await m([{type:"setCellAgent",target:L,agent:S},{type:"setSession",target:L,session:null},{type:"setCellConversation",target:L,conversationId:null}]),P&&!D&&r))try{await r.closeTerminal(P)}catch{}},[i,m,r]),C=g.useCallback(async(L,S,T)=>{const D=i?Qo(i).find(U=>U.id===L):void 0,P=D?.agent??null,I=D?.session??null,O=[];if(S!==P&&O.push({type:"setCellAgent",target:L,agent:S},{type:"setCellConversation",target:L,conversationId:null}),T!==I&&O.push({type:"setSession",target:L,session:T}),await m(O),I&&I!==T&&!P&&r)try{await r.closeTerminal(I)}catch{}},[i,m,r]),k=g.useCallback((L,S)=>p({type:"setCellConversation",target:L,conversationId:S}),[p]),N=g.useCallback((L,S)=>{s(T=>T&&VE(T,L,S)),o(T=>T+1)},[]),R=g.useCallback(L=>{s(S=>S&&KE(S,L)),o(S=>S+1)},[]);return{layout:i,layoutVersion:l,error:c,busy:h,split:x,merge:w,resize:v,move:_,setSession:y,setCellAgent:b,attachLiveAgentToCell:C,setCellConversation:k,setPluginLayoutState:N,replacePluginLayoutWithTerminal:R}}function LA(e,t,n){return e&&t&&!n}function DA({projectId:e,cwd:t,layoutId:n,onOpenConversation:r,onOpenPluginsSettings:i}){const s=vw(e,n),l=ea(e);return s.layout?a.jsxs("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%",position:"relative"},children:[s.error&&a.jsx("p",{role:"alert",style:{color:"crimson",margin:0},children:s.error}),a.jsx(mp,{node:s.layout.root,cwd:t,vm:s,parentSplit:null,projectId:e,workState:l.state,refreshWorkState:l.refresh,onOpenConversation:r,onOpenPluginsSettings:i})]}):a.jsx("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%"},children:s.error?a.jsx("p",{role:"alert",style:{color:"crimson"},children:s.error}):a.jsx("p",{children:"Loading layout…"})})}function mp({node:e,cwd:t,vm:n,parentSplit:r,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o,onOpenPluginsSettings:c}){switch(e.type){case"customPluginLayout":return a.jsx(vA,{projectId:i,cell:e.node,onStateChange:u=>n.setPluginLayoutState(e.node.id,u),onOpenPlugins:()=>c?.(),onChooseAnotherLayout:()=>n.replacePluginLayoutWithTerminal(e.node.id)});case"leaf":return a.jsx(MA,{id:e.node.id,session:e.node.session??null,agent:e.node.agent??null,conversationId:e.node.conversationId??null,agentWasRunning:e.node.agentWasRunning??!1,cwd:t,vm:n,parentSplit:r,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o});case"split":return a.jsx(IA,{split:e.node,cwd:t,vm:n,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o,onOpenPluginsSettings:c});case"grid":return a.jsx(BA,{grid:e.node,cwd:t,vm:n,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o,onOpenPluginsSettings:c})}}function RA(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}const qs={banner:3,veil:4,controls:5};function MA({id:e,session:t,agent:n,conversationId:r,agentWasRunning:i,cwd:s,vm:l,parentSplit:o,projectId:c,workState:u,refreshWorkState:h,onOpenConversation:d}){const f=o!==null&&o.siblings===2,p=o&&o.index===0?1:0,{agent:m,input:x,system:w}=he(),{portal:v,overlay:_}=vP(c,n??null),[y,b]=g.useState([]);g.useEffect(()=>{if(!m)return;let ae=!1;return m.listAgents(c).then(xe=>{ae||b(xe)}).catch(()=>{}),()=>{ae=!0}},[m,c]);const[C,k]=g.useState([]),N=()=>{m?.listLiveAgents&&m.listLiveAgents(c).then(k).catch(()=>{})};g.useEffect(()=>{if(!m?.listLiveAgents)return;let ae=!1;return m.listLiveAgents(c).then(xe=>{ae||k(xe)}).catch(()=>{}),()=>{ae=!0}},[m,c]),g.useEffect(()=>{if(!w)return;let ae,xe=!1;return w.onDomainEvent(Ae=>{(Ae.type==="agentLaunched"||Ae.type==="agentExited")&&N()}).then(Ae=>{xe?Ae():ae=Ae}),()=>{xe=!0,ae?.()}},[w,m,c]);const R=n??null,{active:L}=fw(R??""),{statusForAgent:S}=CA(),T=R?y.find(ae=>ae.id===R):void 0,D=S(T),P=SA(D),I=kA(D),O=R?u?.agents.find(ae=>ae.agentId===R):void 0,U=O?.tickets.find(ae=>ae.status==="inProgress"),G=O?.tickets.filter(ae=>ae.status==="queued")??[],E=Math.max(O?.inboxDepth??0,O?.inbox?.length??0,G.length),z=O?.backgroundTasks?.filter(ae=>ae.status==="completed"||ae.status==="failed"||ae.status==="cancelled")??[],j=O?.busy.state==="busy"||!!U,re=U?.source.kind==="agent"?U:void 0,V=U?.conversationId??r??null;async function A(){if(!(!R||!x))try{await x.interrupt(c,R),await h()}catch(ae){B({message:hx(ae)})}}const ie=ae=>C.find(xe=>xe.agentId===ae),ee=async(ae,xe)=>{const Ae=hx(ae);if(!fx(ae))return{message:Ae};const Dt=(m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C).find(H=>H.agentId===xe);return{message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:Dt&&Dt.nodeId!==e?Dt.nodeId:void 0}},J=ae=>{if(!l.layout)return;const xe=Qo(l.layout).find(Ae=>Ae.id!==e&&(Ae.agent??null)===ae);return xe?{nodeId:xe.id}:void 0},W=ae=>{const xe=ie(ae);if(!(!xe||xe.kind!=="pty"||xe.nodeId===e))return J(ae)?void 0:xe},[Y,B]=g.useState(null),[le,je]=g.useState(null),[Ie,$]=g.useState(null),[ge,de]=g.useState(0);g.useEffect(()=>{if(!R||!m?.attachLiveAgent||le)return;const ae=W(R);if(!ae?.sessionId||ae.sessionId===t)return;let xe=!1;return(async()=>{const Ae=await m.attachLiveAgent(c,R,e);xe||(await l.attachLiveAgentToCell(e,R,Ae.sessionId??ae.sessionId),xe||de(dn=>dn+1))})().catch(()=>{}),()=>{xe=!0}},[C,R,t]);const Ne=async(ae,xe,Ae)=>{const dn=W(R);if(dn?.sessionId&&m.attachLiveAgent){const te=(await m.attachLiveAgent(c,R,e)).sessionId??dn.sessionId;l.setSession(e,te);const pe=await m.reattach(te,xe);return N(),pe.handle}const Dt=await m.launchAgent(c,R,{...ae,conversationId:Ae,nodeId:e},xe).catch(async H=>{throw fx(H)&&B(await ee(H,R)),H});return Dt.assignedConversationId&&l.setCellConversation(e,Dt.assignedConversationId),Dt},_t=m&&R?(ae,xe)=>r?(Promise.resolve(m.inspectConversation?.(c,R,r)).then(Ae=>$(Ae??{})).catch(()=>$({})),new Promise((Ae,dn)=>{je({opts:ae,onData:xe,resolve:Ae,reject:dn})})):Ne(ae,xe,void 0):void 0,Xr=()=>{const ae=le;ae&&(je(null),$(null),Ne(ae.opts,ae.onData,r??void 0).then(ae.resolve,ae.reject))},dt=()=>{const ae=le;ae&&(je(null),$(null),l.setCellConversation(e,null),Ne(ae.opts,ae.onData,void 0).then(ae.resolve,ae.reject))},vr=m&&R?(ae,xe)=>m.reattach(ae,xe):void 0;return a.jsxs("div",{"data-testid":"layout-leaf","data-node-id":e,style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0,border:"1px solid #2a2a2a",boxSizing:"border-box",overflow:"hidden"},children:[a.jsxs("div",{style:{position:"absolute",top:2,right:16,zIndex:qs.controls,display:"flex",gap:2,alignItems:"center"},children:[a.jsxs("select",{"aria-label":`agent selector ${e}`,value:R??"",onChange:ae=>{const xe=ae.target.value;if(xe===""){B(null),l.setCellAgent(e,null);return}(async()=>{const Ae=m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C;k(Ae);const dn=J(xe);if(dn){B({message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:dn.nodeId});return}const Dt=Ae.find(te=>te.agentId===xe);if(Dt&&Dt.kind==="pty"&&Dt.nodeId!==e){if(!m?.attachLiveAgent||!Dt.sessionId){B({message:"Session active introuvable pour cet agent."});return}B(null);const te=await m.attachLiveAgent(c,xe,e);await l.attachLiveAgentToCell(e,xe,te.sessionId??Dt.sessionId),N();return}B(null),await l.setCellAgent(e,xe)})().catch(async Ae=>B(await ee(Ae,xe)))},style:{fontSize:11,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,padding:"1px 2px",maxWidth:100},children:[a.jsx("option",{value:"",children:"Plain"}),y.map(ae=>{const xe=J(ae.id),Ae=W(ae.id);return a.jsxs("option",{value:ae.id,disabled:!!xe,children:[ae.name,xe?" (visible ailleurs)":Ae?" (arrière-plan)":""]},ae.id)})]}),a.jsx("button",{type:"button",title:"Split into columns","aria-label":`split ${e} columns`,onClick:()=>void l.split(e,"row"),children:"⬌"}),a.jsx("button",{type:"button",title:"Split into rows","aria-label":`split ${e} rows`,onClick:()=>void l.split(e,"column"),children:"⬍"}),f&&a.jsx("button",{type:"button",title:"Close this terminal","aria-label":`close ${e}`,onClick:()=>void l.merge(o.container,p),children:"✕"})]}),R&&(j||E>0||z.length>0||V)&&a.jsxs("div",{role:"status","aria-live":"polite",style:{position:"absolute",top:30,left:4,zIndex:qs.banner,display:"flex",maxWidth:"calc(100% - 8px)",alignItems:"center",gap:4,overflow:"hidden"},children:[j&&a.jsx("span",{title:re?.requesterLabel??U?.taskPreview,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-warning, #d49b3a)",borderRadius:3,background:"rgba(212, 155, 58, 0.16)",color:"var(--color-warning, #d49b3a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:re?`Busy · ${re.requesterLabel}`:"Busy"}),!j&&E>0&&a.jsxs("span",{title:`${E} pending message${E===1?"":"s"}`,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued · ",E]}),j&&E>0&&a.jsxs("span",{title:`${E} queued message${E===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued ",E]}),z.length>0&&a.jsxs("span",{title:`${z.length} background task result${z.length===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-success, #57b36a)",borderRadius:3,background:"rgba(87, 179, 106, 0.14)",color:"var(--color-success, #57b36a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Task done ",z.length]}),j&&a.jsx("button",{type:"button","aria-label":`cancel current turn ${e}`,title:"Cancel current turn",onClick:()=>void A(),disabled:!x,style:{flexShrink:0,border:"1px solid var(--color-danger, #d45a5a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-danger, #d45a5a)",cursor:x?"pointer":"default",fontSize:11,padding:"1px 6px"},children:"Cancel"}),V&&d&&a.jsx("button",{type:"button","aria-label":`open cell conversation ${e}`,title:"Open conversation history",onClick:()=>d(V),style:{flexShrink:0,border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",cursor:"pointer",fontSize:11,padding:"1px 6px"},children:"History"})]}),a.jsxs("div",{style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0},children:[a.jsx(up,{cwd:s,open:_t,reattach:vr,sessionId:t,onSessionId:ae=>void l.setSession(e,ae),agentMode:R!=null,portal:R!=null?v:void 0,refitSignal:l.layoutVersion},`${e}-${R??"plain"}-${ge}`),!P&&LA(R!=null,!!_,L)&&a.jsx("div",{"data-testid":"write-portal-overlay",role:"status","aria-live":"polite",style:{position:"absolute",inset:0,zIndex:qs.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.45)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:a.jsx("span",{style:{background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"6px 12px"},children:"Un agent est en train de parler…"})}),!P&&R!=null&&a.jsx(GP,{projectId:c,agentId:R}),P&&a.jsx("div",{"data-testid":"model-server-overlay",role:"status","aria-live":"polite","aria-label":"model server launch",style:{position:"absolute",inset:0,zIndex:qs.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0,maxWidth:"80%",background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"8px 14px"},children:[a.jsx("span",{children:P}),I&&a.jsxs(a.Fragment,{children:[a.jsx("div",{"data-testid":"model-server-progress",role:"progressbar","aria-label":"progression du téléchargement","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":I.percent!=null?Math.round(I.percent):void 0,style:{position:"relative",width:220,maxWidth:"100%",height:6,borderRadius:3,overflow:"hidden",background:"var(--color-raised, #2a2a2a)"},children:a.jsx("div",{style:I.percent!=null?{height:"100%",width:`${I.percent}%`,background:"var(--color-primary, #5b9bd5)",transition:"width 120ms linear"}:{position:"absolute",top:0,bottom:0,width:"40%",background:"var(--color-primary, #5b9bd5)",animation:"model-server-indeterminate 1.1s ease-in-out infinite"}})}),(I.percent!=null||I.bytesLabel)&&a.jsxs("span",{"data-testid":"model-server-progress-label",style:{fontSize:12,color:"var(--color-content-muted, #9a9a9a)"},children:[I.percent!=null?`${Math.round(I.percent)} %`:"",I.percent!=null&&I.bytesLabel?" · ":"",I.bytesLabel??""]}),I.source&&a.jsx("span",{"data-testid":"model-server-source",style:{fontSize:11,color:"var(--color-content-muted, #9a9a9a)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.source,children:I.source})]})]})})]}),Y&&a.jsxs("div",{role:"status",style:{position:"absolute",bottom:4,left:4,right:4,margin:0,fontSize:11,color:"var(--color-content-muted, #9a9a9a)",background:"var(--color-surface, #1e1e1e)",padding:"2px 6px",borderRadius:3,zIndex:qs.banner,display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[a.jsx("span",{style:{minWidth:0},children:Y.message}),Y.goToNodeId&&a.jsx("button",{type:"button","aria-label":"aller à la cellule",onClick:()=>{RA(Y.goToNodeId),B(null)},style:{flexShrink:0,fontSize:11,cursor:"pointer",background:"transparent",color:"var(--color-primary, #5b9bd5)",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,padding:"1px 6px"},children:"Aller à la cellule"})]}),le&&a.jsx(hP,{agentWasRunning:i,details:Ie,onResume:Xr,onNewConversation:dt})]})}function IA({split:e,cwd:t,vm:n,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o}){const c=e.direction==="row",u=e.children.map(m=>m.weight),h=g.useRef(null),[d,f]=g.useState(null),p=Rh(d??u);return a.jsx("div",{ref:h,"data-testid":"layout-split","data-direction":e.direction,style:{display:"flex",flexDirection:c?"row":"column",width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.children.map((m,x)=>a.jsxs("div",{style:{display:"contents"},children:[a.jsx("div",{style:{flexBasis:`${p[x]}%`,flexGrow:0,flexShrink:0,minHeight:0,minWidth:0,overflow:"hidden"},children:a.jsx(mp,{node:m.node,cwd:t,vm:n,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o,parentSplit:{container:e.id,index:x,siblings:e.children.length}})}),xf(Qg(u,x,w)),onDragEnd:w=>{const v=Qg(u,x,w);f(null),n.resize(e.id,v)}})]},_w(m.node,x)))})}function OA({isRow:e,container:t,onDragMove:n,onDragEnd:r}){const i=g.useRef(null);function s(u){if(i.current===null)return null;const h=t.current?.getBoundingClientRect(),d=h?e?h.width:h.height:0;return d<=0?null:(u-i.current)/d}function l(u){u.preventDefault(),u.currentTarget.setPointerCapture(u.pointerId),i.current=e?u.clientX:u.clientY}function o(u){if(i.current===null)return;const h=s(e?u.clientX:u.clientY);h!==null&&n(h)}function c(u){const h=s(e?u.clientX:u.clientY);i.current=null,h!==null&&r(h)}return a.jsx("div",{role:"separator","aria-orientation":e?"vertical":"horizontal",onPointerDown:l,onPointerMove:o,onPointerUp:c,style:{flex:"0 0 6px",cursor:e?"col-resize":"row-resize",background:"#3a3a3a",touchAction:"none"}})}function BA({grid:e,cwd:t,vm:n,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o}){const c=Rh(e.colWeights).map(h=>`${h}fr`).join(" "),u=Rh(e.rowWeights).map(h=>`${h}fr`).join(" ");return a.jsx("div",{"data-testid":"layout-grid-container",style:{display:"grid",gridTemplateColumns:c,gridTemplateRows:u,width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.cells.map((h,d)=>a.jsx("div",{style:{gridColumn:`${h.col+1} / span ${h.colSpan}`,gridRow:`${h.row+1} / span ${h.rowSpan}`,minHeight:0,minWidth:0,overflow:"hidden"},children:a.jsx(mp,{node:h.node,cwd:t,vm:n,parentSplit:null,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o})},_w(h.node,d)))})}function _w(e,t){return e.node.id??String(t)}function hx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function fx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="AGENT_ALREADY_RUNNING"}function Mi(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function px(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="NOT_FOUND"}function zA(e){const{layout:t,system:n}=he(),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{if(!(!e||!t))try{const{layouts:w,activeId:v}=await t.listLayouts(e);i(w),l(_=>_&&w.some(y=>y.id===_)?_:v)}catch(w){h(Mi(w))}},[t,e]);g.useEffect(()=>{if(!e||!t){i([]),l(null);return}let w=!1;return c(!0),t.listLayouts(e).then(({layouts:v,activeId:_})=>{w||(i(v),l(_))}).catch(v=>{w||h(Mi(v))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[t,e]),g.useEffect(()=>{if(!e||!n)return;let w=!1,v;return n.onDomainEvent(_=>{_.type==="layoutChanged"&&_.projectId===e&&d()}).then(_=>{w?_():v=_}),()=>{w=!0,v?.()}},[n,e,d]);const f=g.useCallback(async w=>{if(!(!e||!t)){c(!0),h(null);try{const v=await t.setActiveLayout(e,w);l(v?.activeId??w)}catch(v){h(Mi(v))}finally{c(!1)}}},[t,e]),p=g.useCallback(async(w,v)=>{if(!e||!t)return null;c(!0),h(null);try{const{layoutId:_}=await t.createLayout(e,w,v),y=await t.listLayouts(e);return i(y.layouts),_}catch(_){return h(Mi(_)),null}finally{c(!1)}},[t,e]),m=g.useCallback(async(w,v)=>{if(!(!e||!t)){c(!0),h(null);try{await t.renameLayout(e,w,v),i(_=>_.map(y=>y.id===w?{...y,name:v}:y))}catch(_){px(_)?await d():h(Mi(_))}finally{c(!1)}}},[t,e,d]),x=g.useCallback(async w=>{if(!(!e||!t)){if(r.length<=1){h("Cannot delete the last layout.");return}c(!0),h(null);try{const{activeId:v}=await t.deleteLayout(e,w);i(_=>_.filter(y=>y.id!==w)),l(v)}catch(v){px(v)?await d():h(Mi(v))}finally{c(!1)}}},[t,e,r.length,d]);return{layouts:r,activeId:s,busy:o,error:u,setActive:f,create:p,rename:m,deleteLayout:x}}function FA({projectId:e,onActiveLayoutChange:t}){const n=zA(e);g.useEffect(()=>{const _=n.layouts.find(y=>y.id===n.activeId);_&&t(_)},[n.activeId,n.layouts,t]);const[r,i]=g.useState(null),[s,l]=g.useState(""),o=g.useRef(null),[c,u]=g.useState(!1),{registry:h}=pp(),[d,f]=g.useState(null);async function p(_){await n.setActive(_)}async function m(_){n.layouts.length<=1||await n.deleteLayout(_)}function x(_,y){i(_),l(y),setTimeout(()=>o.current?.focus(),0)}async function w(){if(!r)return;const _=s.trim();_&&await n.rename(r,_),i(null),l("")}async function v(_){u(!1);const y=_==="gitGraph"?"Git Graph":"Layout",b=window.prompt("New layout name:",y);if(!b?.trim())return;const C=await n.create(b.trim(),_);C&&await n.setActive(C)}return n.layouts.length===0?null:a.jsxs("div",{"data-testid":"layout-tabs",className:"flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",children:[n.layouts.map(_=>{const y=_.id===n.activeId,b=_.id===r;return a.jsxs("div",{className:q("group flex items-center gap-1 rounded-md border px-1 transition-colors",y?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[b?a.jsx("input",{ref:o,value:s,onChange:C=>l(C.target.value),onBlur:()=>void w(),onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&(i(null),l(""))},"aria-label":`rename layout ${_.name}`,className:"w-24 rounded border border-border bg-base px-1 py-0.5 text-sm text-content focus:outline-none focus:ring-1 focus:ring-primary"}):a.jsxs("button",{type:"button",role:"tab","aria-selected":y,onClick:()=>void p(_.id),onDoubleClick:()=>x(_.id,_.name),className:q("flex items-center gap-1 px-2 py-1 text-sm focus-visible:outline-none",y?"font-semibold text-content":"text-muted hover:text-content"),children:[_.kind==="gitGraph"&&a.jsx("span",{"aria-label":"git graph layout",className:"text-xs text-primary",title:"Git Graph",children:"⎇"}),_.name]}),a.jsx("button",{type:"button","aria-label":`delete layout ${_.name}`,disabled:n.layouts.length<=1,onClick:()=>void m(_.id),className:q("flex h-4 w-4 items-center justify-center rounded text-xs transition-opacity",n.layouts.length<=1?"cursor-not-allowed opacity-20":"opacity-60 hover:opacity-100 group-hover:opacity-100"),children:"×"})]},_.id)}),a.jsxs("div",{className:"relative",children:[a.jsx("button",{type:"button","aria-label":"create layout",onClick:()=>u(_=>!_),className:"flex h-6 w-6 items-center justify-center rounded border border-transparent text-sm text-muted transition-colors hover:border-border hover:text-content",children:"+"}),c&&a.jsxs("div",{role:"menu",className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col rounded-md border border-border bg-surface shadow-lg",children:[a.jsx("button",{type:"button",role:"menuitem","aria-label":"create terminal layout",onClick:()=>void v("terminal"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"Terminal"}),a.jsx("button",{type:"button",role:"menuitem","aria-label":"create git graph layout",onClick:()=>void v("gitGraph"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"⎇ Git graph"}),a.jsx(yA,{registry:h,onSelect:_=>{u(!1),f(`« ${_.layout.label} » (${_.pluginDisplayName}) : la création de layouts plugins nécessite une extension backend pas encore livrée.`)}})]})]}),(n.error||d)&&a.jsx("span",{className:"ml-2 text-xs text-danger",role:"alert",children:n.error??d})]})}class $A extends g.Component{constructor(){super(...arguments);X(this,"state",{error:null,retryKey:0});X(this,"retry",()=>{this.setState(({retryKey:n})=>({error:null,retryKey:n+1}))})}static getDerivedStateFromError(n){return{error:n}}render(){return this.state.error?a.jsx(we,{title:"Work",children:a.jsxs("div",{role:"alert",className:"rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[a.jsx("p",{className:"font-medium",children:"Work panel failed to render."}),a.jsx("p",{className:"mt-1 text-xs text-danger/80",children:this.state.error.message}),a.jsx(M,{size:"sm",variant:"ghost",className:"mt-2",onClick:this.retry,children:"Retry"})]})}):a.jsx("div",{children:this.props.children},this.state.retryKey)}}function cr(e){return e.length<=8?e:e.slice(0,8)}function WA(e){return e==="inProgress"?"In progress":"Queued"}function HA(e){switch(e){case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed";case"cancelled":return"Cancelled";case"delivered":return"Delivered";case"pending":return"Pending"}}function UA(e){return e==="completed"||e==="failed"||e==="cancelled"}function qA(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function VA(e){if(e.source.kind==="human")return"Human";const t=cr(e.source.agentId);return e.requesterLabel.trim()?`${e.requesterLabel} (${t})`:`Agent ${t}`}function KA(e){switch(e){case"ready":return"Summary";case"missing":return"No summary";case"partial":return"Partial";case"unavailable":return"Unavailable"}}function GA(e){if(e.objectivePreview)return`Goal: ${e.objectivePreview}`;if(e.summaryPreview)return e.summaryPreview;const t=(e.recentTurns??[]).at(-1);return t?`Last: ${t.textPreview}`:null}function mx(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}async function YA(e){if(typeof navigator<"u"&&navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}throw new Error("Clipboard unavailable")}function XA({summary:e,onOpenConversation:t}){const n=GA(e),[r,i]=g.useState(!1),[s,l]=g.useState(!1);return n?a.jsxs("div",{className:"mt-1 min-w-0 pl-1 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsx("span",{className:q("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="ready"?"bg-success/10 text-success":"bg-raised text-muted"),children:KA(e.status)}),t?a.jsx("button",{type:"button","aria-label":`open conversation ${e.conversationId}`,className:"min-w-0 flex-1 break-words text-left hover:text-content hover:underline",onClick:()=>t(e.conversationId),children:n}):a.jsx("span",{className:"min-w-0 flex-1 break-words",children:n}),a.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content",onClick:()=>i(o=>!o),children:r?"Hide":"View"}),a.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content disabled:opacity-50",disabled:!n,onClick:()=>{YA(n).then(()=>{l(!0),window.setTimeout(()=>l(!1),1e3)})},children:s?"Copied":"Copy"})]}),r&&a.jsxs("div",{"aria-label":`conversation ${e.conversationId} details`,className:"mt-1 space-y-1 border-l border-border pl-2",children:[e.objectivePreview&&a.jsxs("p",{children:[a.jsx("span",{className:"font-medium text-content",children:"Goal:"})," ",e.objectivePreview]}),e.summaryPreview&&a.jsxs("p",{children:[a.jsx("span",{className:"font-medium text-content",children:"Summary:"})," ",e.summaryPreview]}),(e.recentTurns??[]).length>0&&a.jsx("ul",{className:"space-y-0.5",children:(e.recentTurns??[]).map(o=>a.jsxs("li",{children:[a.jsxs("span",{className:"font-medium text-content",children:[o.role,":"]})," ",o.textPreview]},`${o.atMs}-${o.role}-${o.textPreview}`))})]})]}):null}function QA({ticket:e,summary:t,onOpenConversation:n}){const r=e.taskLen>e.taskPreview.length;return a.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsxs("span",{className:q("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="inProgress"?"bg-warning/15 text-warning":"bg-raised text-muted"),children:["#",e.position+1," ",WA(e.status)]}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"font-medium text-content",children:VA(e)}),a.jsx("span",{className:"text-muted",children:" · "}),a.jsx("span",{className:"break-words",children:e.taskPreview}),r&&a.jsxs("span",{"aria-label":`${e.taskLen-e.taskPreview.length} more characters`,className:"text-muted",children:[" ","+",e.taskLen-e.taskPreview.length]})]}),a.jsx("code",{"aria-label":`ticket ${cr(e.ticketId)}`,title:e.ticketId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.ticketId)})]}),t&&a.jsx(XA,{summary:t,onOpenConversation:n})]})}function JA({item:e}){return a.jsx("li",{className:"min-w-0 text-xs text-muted",children:a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium text-muted",children:e.kind}),a.jsx("span",{className:"min-w-0 flex-1 break-words",children:e.body}),a.jsx("code",{title:e.id,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.id)})]})})}function ZA({task:e,onRefresh:t}){const{workState:n}=he(),[r,i]=g.useState(!1),[s,l]=g.useState(!1),[o,c]=g.useState(null),u=!!(e.stdoutTail||e.stderrTail),h=e.status==="running"||e.status==="pending",d=e.status==="failed"||e.status==="cancelled";async function f(p){l(!0),c(null);try{await p(e.taskId),await t()}catch(m){c(m instanceof Error?m.message:String(m))}finally{l(!1)}}return a.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsx("span",{className:q("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",qA(e.status)),children:HA(e.status)}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"font-medium text-content",children:e.kind}),e.exitCode!==null&&a.jsxs("span",{className:"text-muted",children:[" · exit ",e.exitCode]})]}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!h||s,loading:s,onClick:()=>void f(p=>n.cancelBackgroundTask(p)),children:"Cancel"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!u,onClick:()=>i(p=>!p),children:"Output"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!d||s,loading:s,onClick:()=>void f(p=>n.retryBackgroundTask(p)),children:"Retry"}),a.jsx("code",{title:e.taskId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.taskId)})]}),e.summary&&UA(e.status)&&a.jsx("p",{"aria-label":`task ${cr(e.taskId)} summary`,title:e.summary,className:"mt-1 truncate pl-1 text-[11px] text-muted",children:e.summary}),o&&a.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:o}),r&&u&&a.jsxs("pre",{"aria-label":`task ${cr(e.taskId)} output`,className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-canvas p-2 text-[11px] text-muted",children:[e.stdoutTail?`stdout -${e.stdoutTail}`:"",e.stdoutTail&&e.stderrTail?` - -`:"",e.stderrTail?`stderr -${e.stderrTail}`:""]})]})}function eT({agent:e,conversations:t,visibleLeaves:n,layout:r,projectId:i,onRefresh:s,onOpenConversation:l}){const{agent:o}=he(),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=e.live!==void 0,p=e.busy??{state:"idle"},m=p.state==="busy",x=[...e.tickets??[]].sort((S,T)=>S.position-T.position),w=[...e.inbox??[]].sort((S,T)=>S.createdAtMs-T.createdAtMs),v=[...e.backgroundTasks??[]].sort((S,T)=>T.updatedAtMs-S.updatedAtMs||S.taskId.localeCompare(T.taskId)),_=Math.max(e.inboxDepth??0,w.length,x.length),y=new Set(n.map(S=>S.id)),b=f&&y.has(e.live.nodeId),C=n.find(S=>!S.session&&!S.agent),k=m||x.some(S=>S.status==="inProgress");async function N(){await s()}async function R(){if(!(!e.live||!C||!o?.attachLiveAgent)){d(!0),u(null);try{const S=await o.attachLiveAgent(i,e.agentId,C.id);await r.attachLiveAgentToCell(C.id,e.agentId,S.sessionId),await N(),mx(C.id)}catch(S){u(S instanceof Error?S.message:String(S))}finally{d(!1)}}}async function L(){if(!e.live||!o?.stopLiveAgent)return;const S=k?" The current turn will be interrupted.":"";if(window.confirm(`Stop ${e.name}?${S}`)){d(!0),u(null);try{const T=await o.stopLiveAgent(i,e.agentId);if(y.has(e.live.nodeId)){const D=n.find(P=>P.id===e.live?.nodeId);(!D?.session||D.session===T.sessionId)&&await r.setSession(e.live.nodeId,null)}await N()}catch(T){u(T instanceof Error?T.message:String(T))}finally{d(!1)}}}return a.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),a.jsx("code",{className:"truncate text-xs text-muted",children:e.profileId})]}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx("span",{className:q("rounded-full px-2 py-0.5 text-xs font-medium",f?"bg-success/15 text-success":"bg-raised text-muted"),children:f?"Live":"Offline"}),a.jsx("span",{className:q("rounded-full px-2 py-0.5 text-xs font-medium",m?"bg-warning/15 text-warning":"bg-raised text-muted"),children:m?"Busy":"Idle"}),_>0&&a.jsxs("span",{"aria-label":`${e.name} queue depth ${_}`,className:"rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary",children:["Queue ",_]}),p.state==="busy"&&a.jsx("code",{"aria-label":`busy ticket ${cr(p.ticket)}`,title:p.ticket,className:"rounded bg-raised px-1.5 py-0.5 text-xs text-muted",children:cr(p.ticket)}),e.live&&b&&a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>mx(e.live.nodeId),children:"Open"}),e.live&&!b&&a.jsx(M,{size:"sm",variant:"ghost",disabled:!C||!o?.attachLiveAgent,loading:h,title:C?void 0:"No empty visible cell available",onClick:()=>void R(),children:"Attach"}),e.live&&a.jsx(M,{size:"sm",variant:"danger",loading:h,disabled:!o?.stopLiveAgent,onClick:()=>void L(),children:"Stop"})]})]}),e.live&&!b&&!C&&a.jsx("p",{className:"mt-1 text-xs text-muted",children:"No empty visible cell."}),c&&a.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:c}),x.length>0&&a.jsx("ul",{"aria-label":`${e.name} tickets`,className:"mt-2 flex flex-col gap-1",children:x.map(S=>a.jsx(QA,{ticket:S,summary:t.get(S.conversationId),onOpenConversation:l},S.ticketId))}),w.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),a.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:w.map(S=>a.jsx(JA,{item:S},S.id))})]}),v.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Background tasks"}),a.jsx("ul",{"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:v.map(S=>a.jsx(ZA,{task:S,onRefresh:N},S.taskId))})]})]})}function tT({projectId:e,onOpenConversation:t}){const n=ea(e),r=vw(e),i=n.state?.agents??[],s=r.layout?Qo(r.layout):[],l=new Map((n.state?.conversations??[]).map(o=>[o.conversationId,o]));return a.jsxs(we,{title:"Work",actions:a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"}),children:[n.error&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),n.busy&&n.state===null?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Loading work state…"})]}):i.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No agent work state."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:i.map(o=>a.jsx(eT,{agent:o,conversations:l,visibleLeaves:s,layout:r,projectId:e,onRefresh:n.refresh,onOpenConversation:t},o.agentId))})]})}function nT(e){return a.jsx($A,{children:a.jsx(tT,{...e})})}function Pu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Au(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function rT(e,t){const{conversation:n}=he(),[r,i]=g.useState([]),[s,l]=g.useState(!1),[o,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useRef([]),f=g.useRef(!1),p=g.useCallback(v=>{d.current=v,i(v)},[]),m=g.useCallback(async()=>{if(!f.current){f.current=!0,l(!0),c(null);try{const v=await n.readPage(e,t,{direction:"backward"});p(Au(v.turns)),h(v.hasMore)}catch(v){c(Pu(v))}finally{l(!1),f.current=!1}}},[n,e,t,p]),x=g.useCallback(async()=>{if(f.current)return;const v=d.current[0];if(!v){await m();return}f.current=!0,l(!0),c(null);try{const _=await n.readPage(e,t,{direction:"backward",anchor:v.id});_.turns.length>0&&p(Au([..._.turns,...d.current])),h(_.hasMore)}catch(_){c(Pu(_))}finally{l(!1),f.current=!1}},[n,e,t,m,p]),w=g.useCallback(async()=>{if(!f.current){if(d.current.length===0){await m();return}f.current=!0,l(!0),c(null);try{for(;;){const v=d.current.at(-1);if(!v)break;const _=await n.readPage(e,t,{direction:"forward",anchor:v.id});if(_.turns.length===0||(p(Au([...d.current,..._.turns])),!_.hasMore))break}}catch(v){c(Pu(v))}finally{l(!1),f.current=!1}}},[n,e,t,m,p]);return g.useEffect(()=>{p([]),h(!1),m()},[m,p]),{turns:r,busy:s,error:o,hasMore:u,loadOlder:x,refreshTail:w}}function gx(e){return e.length<=8?e:e.slice(0,8)}function Tu(e){return e.kind==="human"?"human":`agent:${e.agentId}`}function iT(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleString()}catch{return""}}function sT(e){switch(e){case"prompt":return"Prompt";case"response":return"Response";case"toolActivity":return"Tool"}}function lT({turn:e,sideClass:t}){const[n,r]=g.useState(!1);return a.jsx("div",{className:q("flex flex-col",t),children:a.jsxs("div",{className:"max-w-[80%] rounded-md border border-border bg-surface/60 px-3 py-1.5 text-xs text-muted",children:[a.jsxs("button",{type:"button",className:"flex items-center gap-1.5 font-medium hover:text-content",onClick:()=>r(i=>!i),"aria-expanded":n,children:[a.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),"Tool activity",a.jsxs("span",{className:"text-faint",children:["· ",e.textLen," chars"]})]}),n&&a.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted",children:e.text})]})})}function aT({projectId:e,conversationId:t,onClose:n}){const r=rT(e,t),i=ea(e),s=g.useMemo(()=>{const u=new Map;for(const h of i.state?.agents??[])h.name.trim()&&u.set(h.agentId,h.name.trim());return u},[i.state]),l=g.useMemo(()=>{const u=[],h=new Map;for(const d of r.turns){const f=Tu(d.source);if(h.has(f))continue;const p=u.length===0?"left":"right",m=d.source.kind==="human"?"User":s.get(d.source.agentId)??`Agent ${gx(d.source.agentId)}`;h.set(f,{label:m,side:p}),u.push(f)}return{order:u,meta:h}},[r.turns,s]),o=g.useMemo(()=>{const u=l.order.map(h=>l.meta.get(h)?.label??"?");return u.length>=2?`${u[0]} ↔ ${u[1]}`:u.length===1?u[0]:"Conversation"},[l]);function c(u){return l.meta.get(Tu(u))?.side??"left"}return a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border bg-surface px-4 py-2",children:[a.jsxs("div",{className:"flex min-w-0 flex-col",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:o}),a.jsx("code",{className:"truncate text-xs text-muted",title:t,children:gx(t)})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.refreshTail(),loading:r.busy,children:"Refresh"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"← Retour aux terminaux"})]})]}),r.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),a.jsxs("div",{className:"flex flex-1 flex-col gap-2 overflow-auto px-4 py-3",children:[r.hasMore&&a.jsx("div",{className:"flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.loadOlder(),loading:r.busy,children:"Charger les tours précédents"})}),r.busy&&r.turns.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Chargement du fil…"})]}):r.turns.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun tour pour le moment."}):r.turns.map(u=>{const h=c(u.source),d=h==="right"?"items-end":"items-start";if(u.role==="toolActivity")return a.jsx(lT,{turn:u,sideClass:d},u.id);const f=l.meta.get(Tu(u.source)),p=iT(u.atMs);return a.jsx("div",{className:q("flex flex-col",d),children:a.jsxs("div",{className:q("max-w-[80%] rounded-lg border px-3 py-2 text-sm",h==="right"?"border-primary/20 bg-primary/10 text-content":"border-border bg-raised text-content"),children:[a.jsxs("div",{className:"mb-1 flex items-baseline gap-2 text-xs text-muted",children:[a.jsx("span",{className:"font-medium text-content",children:f?.label??"?"}),a.jsxs("span",{children:["· ",sT(u.role)]}),p&&a.jsxs("span",{className:"text-faint",children:["· ",p]})]}),a.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.text})]})},u.id)})]})]})}function Lu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function oT(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function cT(){const{modelServer:e}=he(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(!1),o=g.useCallback(async()=>{l(!0),i(null);try{n(await e.listModelServers())}catch(f){i(Lu(f))}finally{l(!1)}},[e]);g.useEffect(()=>{o()},[o]);const c=g.useCallback(async f=>{l(!0),i(null);try{const p=await e.saveModelServer(f);return n(m=>{const x=m.findIndex(w=>w.id===p.id);if(x>=0){const w=m.slice();return w[x]=p,w}return[...m,p]}),p}catch(p){return i(Lu(p)),null}finally{l(!1)}},[e]),u=g.useCallback(async f=>{l(!0),i(null);try{return await e.deleteModelServer(f),n(p=>p.filter(m=>m.id!==f)),!0}catch(p){return oT(p)==="model_server_in_use"?i("Ce serveur est encore utilisé par un profil : détache-le d'abord (choisis « aucun » ou un autre serveur) avant de le supprimer."):i(Lu(p)),!1}finally{l(!1)}},[e]),h=g.useCallback(async f=>{try{return await e.previewModelServerCommand(f)}catch{return null}},[e]),d=g.useCallback(()=>i(null),[]);return{servers:t,error:r,busy:s,reload:o,save:c,remove:u,preview:h,clearError:d}}function uT(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function dT(e){return e.startsWith("/")||e.startsWith("\\")?!0:/^[a-zA-Z]:[/\\]/.test(e)}function hT(e){if(/\s/.test(e)||e.startsWith("http://")||e.startsWith("https://")||(e.match(/:/g)??[]).length>1)return!1;const[t,n]=e.includes(":")?[e.slice(0,e.indexOf(":")),e.slice(e.indexOf(":")+1)]:[e,void 0];if(n!==void 0&&n.length===0)return!1;const r=t.split("/");return r.length===2&&r[0].length>0&&r[1].length>0}function fT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),uT(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&(t.port="Port must be an integer between 1 and 65535."),e.servedModelName.trim().length===0&&(t.servedModelName="Le nom du modèle est requis."),(e.host.trim().length===0||/\s/.test(e.host))&&(t.host="L'adresse d'écoute est requise et ne doit pas contenir d'espace.");const n=e.modelSource;return n&&(n.type==="localPath"?n.path.trim().length===0?t.modelSource="Le chemin du fichier .gguf est requis.":dT(n.path.trim())||(t.modelSource="Le chemin du fichier doit être absolu."):n.repo.trim().length===0?t.modelSource="Le modèle Hugging Face est requis.":hT(n.repo.trim())||(t.modelSource="Format attendu : auteur/modèle ou auteur/modèle:quant (ex. unsloth/Qwen3.5-9B-GGUF:Q4_K_M).")),e.autoStart&&!n&&(t.modelSource="Le démarrage automatique nécessite une source de modèle."),t}function pT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`srv-${Math.random().toString(36).slice(2,10)}`}function mT(){return{id:pT(),kind:"llamaCpp",name:"",baseURL:"http://localhost:8080/v1",port:8080,servedModelName:"",host:"127.0.0.1",jinja:!1,args:[],autoStart:!1,stopPolicy:"stopOnAppExit"}}function gT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function xT(e){if(!e)return"";if(e.type==="localPath"){const r=e.path.trim();return r.length===0?"":(r.split(/[/\\]/).pop()??"").replace(/\.gguf$/i,"")}const t=e.repo.trim();return t.length===0?"":(t.includes(":")?t.slice(0,t.indexOf(":")):t).split("/").pop()??""}const vT=["--model","-m","-hf","--port","--host","-ngl","--gpu-layers","-c","--ctx-size","--jinja"];function _T(e){const t=new Set(vT),n=new Set;for(const r of e){const i=r.includes("=")?r.slice(0,r.indexOf("=")):r;t.has(i)&&n.add(i)}return[...n]}function Et({children:e}){return a.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function Ii({children:e}){return a.jsx("small",{className:"text-xs text-muted",children:e})}const yT=[{value:"stopOnAppExit",label:"Stop on app exit"},{value:"keepAlive",label:"Keep alive"},{value:"stopWhenUnused",label:"Stop when unused"}];function bT({vm:e}){const[t,n]=g.useState(null);function r(){e.clearError(),n(mT())}function i(l){e.clearError(),n({...l})}async function s(){if(!t)return;await e.save(t)&&n(null)}return a.jsx(we,{"aria-label":"local model servers",title:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:"Local model servers"}),a.jsx(M,{size:"sm","aria-label":"add model server",onClick:r,className:"ml-auto",children:"Add server"})]}),children:a.jsxs("div",{className:"flex flex-col gap-3",children:[e.error&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error}),e.servers.length===0&&!t&&a.jsx("p",{className:"text-xs text-muted",children:"No local server declared yet. Add one to auto-manage a `llama-server`, or keep using an external endpoint."}),a.jsx("ul",{className:"flex list-none flex-col gap-2 p-0",children:e.servers.map(l=>a.jsxs("li",{className:"flex items-center gap-2 rounded-md border border-border bg-raised p-2",children:[a.jsxs("span",{className:"flex min-w-0 flex-col",children:[a.jsx("strong",{className:"truncate text-sm text-content",children:l.name}),a.jsxs("span",{className:"truncate text-xs text-muted",children:[l.baseURL," · ",l.servedModelName,l.autoStart?" · auto-start":""]})]}),a.jsxs("span",{className:"ml-auto flex items-center gap-1",children:[a.jsx(M,{size:"sm","aria-label":`edit ${l.name}`,onClick:()=>i(l),disabled:e.busy,children:"Edit"}),a.jsx(ir,{size:"sm","aria-label":`delete ${l.name}`,onClick:()=>void e.remove(l.id),disabled:e.busy,children:"×"})]})]},l.id))}),t&&a.jsx(kT,{draft:t,busy:e.busy,preview:e.preview,onChange:n,onCancel:()=>{e.clearError(),n(null)},onSubmit:()=>void s()})]})})}function wT({kind:e,onSelect:t}){const n=(r,i)=>{const s=e===r;return a.jsx("button",{type:"button","aria-pressed":s,onClick:()=>t(r),className:q("h-8 flex-1 rounded-md px-3 text-xs font-medium transition-colors",s?"bg-primary text-white":"bg-raised text-muted hover:text-content"),children:i})};return a.jsxs("div",{role:"group","aria-label":"source du modèle",className:"flex gap-1 rounded-md border border-border p-1",children:[n("huggingFace","Télécharger depuis Hugging Face"),n("localPath","Fichier .gguf local")]})}function ST({preview:e,autoStart:t}){const[n,r]=g.useState(!1),i=t?"Commande générée":"Commande à lancer manuellement";async function s(){if(e)try{await navigator.clipboard.writeText(e.display),r(!0),setTimeout(()=>r(!1),1500)}catch{}}return a.jsxs("section",{"aria-label":"command preview",className:"flex flex-col gap-1 rounded-md border border-border bg-raised p-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Et,{children:i}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"copier la commande",onClick:()=>void s(),disabled:!e,className:"ml-auto",children:n?"Copié":"Copier"})]}),e?a.jsx("code",{"aria-label":"preview command line",className:"whitespace-pre-wrap break-all font-mono text-xs text-content",children:e.display}):a.jsx("span",{className:"text-xs text-muted",children:"Renseigne une source de modèle pour voir la commande."})]})}function kT({draft:e,busy:t,preview:n,onChange:r,onCancel:i,onSubmit:s}){const l=fT(e),o=Object.keys(l).length===0,c=b=>r({...e,...b}),[u,h]=g.useState(e.modelSource?.type??"huggingFace"),d=e.modelSource?.type==="huggingFace"?e.modelSource.repo:"",f=e.modelSource?.type==="localPath"?e.modelSource.path:"";function p(b){const C={modelSource:b};if(e.servedModelName.trim().length===0){const k=xT(b);k.length>0&&(C.servedModelName=k)}c(C)}function m(b){b!==u&&(h(b),c({modelSource:void 0}))}const[x,w]=g.useState(null),v=JSON.stringify({modelSource:e.modelSource,port:e.port,host:e.host,gpuLayers:e.gpuLayers,contextSize:e.contextSize,jinja:e.jinja,binaryPath:e.binaryPath,args:e.args}),_=g.useRef(e);_.current=e,g.useEffect(()=>{if(!e.modelSource){w(null);return}let b=!1;const C=setTimeout(()=>{n(_.current).then(k=>{b||w(k)})},250);return()=>{b=!0,clearTimeout(C)}},[v,n]);const y=_T(e.args);return a.jsxs("fieldset",{"aria-label":"model server editor",className:"flex flex-col gap-3 rounded-md border border-primary/40 p-3",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:e.name.trim().length>0?e.name:"New server"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Nom"}),a.jsx(ce,{"aria-label":"server name",value:e.name,invalid:!!l.name,onChange:b=>c({name:b.target.value})}),l.name&&a.jsx("small",{className:"text-xs text-danger",children:l.name})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Source du modèle"}),a.jsx(wT,{kind:u,onSelect:m})]}),u==="huggingFace"?a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Modèle Hugging Face"}),a.jsx(ce,{"aria-label":"hugging face model",value:d,placeholder:"unsloth/Qwen3.5-9B-GGUF:Q4_K_M",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"huggingFace",repo:C})}}),a.jsx(Ii,{children:"llama.cpp téléchargera/cache le fichier automatiquement."}),l.modelSource&&a.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}):a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Fichier .gguf"}),a.jsx(ce,{"aria-label":"local gguf file",value:f,placeholder:"/home/me/models/qwen.gguf",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"localPath",path:C})}}),a.jsx(Ii,{children:"Chemin absolu vers un .gguf déjà présent."}),l.modelSource&&a.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Nom du modèle dans IdeA"}),a.jsx(ce,{"aria-label":"server served model name",value:e.servedModelName,placeholder:"qwen3-coder-30b",invalid:!!l.servedModelName,onChange:b=>c({servedModelName:b.target.value})}),a.jsx(Ii,{children:"Nom envoyé aux clients OpenAI-compatible."}),l.servedModelName&&a.jsx("small",{className:"text-xs text-danger",children:l.servedModelName})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs("label",{className:"flex min-w-[12rem] flex-1 flex-col gap-1",children:[a.jsx(Et,{children:"Commande serveur"}),a.jsx(ce,{"aria-label":"server binary path",value:e.binaryPath??"",placeholder:"llama-server",onChange:b=>{const C=b.target.value;c({binaryPath:C.length===0?void 0:C})}}),a.jsx(Ii,{children:"Laisse vide pour résoudre `llama-server` via le PATH."})]}),a.jsxs("label",{className:"flex min-w-[6rem] flex-col gap-1",children:[a.jsx(Et,{children:"Port"}),a.jsx(ce,{"aria-label":"server port",value:Number.isNaN(e.port)?"":e.port.toString(),inputMode:"numeric",invalid:!!l.port,onChange:b=>c({port:Number.parseInt(b.target.value,10)})}),l.port&&a.jsx("small",{className:"text-xs text-danger",children:l.port})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Base URL (OpenAI-compatible)"}),a.jsx(ce,{"aria-label":"server base url",value:e.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!l.baseURL,onChange:b=>c({baseURL:b.target.value})}),l.baseURL&&a.jsx("small",{className:"text-xs text-danger",children:l.baseURL})]}),a.jsxs("label",{className:"flex items-start gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":"server auto start",checked:e.autoStart,disabled:!e.modelSource,onChange:b=>c({autoStart:b.target.checked}),className:"mt-1 accent-primary disabled:opacity-50"}),a.jsxs("span",{className:"flex flex-col",children:[a.jsx(Et,{children:"Démarrer automatiquement"}),!e.modelSource&&a.jsx(Ii,{children:"Renseigne d'abord une source de modèle pour l'activer."})]})]}),a.jsxs("details",{className:"rounded-md border border-border p-2",children:[a.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted",children:"Réglages llama.cpp"}),a.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsxs(Et,{children:["Couches GPU ",a.jsx("span",{className:"text-muted",children:"(-ngl)"})]}),a.jsx(ce,{"aria-label":"gpu layers",value:e.gpuLayers===void 0?"":String(e.gpuLayers),inputMode:"numeric",placeholder:"99",onChange:b=>{const C=b.target.value.trim();c({gpuLayers:C.length===0?void 0:Number.parseInt(C,10)})}}),a.jsx(Ii,{children:"0 = CPU seul."})]}),a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsxs(Et,{children:["Taille de contexte ",a.jsx("span",{className:"text-muted",children:"(-c)"})]}),a.jsx(ce,{"aria-label":"context size",value:e.contextSize===void 0?"":String(e.contextSize),inputMode:"numeric",placeholder:"16384",onChange:b=>{const C=b.target.value.trim();c({contextSize:C.length===0?void 0:Number.parseInt(C,10)})}})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsxs(Et,{children:["Adresse d'écoute ",a.jsx("span",{className:"text-muted",children:"(--host)"})]}),a.jsx(ce,{"aria-label":"listen host",value:e.host,placeholder:"127.0.0.1",invalid:!!l.host,onChange:b=>c({host:b.target.value})}),l.host&&a.jsx("small",{className:"text-xs text-danger",children:l.host})]}),a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":"jinja template",checked:e.jinja,onChange:b=>c({jinja:b.target.checked}),className:"accent-primary"}),a.jsxs(Et,{children:["Template chat Jinja ",a.jsx("span",{className:"text-muted",children:"(--jinja)"})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Arguments supplémentaires"}),a.jsx(ce,{"aria-label":"extra arguments",value:e.args.join(" "),placeholder:"--flash-attn --parallel 2",onChange:b=>c({args:gT(b.target.value)})}),y.length>0&&a.jsxs("small",{className:"text-xs text-warning",role:"status",children:[y.join(", ")," : cette option est déjà pilotée par un champ ci-dessus."]})]}),a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx(Et,{children:"Stop policy"}),a.jsx("select",{"aria-label":"server stop policy",value:e.stopPolicy,onChange:b=>c({stopPolicy:b.target.value}),className:q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:yT.map(b=>a.jsx("option",{value:b.value,children:b.label},b.value))})]})]})]}),a.jsx(ST,{preview:x,autoStart:e.autoStart}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{variant:"primary",size:"sm","aria-label":"save model server",onClick:s,disabled:t||!o,children:"Save server"}),a.jsx(M,{variant:"ghost",size:"sm","aria-label":"cancel model server",onClick:i,disabled:t,children:"Cancel"})]})]})}const Du="";function CT({servers:e,value:t,onChange:n,ariaLabel:r="local model server"}){const i=t!==void 0&&!e.some(s=>s.id===t);return a.jsxs("select",{"aria-label":r,value:t??Du,onChange:s=>n(s.target.value===Du?void 0:s.target.value),className:q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:[a.jsx("option",{value:Du,children:"None (external endpoint)"}),e.map(s=>a.jsxs("option",{value:s.id,children:[s.name," — ",s.servedModelName]},s.id)),i&&a.jsxs("option",{value:t,children:[t," (unknown / removed)"]})]})}function jT({mode:e,configured:t,references:n}){if(e==="firstRun")return n.map(l=>({profile:l,selected:!1,available:null}));const r=new Set(t.map(l=>l.id)),i=t.map(l=>({profile:l,selected:!0,available:null})),s=n.filter(l=>!r.has(l.id)).map(l=>({profile:l,selected:!1,available:null}));return[...i,...s]}const NT=3e3;function Da(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function ET(e="firstRun"){const{profile:t}=he(),[n,r]=g.useState(null),[i,s]=g.useState([]),[l,o]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),f=g.useRef(0),p=g.useRef(null);g.useEffect(()=>()=>{f.current+=1,p.current!==null&&clearTimeout(p.current)},[]);const m=g.useCallback(async(k,N)=>{const R=f.current+1;f.current=R;const L=()=>f.current!==R;d(!0),p.current!==null&&clearTimeout(p.current),p.current=setTimeout(()=>{L()||d(!1)},NT);try{const S=await t.detectProfiles(k);if(L())return;const T=new Map(S.map(D=>[D.profile.id,D.available]));s(D=>D.map(P=>{const I=T.get(P.profile.id)??P.available;return{...P,available:I,selected:N.preselect?I===!0:P.selected}}))}catch(S){if(L())return;N.reportError&&o(Da(S))}finally{L()||(p.current!==null&&clearTimeout(p.current),p.current=null,d(!1))}},[t]),x=g.useCallback(async()=>{u(!0),o(null);let k=null;try{const[N,R]=await Promise.all([t.firstRunState(),e==="edit"?t.listProfiles():Promise.resolve([])]);r(N.isFirstRun);const L=jT({mode:e,configured:R,references:N.referenceProfiles});k=L.map(S=>S.profile),s(L)}catch(N){o(Da(N)),r(!1)}finally{u(!1)}k!==null&&m(k,{preselect:e==="firstRun",reportError:!1})},[t,m,e]);g.useEffect(()=>{x()},[x]);const w=g.useCallback(k=>{s(N=>N.map(R=>R.profile.id===k?{...R,selected:!R.selected}:R))},[]),v=g.useCallback((k,N)=>{s(R=>R.map(L=>L.profile.id===k?{...L,profile:N}:L))},[]),_=g.useCallback(async k=>{o(null);try{const N=await t.cloneOpenCodeProfileFromSeed(k);s(R=>[...R,{profile:N,selected:!0,available:null}])}catch(N){o(Da(N))}},[t]),y=g.useCallback(k=>{s(N=>N.filter(R=>R.profile.id!==k))},[]),b=g.useCallback(async()=>{o(null),await m(i.map(k=>k.profile),{preselect:!1,reportError:!0})},[m,i]),C=g.useCallback(async()=>{u(!0),o(null);try{const k=i.filter(N=>N.selected).map(N=>N.profile);await t.configureProfiles(k),r(!1)}catch(k){o(Da(k))}finally{u(!1)}},[t,i]);return{isFirstRun:n,entries:i,error:l,busy:c,detecting:h,toggle:w,updateProfile:v,addOpenCodeProfile:_,remove:y,detect:b,finish:C,reload:x}}function PT(e){return e.length===0||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:/.test(e)?!1:!e.split(/[/\\]/).includes("..")}function yw(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function bw(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function Ru(e,t){return e===void 0?!0:Number.isInteger(e)&&e>0&&e<=t}const xx=4294967295,AT=65535;function TT(e){const t={};return bw(e.endpoint)||(t.endpoint="Endpoint must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),e.apiKeyEnv!==void 0&&e.apiKeyEnv.length>0&&!yw(e.apiKeyEnv)&&(t.apiKeyEnv="Must be a valid env var name (not the key itself)."),Ru(e.requestTimeoutMs,xx)||(t.requestTimeoutMs="Must be a positive integer (ms)."),Ru(e.connectTimeoutMs,xx)||(t.connectTimeoutMs="Must be a positive integer (ms)."),Ru(e.maxToolIterations,AT)||(t.maxToolIterations="Must be a positive integer."),t}function LT(e){const t={};return bw(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),t}function DT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),e.command.trim().length===0&&(t.command="Command is required.");const n=e.contextInjection;return n.strategy==="conventionFile"?PT(n.target)||(t.target="Target must be a relative file name (no .. or absolute)."):n.strategy==="flag"?n.flag.trim().length===0&&(t.flag="Flag is required."):n.strategy==="env"&&(yw(n.var)||(t.var="Must be a valid env var identifier.")),e.structuredAdapter==="openAiCompatible"&&(e.chatHttp?Object.assign(t,TT(e.chatHttp)):(t.endpoint="Endpoint must start with http:// or https://.",t.model="Model is required.")),e.structuredAdapter==="openCode"&&!e.opencodeProvider&&(e.opencode?Object.assign(t,LT(e.opencode)):(t.baseURL="Base URL must start with http:// or https://.",t.model="Model is required.")),t}function RT(){return{endpoint:"http://localhost:11434/v1",model:"qwen2.5-coder",requestTimeoutMs:12e4,connectTimeoutMs:5e3,maxToolIterations:16}}function MT(){return{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}function IT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function qe({children:e}){return a.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function ww(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function OT(){const{profile:e}=he(),[t,n]=g.useState(null),[r,i]=g.useState(!1),[s,l]=g.useState(null),o=g.useCallback(async()=>{i(!0),l(null);try{n(await e.listOpenCodeProviders())}catch(c){n(null),l(ww(c))}finally{i(!1)}},[e]);return g.useEffect(()=>{o()},[o]),{providers:t,loading:r,error:s,reload:()=>void o()}}function Sw({onDone:e,forceOpen:t=!1}){const n=ET(t?"edit":"firstRun"),r=cT(),i=OT();if(n.isFirstRun===null||!t&&n.isFirstRun===!1)return null;async function s(){await n.finish(),e?.()}return a.jsx(we,{"aria-label":"first run setup",className:"border-primary/40",title:a.jsxs("div",{className:"flex flex-col",children:[a.jsx("h2",{className:"text-base font-semibold text-content",children:"Welcome to IdeA"}),a.jsx("p",{className:"text-sm text-muted",children:"Choose which AI CLIs to configure. Commands are pre-filled and editable."})]}),children:a.jsxs("div",{className:"flex flex-col gap-4",children:[n.error&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),a.jsxs(pw,{children:[a.jsx(M,{onClick:()=>void n.detect(),disabled:n.busy,className:"whitespace-nowrap",children:"Detect installed CLIs"}),n.detecting&&a.jsx("span",{role:"status",className:"text-xs text-muted",children:"Detecting…"}),a.jsx(M,{onClick:()=>void n.addOpenCodeProfile(),disabled:n.busy,className:"whitespace-nowrap",children:"Add OpenCode profile"})]}),a.jsx(bT,{vm:r}),a.jsx("ul",{className:"flex list-none flex-col gap-3 p-0",children:n.entries.map(l=>a.jsx(BT,{entry:l,servers:r.servers,providerCatalog:i,onToggle:()=>n.toggle(l.profile.id),onChange:o=>n.updateProfile(l.profile.id,o),onRemove:()=>n.remove(l.profile.id),onDuplicate:l.profile.structuredAdapter==="openCode"?()=>n.addOpenCodeProfile({name:`${l.profile.name} (copy)`,opencode:l.profile.opencode}):void 0},l.profile.id))}),a.jsx("footer",{className:"flex gap-2",children:a.jsx(M,{variant:"primary",onClick:()=>void s(),disabled:n.busy,children:"Save and continue"})})]})})}function BT({entry:e,servers:t,providerCatalog:n,onToggle:r,onChange:i,onRemove:s,onDuplicate:l}){const{profile:o,selected:c,available:u}=e,h=DT(o),d=o.structuredAdapter==="openCode";return a.jsxs("li",{className:"flex flex-col gap-2 rounded-md border border-border bg-raised p-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:r,"aria-label":`use ${o.name}`,className:"accent-primary"}),a.jsx("strong",{className:"text-sm text-content",children:o.name})]}),a.jsx("span",{"aria-label":`${o.name} availability`,className:q("text-xs",u===null?"text-faint":u?"text-success":"text-danger"),children:u===null?"—":u?"✓ installed":"✗ not found"}),a.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[l&&a.jsx(M,{size:"sm","aria-label":`duplicate ${o.name}`,onClick:l,children:"Duplicate"}),a.jsx(ir,{size:"sm","aria-label":`remove ${o.name}`,onClick:s,children:"×"})]})]}),d&&a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Name"}),a.jsx(ce,{"aria-label":`${o.name} name`,value:o.name,invalid:!!h.name,onChange:f=>i({...o,name:f.target.value})}),h.name&&a.jsx("small",{className:"text-xs text-danger",children:h.name})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Command"}),a.jsx(ce,{"aria-label":`${o.name} command`,value:o.command,invalid:!!h.command,onChange:f=>i({...o,command:f.target.value})}),h.command&&a.jsx("small",{className:"text-xs text-danger",children:h.command})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Arguments"}),a.jsx(ce,{"aria-label":`${o.name} args`,value:o.args.join(" "),onChange:f=>i({...o,args:IT(f.target.value)})})]}),o.structuredAdapter==="openAiCompatible"&&a.jsx(WT,{profile:o,errors:h,onChange:i}),o.structuredAdapter==="openCode"&&a.jsx(zT,{profile:o,errors:h,servers:t,providerCatalog:n,onChange:i})]})}function zT({profile:e,errors:t,servers:n,providerCatalog:r,onChange:i}){const[s,l]=g.useState(e.opencodeProvider?"cloud":"local");return a.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[a.jsx("div",{role:"radiogroup","aria-label":"mode du profil OpenCode",className:"flex w-fit gap-1 rounded-md border border-border bg-raised p-0.5",children:[{id:"local",label:"Local (llama.cpp)"},{id:"cloud",label:"Provider cloud"}].map(o=>{const c=s===o.id;return a.jsx("button",{type:"button",role:"radio","aria-checked":c,onClick:()=>l(o.id),className:q("rounded px-2.5 py-1 text-xs font-medium transition-colors",c?"bg-primary text-on-primary":"text-muted hover:text-content"),children:o.label},o.id)})}),s==="local"&&a.jsx($T,{profile:e,errors:t,servers:n,onChange:i}),s==="cloud"&&a.jsx(FT,{profile:e,catalog:r,onChange:i})]})}const vx="__custom__",_x="@ai-sdk/openai-compatible";function FT({profile:e,catalog:t,onChange:n}){const{profile:r}=he(),i=e.opencodeProvider,[s,l]=g.useState(i?.custom?"custom":"catalog"),[o,c]=g.useState(i?.providerId??""),[u,h]=g.useState(i?.model??""),[d,f]=g.useState(""),[p,m]=g.useState(i?.custom?.npm??_x),[x,w]=g.useState(i?.custom?.baseUrl??""),[v,_]=g.useState(i?.custom?.displayName??""),[y,b]=g.useState(""),[C,k]=g.useState(!1),[N,R]=g.useState(!1),[L,S]=g.useState(null),[T,D]=g.useState({}),P=i!==void 0,I=t.providers?.find(z=>z.providerId===o)?.models??[],O=t.providers!==null&&!t.loading,U=(t.providers??[]).filter(z=>{if(z.providerId===o)return!0;const j=d.trim().toLowerCase();return j.length===0?!0:z.displayName.toLowerCase().includes(j)||z.providerId.toLowerCase().includes(j)}),G=N||y.length===0||s==="catalog"&&(!O||!!t.error);async function E(){const z={};if(o.trim().length===0&&(z.providerId="Le provider est obligatoire."),u.trim().length===0&&(z.model="Le modèle est obligatoire."),s==="custom"&&(p.trim().length===0&&(z.npm="Le paquet npm est obligatoire."),x.trim().length===0&&(z.baseUrl="L'URL de base est obligatoire.")),y.length===0&&(z.apiKey="La clé API est obligatoire."),D(z),!(Object.keys(z).length>0)){R(!0),S(null);try{const j=await r.saveOpenCodeProviderProfile({profile:e,providerId:o.trim(),model:u.trim(),apiKey:y,...s==="custom"?{custom:{npm:p.trim(),baseUrl:x.trim(),displayName:v.trim().length>0?v.trim():void 0}}:{}});n(j),b("")}catch(j){S(ww(j))}finally{R(!1)}}}return a.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider cloud (OpenCode)"}),L&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:L}),t.loading&&a.jsx("p",{className:"text-xs text-faint",children:"Chargement des providers…"}),t.error&&a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("p",{role:"alert",className:"text-sm text-danger",children:"Impossible de charger la liste des providers cloud."}),a.jsx(M,{size:"sm",onClick:()=>t.reload(),className:"w-fit",children:"Réessayer"})]}),s==="catalog"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Provider"}),O&&a.jsx("input",{type:"text","aria-label":`${e.name} provider search`,placeholder:"Rechercher un provider…",value:d,onChange:z=>f(z.target.value),className:"h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"}),a.jsxs("select",{"aria-label":`${e.name} provider`,value:o,disabled:!O,onChange:z=>{const j=z.target.value;j===vx?(l("custom"),c(""),h("")):(c(j),h("")),D(re=>({...re,providerId:void 0}))},className:q("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",T.providerId?"border-danger":"border-border"),children:[a.jsx("option",{value:"",disabled:!0,children:t.loading?"Chargement des providers…":"Choisir un provider…"}),U.map(z=>a.jsx("option",{value:z.providerId,children:z.displayName},z.providerId)),a.jsx("option",{value:vx,children:"Autre / personnalisé…"})]}),T.providerId&&a.jsx("small",{className:"text-xs text-danger",children:T.providerId})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Modèle"}),a.jsxs("select",{"aria-label":`${e.name} model`,value:u,disabled:o.length===0,onChange:z=>{h(z.target.value),D(j=>({...j,model:void 0}))},className:q("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",T.model?"border-danger":"border-border"),children:[a.jsx("option",{value:"",disabled:!0,children:o.length===0?"—":"Choisir un modèle…"}),I.map(z=>a.jsx("option",{value:z,children:z},z))]}),T.model&&a.jsx("small",{className:"text-xs text-danger",children:T.model})]})]}),s==="custom"&&a.jsxs("fieldset",{className:"flex flex-col gap-2 rounded-md border border-border/50 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider personnalisé"}),a.jsx(M,{variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{l("catalog"),c(""),h(""),D({})},children:"← Choisir un provider du catalogue"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Identifiant du provider"}),a.jsx(ce,{"aria-label":`${e.name} custom provider id`,value:o,placeholder:"ex. mon-provider",invalid:!!T.providerId,onChange:z=>{c(z.target.value),D(j=>({...j,providerId:void 0}))}}),T.providerId&&a.jsx("small",{className:"text-xs text-danger",children:T.providerId})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Paquet npm"}),a.jsx(ce,{"aria-label":`${e.name} custom npm package`,value:p,placeholder:_x,invalid:!!T.npm,onChange:z=>{m(z.target.value),D(j=>({...j,npm:void 0}))}}),T.npm&&a.jsx("small",{className:"text-xs text-danger",children:T.npm})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"URL de base"}),a.jsx(ce,{"aria-label":`${e.name} custom base url`,value:x,placeholder:"https://api.mon-provider.example/v1",invalid:!!T.baseUrl,onChange:z=>{w(z.target.value),D(j=>({...j,baseUrl:void 0}))}}),T.baseUrl&&a.jsx("small",{className:"text-xs text-danger",children:T.baseUrl})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Modèle"}),a.jsx(ce,{"aria-label":`${e.name} model`,value:u,placeholder:"ex. mon-modele-1",invalid:!!T.model,onChange:z=>{h(z.target.value),D(j=>({...j,model:void 0}))}}),T.model&&a.jsx("small",{className:"text-xs text-danger",children:T.model})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Libellé du modèle (optionnel)"}),a.jsx(ce,{"aria-label":`${e.name} custom display name`,value:v,placeholder:"ex. Mon modèle",onChange:z=>_(z.target.value)})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Clé API"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(ce,{"aria-label":`${e.name} api key`,type:C?"text":"password",value:y,placeholder:P?"Ressaisissez la clé API pour confirmer l'enregistrement":"ex. sk-ant-…",invalid:!!T.apiKey,onChange:z=>{b(z.target.value),D(j=>({...j,apiKey:void 0}))}}),a.jsx(ir,{size:"sm","aria-label":"afficher/masquer la clé API",onClick:()=>k(z=>!z),children:C?"🙈":"👁"})]}),T.apiKey&&a.jsx("small",{className:"text-xs text-danger",children:T.apiKey}),a.jsx("small",{className:"text-xs text-faint",children:"Jamais affichée ni renvoyée par IdeA une fois enregistrée ; stockée chiffrée localement."}),P&&a.jsx("small",{className:"text-xs text-muted",children:"Pour des raisons de sécurité, la clé n'est jamais réaffichée : ressaisissez-la à chaque modification de ce profil."})]}),a.jsx(M,{variant:"primary",size:"sm",loading:N,disabled:G,onClick:()=>void E(),className:"w-fit",children:"Enregistrer"})]})}function $T({profile:e,errors:t,servers:n,onChange:r}){const i=e.opencode??MT(),s=l=>r({...e,opencode:{...i,...l}});return a.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local model (OpenCode + llama.cpp)"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Base URL"}),a.jsx(ce,{"aria-label":`${e.name} base url`,value:i.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!t.baseURL,onChange:l=>s({baseURL:l.target.value})}),t.baseURL&&a.jsx("small",{className:"text-xs text-danger",children:t.baseURL})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Model"}),a.jsx(ce,{"aria-label":`${e.name} model`,value:i.model,placeholder:"qwen3-coder-30b",invalid:!!t.model,onChange:l=>s({model:l.target.value})}),t.model&&a.jsx("small",{className:"text-xs text-danger",children:t.model})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"API key (optional — a local llama.cpp needs none)"}),a.jsx(ce,{"aria-label":`${e.name} api key`,value:i.apiKey??"",placeholder:"e.g. sk-no-key",onChange:l=>{const o=l.target.value;s({apiKey:o.length===0?void 0:o})}})]}),a.jsxs("div",{className:"flex flex-wrap gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":`${e.name} reasoning`,checked:i.reasoning??!0,onChange:l=>s({reasoning:l.target.checked}),className:"accent-primary"}),a.jsx(qe,{children:"Reasoning"})]}),a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":`${e.name} attachment`,checked:i.attachment??!1,onChange:l=>s({attachment:l.target.checked}),className:"accent-primary"}),a.jsx(qe,{children:"Attachments"})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Local model server (bind to a managed llama.cpp server, or none)"}),a.jsx(CT,{ariaLabel:`${e.name} local model server`,servers:n,value:i.localModelServerId,onChange:l=>s({localModelServerId:l})})]})]})}function Mu(e){const t=e.trim();if(t.length===0)return;const n=Number(t);return Number.isFinite(n)?n:NaN}function WT({profile:e,errors:t,onChange:n}){const r=e.chatHttp??RT(),i=s=>n({...e,chatHttp:{...r,...s}});return a.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local / LAN model (OpenAI-compatible)"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Endpoint"}),a.jsx(ce,{"aria-label":`${e.name} endpoint`,value:r.endpoint,placeholder:"http://localhost:11434/v1",invalid:!!t.endpoint,onChange:s=>i({endpoint:s.target.value})}),t.endpoint&&a.jsx("small",{className:"text-xs text-danger",children:t.endpoint})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Model"}),a.jsx(ce,{"aria-label":`${e.name} model`,value:r.model,placeholder:"qwen2.5-coder",invalid:!!t.model,onChange:s=>i({model:s.target.value})}),t.model&&a.jsx("small",{className:"text-xs text-danger",children:t.model})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"API key — environment variable name (never the key itself)"}),a.jsx(ce,{"aria-label":`${e.name} api key env`,value:r.apiKeyEnv??"",placeholder:"e.g. OPENAI_API_KEY (variable name, not the secret)",invalid:!!t.apiKeyEnv,onChange:s=>{const l=s.target.value.trim();i({apiKeyEnv:l.length===0?void 0:l})}}),t.apiKeyEnv&&a.jsx("small",{className:"text-xs text-danger",children:t.apiKeyEnv})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsx(qe,{children:"Request timeout (ms)"}),a.jsx(ce,{"aria-label":`${e.name} request timeout`,value:r.requestTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.requestTimeoutMs,onChange:s=>i({requestTimeoutMs:Mu(s.target.value)})}),t.requestTimeoutMs&&a.jsx("small",{className:"text-xs text-danger",children:t.requestTimeoutMs})]}),a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsx(qe,{children:"Connect timeout (ms)"}),a.jsx(ce,{"aria-label":`${e.name} connect timeout`,value:r.connectTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.connectTimeoutMs,onChange:s=>i({connectTimeoutMs:Mu(s.target.value)})}),t.connectTimeoutMs&&a.jsx("small",{className:"text-xs text-danger",children:t.connectTimeoutMs})]}),a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsx(qe,{children:"Max tool iterations"}),a.jsx(ce,{"aria-label":`${e.name} max tool iterations`,value:r.maxToolIterations?.toString()??"",inputMode:"numeric",invalid:!!t.maxToolIterations,onChange:s=>i({maxToolIterations:Mu(s.target.value)})}),t.maxToolIterations&&a.jsx("small",{className:"text-xs text-danger",children:t.maxToolIterations})]})]})]})}function kw(){const{profile:e}=he(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(!1),o=g.useCallback(async()=>{i(null);try{n(await e.listProfiles())}catch(u){i(u&&typeof u=="object"&&"message"in u?String(u.message):String(u))}},[e]);g.useEffect(()=>{o()},[o]);async function c(u){await e.deleteProfile(u),await o()}return s?a.jsx(Sw,{forceOpen:!0,onDone:()=>{l(!1),o()}}):a.jsx(we,{"aria-label":"ai profiles settings",title:"Profils IA",actions:a.jsx(M,{size:"sm",onClick:()=>l(!0),children:"Configurer les profils"}),children:a.jsxs("div",{className:"flex flex-col gap-3",children:[r&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:r}),t.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun profil configuré."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(u=>a.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[a.jsxs("span",{className:"flex items-baseline gap-2",children:[a.jsx("strong",{className:"text-sm text-content",children:u.name}),a.jsx("code",{className:"text-xs text-muted",children:u.command})]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`supprimer ${u.name}`,onClick:()=>void c(u.id),children:"Supprimer"})]},u.id))})]})})}const HT=3e3,UT=2500;function yx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function qT(){const{device:e}=he(),[t,n]=g.useState(null),[r,i]=g.useState(null),[s,l]=g.useState(!1),[o,c]=g.useState(!1),[u,h]=g.useState(null),[d,f]=g.useState([]),[p,m]=g.useState(!1),x=g.useRef(null),w=g.useCallback(async()=>{try{const R=await e.listDevices();return n(R),i(null),R}catch(R){return i(yx(R)),null}},[e]),v=g.useCallback(async()=>{const R=await w();R&&(x.current=new Set(R.map(L=>L.deviceId)))},[w]);g.useEffect(()=>{v()},[v]),g.useEffect(()=>{if(!u)return;const R=setInterval(()=>{(async()=>{const L=await w();if(!L)return;const S=x.current;if(x.current=new Set(L.map(D=>D.deviceId)),!S)return;const T=L.filter(D=>!S.has(D.deviceId)).map(D=>D.deviceId);T.length>0&&f(T)})()},HT);return()=>clearInterval(R)},[u,w]),g.useEffect(()=>{if(d.length===0)return;const R=setTimeout(()=>f([]),UT);return()=>clearTimeout(R)},[d]);const _=g.useCallback(async R=>{l(!0),i(null);try{return await R(),!0}catch(L){return i(yx(L)),!1}finally{l(!1)}},[]),y=g.useCallback(async()=>{c(!0);try{await _(async()=>{h(await e.createPairingCode())})}finally{c(!1)}},[e,_]),b=g.useCallback(()=>h(null),[]),C=g.useCallback(async(R,L)=>{await _(()=>e.renameDevice(R,L))&&await v()},[e,_,v]),k=g.useCallback(async R=>{const L=R.isCurrentDevice;await _(()=>e.revokeDevice(R.deviceId))&&(L?m(!0):await v())},[e,_,v]),N=g.useCallback(async()=>{const R=t?.some(L=>L.isCurrentDevice)??!1;await _(()=>e.revokeAllDevices())&&(R?m(!0):await v())},[t,e,_,v]);return{devices:t,error:r,busy:s,generating:o,code:u,freshDeviceIds:d,sessionEnded:p,refresh:v,generateCode:y,dismissCode:b,rename:C,revoke:k,revokeAll:N}}const VT=2*60*1e3;function bx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function KT(e){return e.toLocaleTimeString("fr-FR",{hour:"2-digit",minute:"2-digit"})}function Cw(e,t=new Date){const n=new Date(e),r=n.getFullYear()===t.getFullYear();return n.toLocaleDateString("fr-FR",{day:"numeric",month:"short",...r?{}:{year:"numeric"}})}function GT(e,t=new Date){if(t.getTime()-eIu(e.expiresAtMs)),[s,l]=g.useState(!1);g.useEffect(()=>{i(Iu(e.expiresAtMs));const c=setInterval(()=>i(Iu(e.expiresAtMs)),1e3);return()=>clearInterval(c)},[e.expiresAtMs]),g.useEffect(()=>{l(!1)},[e.code]),g.useEffect(()=>{if(!s)return;const c=setTimeout(()=>l(!1),2e3);return()=>clearTimeout(c)},[s]);const o=r===null;return a.jsx(we,{"data-testid":"pairing-code-panel",className:"flex flex-col gap-3",children:o?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-muted",children:"Ce code a expiré."}),a.jsx("div",{children:a.jsx(M,{size:"sm",onClick:t,children:"Générer un nouveau code"})})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-muted",children:"Saisissez ce code sur le nouvel appareil."}),a.jsx("p",{"data-testid":"pairing-code-value","aria-label":e.code,className:"flex gap-3 font-mono text-2xl font-semibold tracking-[0.2em] text-content sm:text-3xl",children:XT(e.code).map((c,u)=>a.jsx("span",{"aria-hidden":"true",children:c},u))}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void QT(e.code).then(c=>l(c)),children:s?"Copié":"Copier"}),a.jsx("span",{className:"text-xs text-faint","data-testid":"pairing-code-countdown",children:r}),a.jsx(M,{size:"sm",variant:"ghost",className:"ml-auto",onClick:n,children:"Fermer"})]})]})})}function wx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:i=!1,onConfirm:s,onCancel:l}){const o=g.useRef(null);return g.useEffect(()=>{o.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.floatingWindow},onClick:l,children:a.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"text-sm text-muted",children:t}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{ref:o,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),a.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:i,onClick:()=>void s(),children:n})]})]})})}const gp=40,jw="Cet appareil",ZT=[[/\bEdg(?:e|A|iOS)?\//,"Edge"],[/\bOPR\/|\bOpera\//,"Opera"],[/\bFirefox\/|\bFxiOS\//,"Firefox"],[/\bChrome\/|\bCriOS\//,"Chrome"],[/\bSafari\//,"Safari"]],eL=[[/\bWindows\b/,"Windows"],[/\bMac OS X\b|\bMacintosh\b/,"Mac"],[/\bCrOS\b/,"ChromeOS"],[/\bLinux\b|\bX11\b/,"Linux"]];function tL(e){const t=e??"";if(/\biPhone\b/.test(t))return"iPhone";if(/\biPad\b/.test(t))return"iPad";if(/\bAndroid\b/.test(t))return"Android";const n=ZT.find(([i])=>i.test(t))?.[1],r=eL.find(([i])=>i.test(t))?.[1];return n&&r?`${n} sur ${r}`:n??r??jw}function Sx(e){return Array.from(e.trim()).slice(0,gp).join("")}function nL(){return typeof navigator>"u"||!navigator.userAgent?jw:tL(navigator.userAgent)}function Nw({onSessionEnded:e}){const t=qT(),[n,r]=g.useState(null),[i,s]=g.useState(!1),[l,o]=g.useState(null);g.useEffect(()=>{t.sessionEnded&&e?.()},[t.sessionEnded,e]);const c=t.devices;return a.jsxs("section",{"data-testid":"devices-screen",className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Appareils"}),a.jsx("p",{className:"text-sm text-muted",children:"Les appareils autorisés à accéder à cette instance IdeA."})]}),a.jsx(M,{onClick:()=>void t.generateCode(),loading:t.generating,children:"Appairer"})]}),t.code&&a.jsx(JT,{code:t.code,onRegenerate:()=>void t.generateCode(),onDismiss:t.dismissCode}),t.error&&a.jsx(we,{className:"border-danger/40",children:a.jsx("p",{role:"alert",className:"text-sm text-danger",children:t.error})}),c===null?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Re,{size:12})," Chargement des appareils…"]}):c.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun appareil appairé."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"device-list",children:c.map(u=>a.jsx(rL,{device:u,fresh:t.freshDeviceIds.includes(u.deviceId),renaming:l===u.deviceId,onStartRename:()=>o(u.deviceId),onCancelRename:()=>o(null),onRename:async h=>{await t.rename(u.deviceId,h),o(null)},onRevoke:()=>r(u)},u.deviceId))}),c!==null&&c.length>0&&a.jsx("div",{className:"pt-1",children:a.jsx(M,{variant:"ghost",size:"sm",onClick:()=>s(!0),children:"Révoquer tous les appareils"})}),n&&a.jsx(wx,{title:"Révoquer cet appareil ?",body:n.isCurrentDevice?"Il devra être appairé à nouveau pour accéder à IdeA. Vous serez déconnecté immédiatement.":"Il devra être appairé à nouveau pour accéder à IdeA.",confirmLabel:"Révoquer",busy:t.busy,onConfirm:async()=>{const u=n;r(null),await t.revoke(u)},onCancel:()=>r(null)}),i&&a.jsx(wx,{title:"Révoquer tous les appareils ?",body:"Tous les appareils, y compris celui-ci, devront être appairés à nouveau. Vous serez déconnecté immédiatement.",confirmLabel:"Tout révoquer",danger:!0,busy:t.busy,onConfirm:async()=>{s(!1),await t.revokeAll()},onCancel:()=>s(!1)})]})}function rL({device:e,fresh:t,renaming:n,onStartRename:r,onCancelRename:i,onRename:s,onRevoke:l}){return a.jsx("li",{"data-testid":"device-row","data-fresh":t||void 0,className:q("py-3 transition-colors first:pt-0 last:pb-0",t&&"bg-success/10"),children:n?a.jsx(iL,{device:e,onSubmit:s,onCancel:i}):a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),e.isCurrentDevice&&a.jsx("span",{className:"shrink-0 rounded-full bg-primary/15 px-2 py-0.5 text-[0.65rem] font-medium text-primary",children:"Cet appareil"})]}),a.jsx("span",{className:"text-xs text-muted",children:GT(e.lastSeenAtMs)}),a.jsx("span",{className:"text-[0.7rem] text-faint",children:YT(e.pairedAtMs)})]}),a.jsx(sL,{deviceName:e.name,onRename:r,onRevoke:l})]})})}function iL({device:e,onSubmit:t,onCancel:n}){const[r,i]=g.useState(e.name),s=r.trim();return a.jsxs("form",{className:"flex flex-col gap-2",onSubmit:l=>{l.preventDefault(),s.length>0&&t(s)},children:[a.jsx(qt,{label:"Nom de l'appareil",hideLabel:!0,children:({id:l})=>a.jsx(ce,{id:l,value:r,autoFocus:!0,maxLength:gp,onChange:o=>i(o.target.value),onKeyDown:o=>{o.key==="Escape"&&n()}})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{type:"submit",size:"sm",disabled:s.length===0,children:"Renommer"}),a.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Annuler"})]})]})}function sL({deviceName:e,onRename:t,onRevoke:n}){const[r,i]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const s=()=>i(!1);return window.addEventListener("click",s),()=>window.removeEventListener("click",s)},[r]),a.jsxs("div",{className:"relative shrink-0",onClick:s=>s.stopPropagation(),children:[a.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":r,"aria-label":`Actions pour ${e}`,onClick:()=>i(s=>!s),className:"rounded-md px-2 py-1 text-sm text-muted transition-colors hover:bg-raised hover:text-content",children:"⋯"}),r&&a.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-10 mt-1 flex min-w-36 flex-col rounded-md border border-border bg-raised py-1 shadow-lg",children:[a.jsx("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),t()},className:"px-3 py-1.5 text-left text-sm text-content transition-colors hover:bg-canvas",children:"Renommer"}),a.jsx("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),n()},className:"px-3 py-1.5 text-left text-sm text-danger transition-colors hover:bg-canvas",children:"Révoquer"})]})]})}const lL=250;function Vs(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function aL(){const{desktopServer:e}=he(),[t,n]=g.useState(null),[r,i]=g.useState({state:"stopped"}),[s,l]=g.useState([]),[o,c]=g.useState(),[u,h]=g.useState([]),[d,f]=g.useState(null),[p,m]=g.useState(null),[x,w]=g.useState(!1),[v,_]=g.useState(!1),y=g.useRef(0);g.useEffect(()=>{let P=!0;return(async()=>{try{const[I,O]=await Promise.all([e.getExposureSettings(),e.status()]);if(!P)return;n(I),i(O)}catch(I){P&&m(Vs(I))}})(),()=>{P=!1}},[e]),g.useEffect(()=>{let P=!0;return(async()=>{try{const I=await e.previewExposure({mode:"localOnly",autoStart:!1,port:0,trustedProxies:[]});P&&l(I.candidateLanAddresses)}catch{}})(),()=>{P=!1}},[e]),g.useEffect(()=>{let P,I=!1;return e.onStatusChanged(i).then(O=>{I?O():P=O}),()=>{I=!0,P?.()}},[e]),g.useEffect(()=>{if(!t)return;const P=++y.current,I=setTimeout(()=>{e.previewExposure(t).then(O=>{P===y.current&&(c(O.upstreamUrl),h(O.warnings),f(null))},O=>{P===y.current&&(c(void 0),h([]),f(Vs(O)))})},lL);return()=>clearTimeout(I)},[e,t]);const b=g.useCallback(P=>{m(null),n(I=>I&&{...I,...P})},[]),C=g.useCallback(P=>{b(P==="localOnly"?{mode:P,publicOrigin:void 0,lanBindAddress:void 0,trustedProxies:[]}:P==="remoteProxyLocal"?{mode:P,lanBindAddress:void 0,trustedProxies:[]}:{mode:P})},[b]),k=g.useCallback(P=>b({publicOrigin:P.trim()||void 0}),[b]),N=g.useCallback(P=>b({lanBindAddress:P||void 0}),[b]),R=g.useCallback(P=>b({trustedProxies:P.split(/[\s,]+/).map(I=>I.trim()).filter(Boolean)}),[b]),L=g.useCallback(P=>b({port:P}),[b]),S=g.useCallback(async P=>{if(!t)return;const I={...t,autoStart:P};_(!0),m(null);try{await e.saveExposureSettings(I),n(I)}catch(O){m(Vs(O))}finally{_(!1)}},[e,t]),T=g.useCallback(async()=>{if(t){w(!0),m(null);try{await e.saveExposureSettings(t),i(await e.start())}catch(P){m(Vs(P))}finally{w(!1)}}},[e,t]),D=g.useCallback(async()=>{w(!0),m(null);try{i(await e.stop())}catch(P){m(Vs(P))}finally{w(!1)}},[e]);return{ready:t!==null,settings:t,status:r,candidateLanAddresses:s,upstreamUrl:o,warnings:u,validationError:d,actionError:p,busy:x,autoStartBusy:v,setMode:C,setPublicOrigin:k,setLanBindAddress:N,setTrustedProxies:R,setPort:L,setAutoStart:S,start:T,stop:D}}const oL=[{mode:"localOnly",title:"Cet ordinateur uniquement",description:"Pour utiliser IdeA uniquement sur cet ordinateur. Les appareils distants ne peuvent pas se connecter."},{mode:"remoteProxyLocal",title:"Accès distant, proxy sur cet ordinateur",description:"À utiliser quand le proxy HTTPS tourne sur la même machine qu'IdeA Desktop."},{mode:"remoteProxyOtherMachine",title:"Accès distant, proxy sur une autre machine",description:"À utiliser quand le proxy HTTPS tourne sur une autre machine. IdeA n'acceptera que le trafic provenant de ce proxy."}],cL={stopped:"Arrêté",starting:"Démarrage…",running:"En cours d'exécution",stopping:"Arrêt…",failed:"Échec"};function uL({value:e,label:t}){const[n,r]=g.useState(!1),i=typeof navigator<"u"&&!!navigator.clipboard;return a.jsx(M,{size:"sm",variant:"ghost","aria-label":t,disabled:!i,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),window.setTimeout(()=>r(!1),1500)},()=>r(!1))},children:n?"Copié":"Copier"})}function dL({value:e,copyLabel:t}){return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("code",{className:"flex-1 truncate rounded-md border border-border bg-raised px-2 py-1.5 font-mono text-xs text-content",children:e}),a.jsx(uL,{value:e,label:t})]})}function hL(){const e=aL(),t=g.useRef(null);if(!e.ready||!e.settings)return a.jsx(we,{"aria-label":"deployment settings",title:"Déploiement",children:a.jsx("p",{className:"text-sm text-muted",children:"Chargement…"})});const{settings:n,status:r}=e,i=r.state==="running",s=n.mode!=="localOnly",l=n.mode==="remoteProxyOtherMachine",o=r.state==="starting"||r.state==="stopping";return a.jsxs("div",{"aria-label":"deployment settings",className:"flex flex-col gap-4",children:[a.jsx(we,{title:"Serveur",actions:i||r.state==="stopping"?a.jsx(M,{size:"sm",onClick:()=>void e.stop(),disabled:e.busy||o,children:"Arrêter"}):a.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy||o,children:"Démarrer"}),children:a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{"aria-hidden":!0,className:q("size-2 rounded-full",i&&"bg-success",r.state==="failed"&&"bg-danger",(r.state==="stopped"||o)&&"bg-faint")}),a.jsx("span",{className:"text-content",children:cL[r.state]})]}),r.localUrl&&a.jsxs("p",{className:"text-xs text-muted",children:["URL locale : ",a.jsx("code",{className:"font-mono text-content",children:r.localUrl})]}),r.publicUrl&&a.jsxs("p",{className:"text-xs text-muted",children:["URL publique : ",a.jsx("code",{className:"font-mono text-content",children:r.publicUrl})]}),r.state==="failed"&&r.error&&(r.error.code==="PORT_IN_USE"?a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsxs("p",{role:"alert",className:"text-sm text-danger",children:["Le serveur n'a pas démarré automatiquement. ",r.error.message]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>{t.current?.scrollIntoView?.({behavior:"smooth",block:"center"}),t.current?.focus()},children:"Modifier le port"}),a.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy,children:"Réessayer"})]})]}):a.jsx("p",{role:"alert",className:"text-sm text-danger",children:r.error.message})),e.actionError&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.actionError}),a.jsxs("label",{className:"flex cursor-pointer items-start gap-2 pt-2",children:[a.jsx("input",{type:"checkbox",className:"mt-0.5","aria-label":"Démarrer le serveur au lancement d'IdeA",checked:n.autoStart,disabled:e.autoStartBusy,onChange:c=>void e.setAutoStart(c.target.checked)}),a.jsxs("span",{className:"flex flex-col gap-0.5",children:[a.jsx("span",{className:"text-sm text-content",children:"Démarrer le serveur au lancement d'IdeA"}),a.jsx("span",{className:"text-xs text-muted",children:"IdeA utilisera les réglages réseau enregistrés ci-dessous au prochain démarrage de l'application desktop."})]})]})]})}),a.jsx(we,{title:"Accès réseau",children:a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx("div",{role:"radiogroup","aria-label":"mode d'accès réseau",className:"flex flex-col gap-2",children:oL.map(c=>{const u=n.mode===c.mode;return a.jsxs("label",{className:q("flex cursor-pointer gap-3 rounded-lg border p-3 transition-colors",u?"border-border-strong bg-raised":"border-border hover:bg-raised"),children:[a.jsx("input",{type:"radio",name:"exposure-mode",className:"mt-1",checked:u,onChange:()=>e.setMode(c.mode)}),a.jsxs("span",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),a.jsx("span",{className:"text-xs text-muted",children:c.description})]})]},c.mode)})}),a.jsx(qt,{label:"Port",children:({id:c})=>a.jsx(ce,{ref:t,id:c,type:"number",value:String(n.port),onChange:u=>e.setPort(Number(u.target.value))})}),s&&a.jsx(qt,{label:"Origine publique",hint:"Exemple : https://idea.example.com",children:({id:c,describedBy:u})=>a.jsx(ce,{id:c,"aria-describedby":u,placeholder:"https://idea.example.com",value:n.publicOrigin??"",onChange:h=>e.setPublicOrigin(h.target.value)})}),l&&a.jsxs(a.Fragment,{children:[a.jsx(qt,{label:"Adresse LAN d'écoute",hint:"L'adresse de cette machine à laquelle le proxy se connectera.",children:({id:c,describedBy:u})=>e.candidateLanAddresses.length>0?a.jsxs("select",{id:c,"aria-describedby":u,className:"rounded-md border border-border bg-surface px-2 py-1.5 text-sm text-content",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value),children:[a.jsx("option",{value:"",children:"Sélectionner une adresse…"}),e.candidateLanAddresses.map(h=>a.jsx("option",{value:h,children:h},h))]}):a.jsx(ce,{id:c,"aria-describedby":u,placeholder:"192.168.1.42",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value)})}),a.jsx(qt,{label:"IP/CIDR du proxy autorisé",hint:"Ce n'est pas l'adresse d'écoute d'IdeA. C'est la machine autorisée à contacter IdeA.",children:({id:c,describedBy:u})=>a.jsx(ce,{id:c,"aria-describedby":u,placeholder:"203.0.113.7 or 203.0.113.0/24",value:n.trustedProxies.join(", "),onChange:h=>e.setTrustedProxies(h.target.value)})}),a.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Si votre proxy n'est pas sur cet ordinateur, choisissez ce mode. Sinon, le proxy peut expirer sans erreur IdeA."})]}),e.warnings.map(c=>a.jsx("p",{className:"text-xs text-warning",children:c.message},c.code)),e.validationError&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.validationError})]})}),s&&a.jsx(we,{title:"Configuration du proxy",children:a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("p",{className:"text-xs text-muted",children:"Faites pointer votre proxy inverse HTTPS vers cet upstream."}),e.upstreamUrl?a.jsx(dL,{value:e.upstreamUrl,copyLabel:"copier l'URL upstream"}):a.jsx("p",{className:"text-xs text-faint",children:"Complétez les paramètres ci-dessus pour obtenir l'URL upstream."})]})}),a.jsx(we,{title:"Appairage",children:a.jsxs("p",{className:"text-sm text-muted",children:["L'appairage est géré dans"," ",a.jsx("span",{className:"text-content",children:"Paramètres → Appareils"}),", où vous pouvez générer un code et révoquer des appareils."]})})]})}const Ew={aiProfiles:"Profils IA",deployment:"Déploiement",devices:"Appareils",plugins:"Plugins"},Pw=["aiProfiles","deployment","devices","plugins"];function fL({section:e,onSectionChange:t,onClose:n}){return a.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[a.jsxs("nav",{"aria-label":"settings sections",className:"flex w-52 shrink-0 flex-col gap-1 border-r border-border p-3",children:[Pw.map(r=>{const i=r===e;return a.jsx("button",{type:"button","aria-current":i?"page":void 0,onClick:()=>t(r),className:q("rounded-md px-3 py-2 text-left text-sm transition-colors",i?"bg-raised font-semibold text-content":"text-muted hover:bg-raised hover:text-content"),children:Ew[r]},r)}),a.jsx("div",{className:"mt-auto pt-2",children:a.jsx(M,{size:"sm",variant:"ghost",className:"w-full",onClick:n,children:"Fermer les paramètres"})})]}),a.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:a.jsx("div",{className:"w-full max-w-2xl",children:e==="aiProfiles"?a.jsx(kw,{}):e==="deployment"?a.jsx(hL,{}):e==="plugins"?a.jsx(uA,{}):a.jsx(Nw,{})})})]})}function Ks(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const pL={branches:[],current:null},kx=20;function mL(e){const{git:t}=he(),[n,r]=g.useState([]),[i,s]=g.useState(pL),[l,o]=g.useState([]),[c,u]=g.useState(!1),[h,d]=g.useState(null),f=g.useCallback(async()=>{u(!0),d(null);try{const[v,_,y]=await Promise.all([t.status(e),t.branches(e),t.log(e,kx)]);r(v),s(_),o(y)}catch(v){d(Ks(v))}finally{u(!1)}},[t,e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async v=>{u(!0),d(null);try{await t.stage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!0}:y))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async v=>{u(!0),d(null);try{await t.unstage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!1}:y))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]),x=g.useCallback(async v=>{u(!0),d(null);try{const _=await t.commit(e,v);r(y=>y.filter(b=>!b.staged)),o(y=>[_,...y].slice(0,kx))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]),w=g.useCallback(async v=>{u(!0),d(null);try{await t.checkout(e,v),s(_=>({branches:_.branches.includes(v)?_.branches:[..._.branches,v],current:v}))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]);return{files:n,branches:i,log:l,busy:c,error:h,refresh:f,stage:p,unstage:m,commit:x,checkout:w}}function Cx(e){const t={children:[]};for(const n of e){const r=n.path.split("/").filter(Boolean);let i=t;r.forEach((s,l)=>{const o=l===r.length-1,c=r.slice(0,l+1).join("/");let u=i.children.find(h=>h.name===s&&h.isDir===!o);u||(u={name:s,path:c,isDir:!o,staged:n.staged,children:[]},i.children.push(u)),i=u})}return Aw(t),t.children}function Aw(e){e.children.sort((t,n)=>t.isDir!==n.isDir?t.isDir?-1:1:t.name.localeCompare(n.name)),e.children.forEach(Aw)}function zh({nodes:e,depth:t,action:n,onAction:r,busy:i}){return a.jsx("ul",{className:"flex flex-col gap-0.5",children:e.map(s=>s.isDir?a.jsxs("li",{children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-xs text-muted",style:{paddingLeft:`${t*14+8}px`},children:[a.jsx("span",{"aria-hidden":!0,className:"text-faint",children:"▸"}),a.jsx("span",{className:"truncate",children:s.name})]}),a.jsx(zh,{nodes:s.children,depth:t+1,action:n,onAction:r,busy:i})]},s.path):a.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:bg-raised",style:{paddingLeft:`${t*14+8}px`},children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx("span",{"aria-hidden":!0,className:q("size-1.5 shrink-0 rounded-full",n==="unstage"?"bg-success":"bg-warning")}),a.jsx("code",{className:"min-w-0 truncate text-xs text-content",children:s.name})]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`${n} ${s.path}`,disabled:i,onClick:()=>r(s.path),className:"shrink-0 text-muted hover:text-content",children:n==="unstage"?"Unstage":"Stage"})]},s.path))})}function Tw({projectId:e}){const t=mL(e),[n,r]=g.useState(""),[i,s]=g.useState(""),l=t.files.filter(f=>f.staged),o=t.files.filter(f=>!f.staged),c=n.trim().length>0&&l.length>0&&!t.busy;async function u(f){f.preventDefault(),c&&(await t.commit(n.trim()),r(""))}async function h(f){await t.checkout(f)}async function d(f){f.preventDefault();const p=i.trim();!p||t.busy||(await t.checkout(p),s(""))}return a.jsxs(we,{title:"Git",className:"flex flex-col gap-0",children:[t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("section",{"aria-label":"Changes",className:"border-b border-border p-4",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Changes"}),t.busy&&a.jsx(Re,{size:12})]}),t.files.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No changes."}):a.jsxs("div",{className:"flex flex-col gap-3",children:[l.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Staged"}),a.jsx(zh,{nodes:Cx(l),depth:0,action:"unstage",onAction:f=>void t.unstage(f),busy:t.busy})]}),o.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Unstaged"}),a.jsx(zh,{nodes:Cx(o),depth:0,action:"stage",onAction:f=>void t.stage(f),busy:t.busy})]})]})]}),a.jsxs("section",{"aria-label":"Commit",className:"border-b border-border p-4",children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Commit"}),a.jsxs("form",{onSubmit:u,className:"flex flex-col gap-2",children:[a.jsx(ce,{"aria-label":"commit message",placeholder:"Commit message",value:n,onChange:f=>r(f.target.value)}),a.jsx(M,{type:"submit",variant:"primary",disabled:!c,loading:t.busy,className:"self-end",children:"Commit"})]})]}),a.jsxs("section",{"aria-label":"Branches",className:"border-b border-border p-4",children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Branches"}),a.jsxs("p",{className:"mb-2 text-sm text-content",children:["Current:"," ",a.jsx("span",{className:"font-medium",children:t.branches.current??"(none)"})]}),t.branches.branches.length>0&&a.jsx("ul",{className:"mb-3 flex flex-col gap-0.5",children:t.branches.branches.map(f=>{const p=f===t.branches.current;return a.jsxs("li",{className:q("flex items-center justify-between gap-2 rounded-md px-2 py-1",p&&"bg-raised"),children:[a.jsx("span",{className:q("text-sm",p?"font-semibold text-primary":"text-content"),children:f}),!p&&a.jsx(M,{size:"sm",variant:"ghost","aria-label":`checkout ${f}`,disabled:t.busy,onClick:()=>void h(f),className:"shrink-0 text-muted hover:text-content",children:"Checkout"})]},f)})}),a.jsxs("form",{onSubmit:d,className:"flex items-center gap-2",children:[a.jsx(ce,{"aria-label":"new branch name",placeholder:"New branch",value:i,onChange:f=>s(f.target.value),className:"flex-1"}),a.jsx(M,{type:"submit",variant:"ghost",disabled:!i.trim()||t.busy,children:"Create & checkout"})]})]}),a.jsxs("section",{"aria-label":"Log",className:"p-4",children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Log"}),t.log.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No commits yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.log.map(f=>a.jsxs("li",{className:"flex items-baseline gap-2 py-1.5",children:[a.jsx("code",{className:"shrink-0 text-xs text-faint",children:f.hash.slice(0,7)}),a.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:f.summary})]},f.hash))})]})]})}const jx=["#4f9cf9","#a78bfa","#34d399","#fbbf24","#f87171","#38bdf8","#fb923c","#c084fc","#f472b6","#2dd4bf"];function Gs(e){return jx[e%jx.length]}function gL(e){return e.indexOf(null)}function Nx(e,t){const n=gL(e);return n!==-1?(e[n]=t,n):(e.push(t),e.length-1)}function xL(e){const t=[],n=[];for(const r of e){const{hash:i,parents:s}=r,l=t.slice();let o=t.indexOf(i);o===-1&&(o=Nx(t,i));for(let f=0;f{o(!0),u(null);try{const d=await t.graph(e,vL);r(d),s(xL(d))}catch(d){u(d&&typeof d=="object"&&"message"in d?String(d.message):String(d))}finally{o(!1)}},[t,e]);return g.useEffect(()=>{h()},[h]),{commits:n,rows:i,busy:l,error:c,refresh:h}}const ec=16,po=36,Ex=4.5,Fh=e=>e*ec+ec/2;function Px(e,t,n){const r=Fh(e.fromLane),i=Fh(e.toLane);if(r===i)return`M ${r} ${t} L ${i} ${n}`;const s=(t+n)/2;return`M ${r} ${t} C ${r} ${s} ${i} ${s} ${i} ${n}`}function yL({row:e,laneCount:t}){const n=t*ec+ec/2,r=po/2,i=Fh(e.lane);return a.jsxs("svg",{width:n,height:po,"aria-hidden":!0,className:"shrink-0 overflow-visible",children:[e.incoming.map((s,l)=>a.jsx("path",{d:Px(s,0,r),fill:"none",stroke:s.color,strokeWidth:2},`in-${l}`)),e.outgoing.map((s,l)=>a.jsx("path",{d:Px(s,r,po),fill:"none",stroke:s.color,strokeWidth:2},`out-${l}`)),a.jsx("circle",{cx:i,cy:r,r:Ex+1.5,className:"fill-canvas"}),a.jsx("circle",{cx:i,cy:r,r:Ex,fill:e.color,stroke:"var(--color-canvas)",strokeWidth:1})]})}function bL(e){const t=Math.floor(Date.now()/1e3)-e;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:t<31536e3?`${Math.floor(t/2592e3)}mo ago`:`${Math.floor(t/31536e3)}y ago`}function wL({commit:e,onClose:t}){const n=r=>r.startsWith("tag:");return a.jsxs("aside",{"aria-label":"commit detail",className:"flex w-80 shrink-0 flex-col gap-3 overflow-y-auto border-l border-border bg-surface p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e.summary}),a.jsx("button",{type:"button","aria-label":"close commit detail",onClick:t,className:"shrink-0 text-muted hover:text-content",children:"×"})]}),a.jsxs("dl",{className:"flex flex-col gap-2 text-xs",children:[a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Hash"}),a.jsx("dd",{children:a.jsx("code",{className:"text-content break-all",children:e.hash})})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Author"}),a.jsx("dd",{className:"text-content",children:e.author})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Date"}),a.jsx("dd",{className:"text-content",children:new Date(e.timestamp*1e3).toLocaleString()})]}),e.parents.length>0&&a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Parents"}),a.jsx("dd",{className:"flex flex-col gap-0.5",children:e.parents.map(r=>a.jsx("code",{className:"text-content",children:r.slice(0,8)},r))})]}),e.refs.length>0&&a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Refs"}),a.jsx("dd",{className:"flex flex-wrap gap-1",children:e.refs.map(r=>a.jsx("span",{className:q("rounded px-1 py-0.5 text-xs font-medium text-base",n(r)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:r},r))})]})]})]})}function SL({projectId:e}){const t=_L(e),[n,r]=g.useState(null),i=n!=null?t.commits.find(o=>o.hash===n)??null:null,s=t.rows.reduce((o,c)=>Math.max(o,c.laneCount),1),l=o=>o.startsWith("tag:");return a.jsxs("div",{className:"flex flex-1 overflow-hidden","aria-label":"git graph",children:[a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:"Git Graph"}),t.busy&&a.jsx(Re,{size:14}),a.jsx("button",{type:"button","aria-label":"refresh git graph",onClick:()=>void t.refresh(),disabled:t.busy,className:"ml-auto text-xs text-muted hover:text-content disabled:opacity-40",children:"Refresh"})]}),t.error&&a.jsx("p",{role:"alert",className:"mx-3 mt-2 shrink-0 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger",children:t.error}),a.jsxs("div",{className:"flex-1 overflow-y-auto",role:"list","aria-label":"commits",children:[t.rows.length===0&&!t.busy&&a.jsx("p",{className:"p-4 text-sm text-muted",children:"No commits found."}),t.rows.map(o=>{const c=o.commit.hash===n;return a.jsxs("div",{role:"listitem","aria-label":`commit ${o.commit.hash.slice(0,8)}: ${o.commit.summary}`,onClick:()=>r(c?null:o.commit.hash),className:q("flex cursor-pointer items-center gap-2 border-b border-border/50 px-2 hover:bg-raised",c&&"bg-raised"),style:{height:po},children:[a.jsx(yL,{row:o,laneCount:s}),o.commit.refs.length>0&&a.jsx("div",{className:"flex shrink-0 flex-wrap gap-1",children:o.commit.refs.map(u=>a.jsx("span",{className:q("rounded px-1 py-0.5 text-xs font-medium",l(u)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:u},u))}),a.jsx("code",{className:"shrink-0 text-xs text-faint",children:o.commit.hash.slice(0,8)}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:o.commit.summary}),a.jsx("span",{className:"shrink-0 text-xs text-muted",children:o.commit.author}),a.jsx("span",{className:"shrink-0 text-xs text-faint",children:bL(o.commit.timestamp)})]},o.commit.hash)})]})]}),i&&a.jsx(wL,{commit:i,onClose:()=>r(null)})]})}function Ra(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function kL(){const{project:e}=he(),[t,n]=g.useState([]),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useCallback(async()=>{h(!0),c(null);try{n(await e.listProjects())}catch(v){c(Ra(v))}finally{h(!1)}},[e]);g.useEffect(()=>{d()},[d]);const f=g.useCallback(v=>{i(_=>_.some(y=>y.id===v.id)?_:[..._,v]),l(v.id)},[]),p=g.useCallback(async v=>{h(!0),c(null);try{const _=await e.openProject(v);f(_)}catch(_){c(Ra(_))}finally{h(!1)}},[e,f]),m=g.useCallback(async(v,_)=>{h(!0),c(null);try{const y=await e.createProject(v,_);n(b=>[...b,y]),f(y)}catch(y){c(Ra(y))}finally{h(!1)}},[e,f]),x=g.useCallback(async v=>{c(null);try{await e.closeProject(v)}catch(_){c(Ra(_))}i(_=>{const y=_.filter(b=>b.id!==v);return l(b=>b===v?y.at(-1)?.id??null:b),y})},[e]),w=g.useCallback(v=>{l(v)},[]);return{projects:t,openTabs:r,activeTabId:s,error:o,busy:u,refresh:d,createProject:m,openProject:p,closeTab:x,activateTab:w}}function CL({items:e,activeTabId:t,onSelect:n,onClose:r,projectsPanelOpen:i,onOpenProjectsPanel:s,className:l}){return a.jsxs("div",{className:q("flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",l),children:[e.length===0?a.jsx("p",{className:"px-2 text-sm text-muted",children:"No open tabs."}):a.jsx(FP,{items:e,value:t,onSelect:n,onClose:r}),a.jsx(M,{size:"sm",variant:"secondary",onClick:s,"aria-label":"open projects panel","aria-pressed":i,title:"Ajouter un projet",className:q("shrink-0",i&&"ring-1 ring-border-strong"),children:"+"})]})}function jL(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const NL=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EL=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,PL={};function Ax(e,t){return(PL.jsx?EL:NL).test(e)}const AL=/[ \t\n\f\r]/g;function TL(e){return typeof e=="object"?e.type==="text"?Tx(e.value):!1:Tx(e)}function Tx(e){return e.replace(AL,"")===""}class ta{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}ta.prototype.normal={};ta.prototype.property={};ta.prototype.space=void 0;function Lw(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new ta(n,r,t)}function $h(e){return e.toLowerCase()}class Qt{constructor(t,n){this.attribute=n,this.property=t}}Qt.prototype.attribute="";Qt.prototype.booleanish=!1;Qt.prototype.boolean=!1;Qt.prototype.commaOrSpaceSeparated=!1;Qt.prototype.commaSeparated=!1;Qt.prototype.defined=!1;Qt.prototype.mustUseProperty=!1;Qt.prototype.number=!1;Qt.prototype.overloadedBoolean=!1;Qt.prototype.property="";Qt.prototype.spaceSeparated=!1;Qt.prototype.space=void 0;let LL=0;const me=Ei(),tt=Ei(),Wh=Ei(),Z=Ei(),Le=Ei(),gi=Ei(),tn=Ei();function Ei(){return 2**++LL}const Hh=Object.freeze(Object.defineProperty({__proto__:null,boolean:me,booleanish:tt,commaOrSpaceSeparated:tn,commaSeparated:gi,number:Z,overloadedBoolean:Wh,spaceSeparated:Le},Symbol.toStringTag,{value:"Module"})),Ou=Object.keys(Hh);class xp extends Qt{constructor(t,n,r,i){let s=-1;if(super(t,n),Lx(this,"space",i),typeof r=="number")for(;++s4&&n.slice(0,4)==="data"&&OL.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(Dx,FL);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!Dx.test(s)){let l=s.replace(IL,zL);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}i=xp}return new i(r,t)}function zL(e){return"-"+e.toLowerCase()}function FL(e){return e.charAt(1).toUpperCase()}const $L=Lw([Dw,DL,Iw,Ow,Bw],"html"),vp=Lw([Dw,RL,Iw,Ow,Bw],"svg");function WL(e){return e.join(" ").trim()}var _p={},Rx=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,HL=/\n/g,UL=/^\s*/,qL=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,VL=/^:\s*/,KL=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,GL=/^[;\s]*/,YL=/^\s+|\s+$/g,XL=` -`,Mx="/",Ix="*",ai="",QL="comment",JL="declaration";function ZL(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function i(m){var x=m.match(HL);x&&(n+=x.length);var w=m.lastIndexOf(XL);r=~w?m.length-w:r+m.length}function s(){var m={line:n,column:r};return function(x){return x.position=new l(m),u(),x}}function l(m){this.start=m,this.end={line:n,column:r},this.source=t.source}l.prototype.content=e;function o(m){var x=new Error(t.source+":"+n+":"+r+": "+m);if(x.reason=m,x.filename=t.source,x.line=n,x.column=r,x.source=e,!t.silent)throw x}function c(m){var x=m.exec(e);if(x){var w=x[0];return i(w),e=e.slice(w.length),x}}function u(){c(UL)}function h(m){var x;for(m=m||[];x=d();)x!==!1&&m.push(x);return m}function d(){var m=s();if(!(Mx!=e.charAt(0)||Ix!=e.charAt(1))){for(var x=2;ai!=e.charAt(x)&&(Ix!=e.charAt(x)||Mx!=e.charAt(x+1));)++x;if(x+=2,ai===e.charAt(x-1))return o("End of comment missing");var w=e.slice(2,x-2);return r+=2,i(w),e=e.slice(x),r+=2,m({type:QL,comment:w})}}function f(){var m=s(),x=c(qL);if(x){if(d(),!c(VL))return o("property missing ':'");var w=c(KL),v=m({type:JL,property:Ox(x[0].replace(Rx,ai)),value:w?Ox(w[0].replace(Rx,ai)):ai});return c(GL),v}}function p(){var m=[];h(m);for(var x;x=f();)x!==!1&&(m.push(x),h(m));return m}return u(),p()}function Ox(e){return e?e.replace(YL,ai):ai}var eD=ZL,tD=vo&&vo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_p,"__esModule",{value:!0});_p.default=rD;const nD=tD(eD);function rD(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,nD.default)(e),i=typeof t=="function";return r.forEach(s=>{if(s.type!=="declaration")return;const{property:l,value:o}=s;i?t(l,o,s):o&&(n=n||{},n[l]=o)}),n}var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.camelCase=void 0;var iD=/^--[a-zA-Z0-9_-]+$/,sD=/-([a-z])/g,lD=/^[^-]+$/,aD=/^-(webkit|moz|ms|o|khtml)-/,oD=/^-(ms)-/,cD=function(e){return!e||lD.test(e)||iD.test(e)},uD=function(e,t){return t.toUpperCase()},Bx=function(e,t){return"".concat(t,"-")},dD=function(e,t){return t===void 0&&(t={}),cD(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(oD,Bx):e=e.replace(aD,Bx),e.replace(sD,uD))};Cc.camelCase=dD;var hD=vo&&vo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},fD=hD(_p),pD=Cc;function Uh(e,t){var n={};return!e||typeof e!="string"||(0,fD.default)(e,function(r,i){r&&i&&(n[(0,pD.camelCase)(r,t)]=i)}),n}Uh.default=Uh;var mD=Uh;const gD=ef(mD),zw=Fw("end"),yp=Fw("start");function Fw(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function xD(e){const t=yp(e),n=zw(e);if(t&&n)return{start:t,end:n}}function _l(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?zx(e.position):"start"in e||"end"in e?zx(e):"line"in e||"column"in e?qh(e):""}function qh(e){return Fx(e&&e.line)+":"+Fx(e&&e.column)}function zx(e){return qh(e&&e.start)+"-"+qh(e&&e.end)}function Fx(e){return e&&typeof e=="number"?e:1}class Lt extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",s={},l=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s={...n}),typeof t=="string"?i=t:!s.cause&&t&&(l=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?s.ruleId=r:(s.source=r.slice(0,c),s.ruleId=r.slice(c+1))}if(!s.place&&s.ancestors&&s.ancestors){const c=s.ancestors[s.ancestors.length-1];c&&(s.place=c.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=_l(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=l&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Lt.prototype.file="";Lt.prototype.name="";Lt.prototype.reason="";Lt.prototype.message="";Lt.prototype.stack="";Lt.prototype.column=void 0;Lt.prototype.line=void 0;Lt.prototype.ancestors=void 0;Lt.prototype.cause=void 0;Lt.prototype.fatal=void 0;Lt.prototype.place=void 0;Lt.prototype.ruleId=void 0;Lt.prototype.source=void 0;const bp={}.hasOwnProperty,vD=new Map,_D=/[A-Z]/g,yD=new Set(["table","tbody","thead","tfoot","tr"]),bD=new Set(["td","th"]),$w="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function wD(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=AD(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=PD(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?vp:$L,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=Ww(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function Ww(e,t,n){if(t.type==="element")return SD(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return kD(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return jD(e,t,n);if(t.type==="mdxjsEsm")return CD(e,t);if(t.type==="root")return ND(e,t,n);if(t.type==="text")return ED(e,t)}function SD(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=vp,e.schema=i),e.ancestors.push(t);const s=Uw(e,t.tagName,!1),l=TD(e,t);let o=Sp(e,t);return yD.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!TL(c):!0})),Hw(e,l,s,t),wp(l,o),e.ancestors.pop(),e.schema=r,e.create(t,s,l,n)}function kD(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Hl(e,t.position)}function CD(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Hl(e,t.position)}function jD(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=vp,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:Uw(e,t.name,!0),l=LD(e,t),o=Sp(e,t);return Hw(e,l,s,t),wp(l,o),e.ancestors.pop(),e.schema=r,e.create(t,s,l,n)}function ND(e,t,n){const r={};return wp(r,Sp(e,t)),e.create(t,e.Fragment,r,n)}function ED(e,t){return t.value}function Hw(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function wp(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function PD(e,t,n){return r;function r(i,s,l,o){const u=Array.isArray(l.children)?n:t;return o?u(s,l,o):u(s,l)}}function AD(e,t){return n;function n(r,i,s,l){const o=Array.isArray(s.children),c=yp(r);return t(i,s,l,o,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function TD(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&bp.call(t.properties,i)){const s=DD(e,i,t.properties[i]);if(s){const[l,o]=s;e.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&bD.has(t.tagName)?r=o:n[l]=o}}if(r){const s=n.style||(n.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function LD(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const s=r.data.estree.body[0];s.type;const l=s.expression;l.type;const o=l.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else Hl(e,t.position);else{const i=r.name;let s;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,s=e.evaluater.evaluateExpression(o.expression)}else Hl(e,t.position);else s=r.value===null?!0:r.value;n[i]=s}return n}function Sp(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:vD;for(;++ri?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),e.splice(...l);else for(n&&e.splice(t,n);s0?(an(e,e.length,0,t),e):t}const Hx={}.hasOwnProperty;function Vw(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Dn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const It=Yr(/[A-Za-z]/),At=Yr(/[\dA-Za-z]/),WD=Yr(/[#-'*+\--9=?A-Z^-~]/);function tc(e){return e!==null&&(e<32||e===127)}const Vh=Yr(/\d/),HD=Yr(/[\dA-Fa-f]/),UD=Yr(/[!-/:-@[-`{-~]/);function ue(e){return e!==null&&e<-2}function De(e){return e!==null&&(e<0||e===32)}function ye(e){return e===-2||e===-1||e===32}const jc=Yr(/\p{P}|\p{S}/u),ki=Yr(/\s/);function Yr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Cs(e){const t=[];let n=-1,r=0,i=0;for(;++n55295&&s<57344){const o=e.charCodeAt(n+1);s<56320&&o>56319&&o<57344?(l=String.fromCharCode(s,o),i=1):l="�"}else l=String.fromCharCode(s);l&&(t.push(e.slice(r,n),encodeURIComponent(l)),r=n+i+1,l=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function ke(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let s=0;return l;function l(c){return ye(c)?(e.enter(n),o(c)):t(c)}function o(c){return ye(c)&&s++l))return;const N=t.events.length;let R=N,L,S;for(;R--;)if(t.events[R][0]==="exit"&&t.events[R][1].type==="chunkFlow"){if(L){S=t.events[R][1].end;break}L=!0}for(v(r),k=N;ky;){const C=n[b];t.containerState=C[1],C[0].exit.call(t,e)}n.length=y}function _(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function YD(e,t,n){return ke(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function xs(e){if(e===null||De(e)||ki(e))return 1;if(jc(e))return 2}function Nc(e,t,n){const r=[];let i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},f={...e[n][1].start};qx(d,-c),qx(f,c),l={type:c>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},s={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?"strong":"emphasis",start:{...l.start},end:{...o.end}},e[r][1].end={...l.start},e[n][1].start={...o.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=vn(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=vn(u,[["enter",i,t],["enter",l,t],["exit",l,t],["enter",s,t]]),u=vn(u,Nc(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=vn(u,[["exit",s,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(h=2,u=vn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):h=0,an(e,r-1,n-r+3,u),n=r+u.length-h-2;break}}for(n=-1;++n0&&ye(k)?ke(e,_,"linePrefix",s+1)(k):_(k)}function _(k){return k===null||ue(k)?e.check(Vx,x,b)(k):(e.enter("codeFlowValue"),y(k))}function y(k){return k===null||ue(k)?(e.exit("codeFlowValue"),_(k)):(e.consume(k),y)}function b(k){return e.exit("codeFenced"),t(k)}function C(k,N,R){let L=0;return S;function S(O){return k.enter("lineEnding"),k.consume(O),k.exit("lineEnding"),T}function T(O){return k.enter("codeFencedFence"),ye(O)?ke(k,D,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):D(O)}function D(O){return O===o?(k.enter("codeFencedFenceSequence"),P(O)):R(O)}function P(O){return O===o?(L++,k.consume(O),P):L>=l?(k.exit("codeFencedFenceSequence"),ye(O)?ke(k,I,"whitespace")(O):I(O)):R(O)}function I(O){return O===null||ue(O)?(k.exit("codeFencedFence"),N(O)):R(O)}}}function aR(e,t,n){const r=this;return i;function i(l){return l===null?n(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s)}function s(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const zu={name:"codeIndented",tokenize:cR},oR={partial:!0,tokenize:uR};function cR(e,t,n){const r=this;return i;function i(u){return e.enter("codeIndented"),ke(e,s,"linePrefix",5)(u)}function s(u){const h=r.events[r.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(u):n(u)}function l(u){return u===null?c(u):ue(u)?e.attempt(oR,l,c)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||ue(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),o)}function c(u){return e.exit("codeIndented"),t(u)}}function uR(e,t,n){const r=this;return i;function i(l){return r.parser.lazy[r.now().line]?n(l):ue(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i):ke(e,s,"linePrefix",5)(l)}function s(l){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(l):ue(l)?i(l):n(l)}}const dR={name:"codeText",previous:fR,resolve:hR,tokenize:pR};function hR(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&Ys(this.left,r),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Ys(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Ys(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):e.interrupt(r.parser.constructs.flow,n,t)(l)}}function Jw(e,t,n,r,i,s,l,o,c){const u=c||Number.POSITIVE_INFINITY;let h=0;return d;function d(v){return v===60?(e.enter(r),e.enter(i),e.enter(s),e.consume(v),e.exit(s),f):v===null||v===32||v===41||tc(v)?n(v):(e.enter(r),e.enter(l),e.enter(o),e.enter("chunkString",{contentType:"string"}),x(v))}function f(v){return v===62?(e.enter(s),e.consume(v),e.exit(s),e.exit(i),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(o),f(v)):v===null||v===60||ue(v)?n(v):(e.consume(v),v===92?m:p)}function m(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function x(v){return!h&&(v===null||v===41||De(v))?(e.exit("chunkString"),e.exit(o),e.exit(l),e.exit(r),t(v)):h999||p===null||p===91||p===93&&!c||p===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(e.exit(s),e.enter(i),e.consume(p),e.exit(i),e.exit(r),t):ue(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||ue(p)||o++>999?(e.exit("chunkString"),h(p)):(e.consume(p),c||(c=!ye(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),o++,d):d(p)}}function eS(e,t,n,r,i,s){let l;return o;function o(f){return f===34||f===39||f===40?(e.enter(r),e.enter(i),e.consume(f),e.exit(i),l=f===40?41:f,c):n(f)}function c(f){return f===l?(e.enter(i),e.consume(f),e.exit(i),e.exit(r),t):(e.enter(s),u(f))}function u(f){return f===l?(e.exit(s),c(l)):f===null?n(f):ue(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),ke(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===l||f===null||ue(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:h)}function d(f){return f===l||f===92?(e.consume(f),h):h(f)}}function yl(e,t){let n;return r;function r(i){return ue(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):ye(i)?ke(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const wR={name:"definition",tokenize:kR},SR={partial:!0,tokenize:CR};function kR(e,t,n){const r=this;let i;return s;function s(p){return e.enter("definition"),l(p)}function l(p){return Zw.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return i=Dn(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),c):n(p)}function c(p){return De(p)?yl(e,u)(p):u(p)}function u(p){return Jw(e,h,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(SR,d,d)(p)}function d(p){return ye(p)?ke(e,f,"whitespace")(p):f(p)}function f(p){return p===null||ue(p)?(e.exit("definition"),r.parser.defined.push(i),t(p)):n(p)}}function CR(e,t,n){return r;function r(o){return De(o)?yl(e,i)(o):n(o)}function i(o){return eS(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return ye(o)?ke(e,l,"whitespace")(o):l(o)}function l(o){return o===null||ue(o)?t(o):n(o)}}const jR={name:"hardBreakEscape",tokenize:NR};function NR(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return ue(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const ER={name:"headingAtx",resolve:PR,tokenize:AR};function PR(e,t){let n=e.length-2,r=3,i,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},an(e,r,n-r+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function AR(e,t,n){let r=0;return i;function i(h){return e.enter("atxHeading"),s(h)}function s(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&r++<6?(e.consume(h),l):h===null||De(h)?(e.exit("atxHeadingSequence"),o(h)):n(h)}function o(h){return h===35?(e.enter("atxHeadingSequence"),c(h)):h===null||ue(h)?(e.exit("atxHeading"),t(h)):ye(h)?ke(e,o,"whitespace")(h):(e.enter("atxHeadingText"),u(h))}function c(h){return h===35?(e.consume(h),c):(e.exit("atxHeadingSequence"),o(h))}function u(h){return h===null||h===35||De(h)?(e.exit("atxHeadingText"),o(h)):(e.consume(h),u)}}const TR=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Gx=["pre","script","style","textarea"],LR={concrete:!0,name:"htmlFlow",resolveTo:MR,tokenize:IR},DR={partial:!0,tokenize:BR},RR={partial:!0,tokenize:OR};function MR(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function IR(e,t,n){const r=this;let i,s,l,o,c;return u;function u(A){return h(A)}function h(A){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(A),d}function d(A){return A===33?(e.consume(A),f):A===47?(e.consume(A),s=!0,x):A===63?(e.consume(A),i=3,r.interrupt?t:j):It(A)?(e.consume(A),l=String.fromCharCode(A),w):n(A)}function f(A){return A===45?(e.consume(A),i=2,p):A===91?(e.consume(A),i=5,o=0,m):It(A)?(e.consume(A),i=4,r.interrupt?t:j):n(A)}function p(A){return A===45?(e.consume(A),r.interrupt?t:j):n(A)}function m(A){const ie="CDATA[";return A===ie.charCodeAt(o++)?(e.consume(A),o===ie.length?r.interrupt?t:D:m):n(A)}function x(A){return It(A)?(e.consume(A),l=String.fromCharCode(A),w):n(A)}function w(A){if(A===null||A===47||A===62||De(A)){const ie=A===47,ee=l.toLowerCase();return!ie&&!s&&Gx.includes(ee)?(i=1,r.interrupt?t(A):D(A)):TR.includes(l.toLowerCase())?(i=6,ie?(e.consume(A),v):r.interrupt?t(A):D(A)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(A):s?_(A):y(A))}return A===45||At(A)?(e.consume(A),l+=String.fromCharCode(A),w):n(A)}function v(A){return A===62?(e.consume(A),r.interrupt?t:D):n(A)}function _(A){return ye(A)?(e.consume(A),_):S(A)}function y(A){return A===47?(e.consume(A),S):A===58||A===95||It(A)?(e.consume(A),b):ye(A)?(e.consume(A),y):S(A)}function b(A){return A===45||A===46||A===58||A===95||At(A)?(e.consume(A),b):C(A)}function C(A){return A===61?(e.consume(A),k):ye(A)?(e.consume(A),C):y(A)}function k(A){return A===null||A===60||A===61||A===62||A===96?n(A):A===34||A===39?(e.consume(A),c=A,N):ye(A)?(e.consume(A),k):R(A)}function N(A){return A===c?(e.consume(A),c=null,L):A===null||ue(A)?n(A):(e.consume(A),N)}function R(A){return A===null||A===34||A===39||A===47||A===60||A===61||A===62||A===96||De(A)?C(A):(e.consume(A),R)}function L(A){return A===47||A===62||ye(A)?y(A):n(A)}function S(A){return A===62?(e.consume(A),T):n(A)}function T(A){return A===null||ue(A)?D(A):ye(A)?(e.consume(A),T):n(A)}function D(A){return A===45&&i===2?(e.consume(A),U):A===60&&i===1?(e.consume(A),G):A===62&&i===4?(e.consume(A),re):A===63&&i===3?(e.consume(A),j):A===93&&i===5?(e.consume(A),z):ue(A)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(DR,V,P)(A)):A===null||ue(A)?(e.exit("htmlFlowData"),P(A)):(e.consume(A),D)}function P(A){return e.check(RR,I,V)(A)}function I(A){return e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),O}function O(A){return A===null||ue(A)?P(A):(e.enter("htmlFlowData"),D(A))}function U(A){return A===45?(e.consume(A),j):D(A)}function G(A){return A===47?(e.consume(A),l="",E):D(A)}function E(A){if(A===62){const ie=l.toLowerCase();return Gx.includes(ie)?(e.consume(A),re):D(A)}return It(A)&&l.length<8?(e.consume(A),l+=String.fromCharCode(A),E):D(A)}function z(A){return A===93?(e.consume(A),j):D(A)}function j(A){return A===62?(e.consume(A),re):A===45&&i===2?(e.consume(A),j):D(A)}function re(A){return A===null||ue(A)?(e.exit("htmlFlowData"),V(A)):(e.consume(A),re)}function V(A){return e.exit("htmlFlow"),t(A)}}function OR(e,t,n){const r=this;return i;function i(l){return ue(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s):n(l)}function s(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function BR(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(na,t,n)}}const zR={name:"htmlText",tokenize:FR};function FR(e,t,n){const r=this;let i,s,l;return o;function o(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),c}function c(j){return j===33?(e.consume(j),u):j===47?(e.consume(j),C):j===63?(e.consume(j),y):It(j)?(e.consume(j),R):n(j)}function u(j){return j===45?(e.consume(j),h):j===91?(e.consume(j),s=0,m):It(j)?(e.consume(j),_):n(j)}function h(j){return j===45?(e.consume(j),p):n(j)}function d(j){return j===null?n(j):j===45?(e.consume(j),f):ue(j)?(l=d,G(j)):(e.consume(j),d)}function f(j){return j===45?(e.consume(j),p):d(j)}function p(j){return j===62?U(j):j===45?f(j):d(j)}function m(j){const re="CDATA[";return j===re.charCodeAt(s++)?(e.consume(j),s===re.length?x:m):n(j)}function x(j){return j===null?n(j):j===93?(e.consume(j),w):ue(j)?(l=x,G(j)):(e.consume(j),x)}function w(j){return j===93?(e.consume(j),v):x(j)}function v(j){return j===62?U(j):j===93?(e.consume(j),v):x(j)}function _(j){return j===null||j===62?U(j):ue(j)?(l=_,G(j)):(e.consume(j),_)}function y(j){return j===null?n(j):j===63?(e.consume(j),b):ue(j)?(l=y,G(j)):(e.consume(j),y)}function b(j){return j===62?U(j):y(j)}function C(j){return It(j)?(e.consume(j),k):n(j)}function k(j){return j===45||At(j)?(e.consume(j),k):N(j)}function N(j){return ue(j)?(l=N,G(j)):ye(j)?(e.consume(j),N):U(j)}function R(j){return j===45||At(j)?(e.consume(j),R):j===47||j===62||De(j)?L(j):n(j)}function L(j){return j===47?(e.consume(j),U):j===58||j===95||It(j)?(e.consume(j),S):ue(j)?(l=L,G(j)):ye(j)?(e.consume(j),L):U(j)}function S(j){return j===45||j===46||j===58||j===95||At(j)?(e.consume(j),S):T(j)}function T(j){return j===61?(e.consume(j),D):ue(j)?(l=T,G(j)):ye(j)?(e.consume(j),T):L(j)}function D(j){return j===null||j===60||j===61||j===62||j===96?n(j):j===34||j===39?(e.consume(j),i=j,P):ue(j)?(l=D,G(j)):ye(j)?(e.consume(j),D):(e.consume(j),I)}function P(j){return j===i?(e.consume(j),i=void 0,O):j===null?n(j):ue(j)?(l=P,G(j)):(e.consume(j),P)}function I(j){return j===null||j===34||j===39||j===60||j===61||j===96?n(j):j===47||j===62||De(j)?L(j):(e.consume(j),I)}function O(j){return j===47||j===62||De(j)?L(j):n(j)}function U(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):n(j)}function G(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),E}function E(j){return ye(j)?ke(e,z,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):z(j)}function z(j){return e.enter("htmlTextData"),l(j)}}const jp={name:"labelEnd",resolveAll:UR,resolveTo:qR,tokenize:VR},$R={tokenize:KR},WR={tokenize:GR},HR={tokenize:YR};function UR(e){let t=-1;const n=[];for(;++t=3&&(u===null||ue(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===i?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),ye(u)?ke(e,o,"whitespace")(u):o(u))}}const Ht={continuation:{tokenize:sM},exit:aM,name:"list",tokenize:iM},nM={partial:!0,tokenize:oM},rM={partial:!0,tokenize:lM};function iM(e,t,n){const r=this,i=r.events[r.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,l=0;return o;function o(p){const m=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Vh(p)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(mo,n,u)(p):u(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(p)}return n(p)}function c(p){return Vh(p)&&++l<10?(e.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(na,r.interrupt?n:h,e.attempt(nM,f,d))}function h(p){return r.containerState.initialBlankLine=!0,s++,f(p)}function d(p){return ye(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function sM(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(na,i,s);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,ke(e,t,"listItemIndent",r.containerState.size+1)(o)}function s(o){return r.containerState.furtherBlankLines||!ye(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(rM,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,ke(e,e.attempt(Ht,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function lM(e,t,n){const r=this;return ke(e,i,"listItemIndent",r.containerState.size+1);function i(s){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(s):n(s)}}function aM(e){e.exit(this.containerState.type)}function oM(e,t,n){const r=this;return ke(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const l=r.events[r.events.length-1];return!ye(s)&&l&&l[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const Yx={name:"setextUnderline",resolveTo:cM,tokenize:uM};function cM(e,t){let n=e.length,r,i,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const l={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",l,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end={...e[s][1].end}):e[r][1]=l,e.push(["exit",l,t]),e}function uM(e,t,n){const r=this;let i;return s;function s(u){let h=r.events.length,d;for(;h--;)if(r.events[h][1].type!=="lineEnding"&&r.events[h][1].type!=="linePrefix"&&r.events[h][1].type!=="content"){d=r.events[h][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),i=u,l(u)):n(u)}function l(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),ye(u)?ke(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||ue(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const dM={tokenize:hM};function hM(e){const t=this,n=e.attempt(na,r,e.attempt(this.parser.constructs.flowInitial,i,ke(e,e.attempt(this.parser.constructs.flow,i,e.attempt(xR,i)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const fM={resolveAll:nS()},pM=tS("string"),mM=tS("text");function tS(e){return{resolveAll:nS(e==="text"?gM:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],s=n.attempt(i,l,o);return l;function l(h){return u(h)?s(h):o(h)}function o(h){if(h===null){n.consume(h);return}return n.enter("data"),n.consume(h),c}function c(h){return u(h)?(n.exit("data"),s(h)):(n.consume(h),c)}function u(h){if(h===null)return!0;const d=i[h];let f=-1;if(d)for(;++f-1){const o=l[0];typeof o=="string"?l[0]=o.slice(r):l.shift()}s>0&&l.push(e[i].slice(0,s))}return l}function PM(e,t){let n=-1;const r=[];let i;for(;++n0){const Cn=pe.tokenStack[pe.tokenStack.length-1];(Cn[1]||Qx).call(pe,void 0,Cn[0])}for(te.position={start:Sr(H.length>0?H[0][1].start:{line:1,column:1,offset:0}),end:Sr(H.length>0?H[H.length-2][1].end:{line:1,column:1,offset:0})},Te=-1;++Te0&&(r.className=["language-"+i[0]]);let s={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function HM(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function UM(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qM(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),i=Cs(r.toLowerCase()),s=e.footnoteOrder.indexOf(r);let l,o=e.footnoteCounts.get(r);o===void 0?(o=0,e.footnoteOrder.push(r),l=e.footnoteOrder.length):l=s+1,o+=1,e.footnoteCounts.set(r,o);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function VM(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function KM(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function sS(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});const l=i[i.length-1];return l&&l.type==="text"?l.value+=r:i.push({type:"text",value:r}),i}function GM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return sS(e,t);const i={src:Cs(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function YM(e,t){const n={src:Cs(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function XM(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function QM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return sS(e,t);const i={href:Cs(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function JM(e,t){const n={href:Cs(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ZM(e,t,n){const r=e.all(t),i=n?eI(n):lS(t),s={},l=[];if(typeof t.checked=="boolean"){const h=r[0];let d;h&&h.type==="element"&&h.tagName==="p"?d=h:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o1}function tI(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},o=yp(t.children[1]),c=zw(t.children[t.children.length-1]);o&&c&&(l.position={start:o,end:c}),i.push(l)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function lI(e,t,n){const r=n?n.children:void 0,s=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,o=l?l.length:t.children.length;let c=-1;const u=[];for(;++c0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return s.push(ev(t.slice(i),i>0,!1)),s.join("")}function ev(e,t,n){let r=0,i=e.length;if(t){let s=e.codePointAt(r);for(;s===Jx||s===Zx;)r++,s=e.codePointAt(r)}if(n){let s=e.codePointAt(i-1);for(;s===Jx||s===Zx;)i--,s=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function cI(e,t){const n={type:"text",value:oI(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function uI(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const dI={blockquote:FM,break:$M,code:WM,delete:HM,emphasis:UM,footnoteReference:qM,heading:VM,html:KM,imageReference:GM,image:YM,inlineCode:XM,linkReference:QM,link:JM,listItem:ZM,list:tI,paragraph:nI,root:rI,strong:iI,table:sI,tableCell:aI,tableRow:lI,text:cI,thematicBreak:uI,toml:Ma,yaml:Ma,definition:Ma,footnoteDefinition:Ma};function Ma(){}const aS=-1,Ec=0,bl=1,nc=2,Np=3,Ep=4,Pp=5,Ap=6,oS=7,cS=8,hI=typeof self=="object"?self:globalThis,tv=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new hI[e](t)},fI=(e,t)=>{const n=(i,s)=>(e.set(s,i),i),r=i=>{if(e.has(i))return e.get(i);const[s,l]=t[i];switch(s){case Ec:case aS:return n(l,i);case bl:{const o=n([],i);for(const c of l)o.push(r(c));return o}case nc:{const o=n({},i);for(const[c,u]of l)o[r(c)]=r(u);return o}case Np:return n(new Date(l),i);case Ep:{const{source:o,flags:c}=l;return n(new RegExp(o,c),i)}case Pp:{const o=n(new Map,i);for(const[c,u]of l)o.set(r(c),r(u));return o}case Ap:{const o=n(new Set,i);for(const c of l)o.add(r(c));return o}case oS:{const{name:o,message:c}=l;return n(tv(o,c),i)}case cS:return n(BigInt(l),i);case"BigInt":return n(Object(BigInt(l)),i);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:o}=new Uint8Array(l);return n(new DataView(o),l)}}return n(tv(s,l),i)};return r},nv=e=>fI(new Map,e)(0),Oi="",{toString:pI}={},{keys:mI}=Object,Xs=e=>{const t=typeof e;if(t!=="object"||!e)return[Ec,t];const n=pI.call(e).slice(8,-1);switch(n){case"Array":return[bl,Oi];case"Object":return[nc,Oi];case"Date":return[Np,Oi];case"RegExp":return[Ep,Oi];case"Map":return[Pp,Oi];case"Set":return[Ap,Oi];case"DataView":return[bl,n]}return n.includes("Array")?[bl,n]:n.includes("Error")?[oS,n]:[nc,n]},Ia=([e,t])=>e===Ec&&(t==="function"||t==="symbol"),gI=(e,t,n,r)=>{const i=(l,o)=>{const c=r.push(l)-1;return n.set(o,c),c},s=l=>{if(n.has(l))return n.get(l);let[o,c]=Xs(l);switch(o){case Ec:{let h=l;switch(c){case"bigint":o=cS,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);h=null;break;case"undefined":return i([aS],l)}return i([o,h],l)}case bl:{if(c){let f=l;return c==="DataView"?f=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(f=new Uint8Array(l)),i([c,[...f]],l)}const h=[],d=i([o,h],l);for(const f of l)h.push(s(f));return d}case nc:{if(c)switch(c){case"BigInt":return i([c,l.toString()],l);case"Boolean":case"Number":case"String":return i([c,l.valueOf()],l)}if(t&&"toJSON"in l)return s(l.toJSON());const h=[],d=i([o,h],l);for(const f of mI(l))(e||!Ia(Xs(l[f])))&&h.push([s(f),s(l[f])]);return d}case Np:return i([o,l.toISOString()],l);case Ep:{const{source:h,flags:d}=l;return i([o,{source:h,flags:d}],l)}case Pp:{const h=[],d=i([o,h],l);for(const[f,p]of l)(e||!(Ia(Xs(f))||Ia(Xs(p))))&&h.push([s(f),s(p)]);return d}case Ap:{const h=[],d=i([o,h],l);for(const f of l)(e||!Ia(Xs(f)))&&h.push(s(f));return d}}const{message:u}=l;return i([o,{name:c,message:u}],l)};return s},rv=(e,{json:t,lossy:n}={})=>{const r=[];return gI(!(t||n),!!t,new Map,r)(e),r},rc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?nv(rv(e,t)):structuredClone(e):(e,t)=>nv(rv(e,t));function xI(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function vI(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function _I(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||xI,r=e.options.footnoteBackLabel||vI,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&m.push({type:"text",value:" "});let _=typeof n=="string"?n:n(c,p);typeof _=="string"&&(_={type:"text",value:_}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const w=h[h.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const _=w.children[w.children.length-1];_&&_.type==="text"?_.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...m)}else h.push(...m);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(h,!0)};e.patch(u,v),o.push(v)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:{...rc(l),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:` -`}]}}const Pc=function(e){if(e==null)return SI;if(typeof e=="function")return Ac(e);if(typeof e=="object")return Array.isArray(e)?yI(e):bI(e);if(typeof e=="string")return wI(e);throw new Error("Expected function, string, or object as test")};function yI(e){const t=[];let n=-1;for(;++n":""))+")"})}return f;function f(){let p=uS,m,x,w;if((!t||s(c,u,h[h.length-1]||void 0))&&(p=NI(n(c,h)),p[0]===Gh))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==jI)for(x=(r?v.children.length:-1)+l,w=h.concat(v);x>-1&&x0&&n.push({type:"text",value:` -`}),n}function iv(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function sv(e,t){const n=PI(e,t),r=n.one(e,void 0),i=_I(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&s.children.push({type:"text",value:` -`},i),s}function RI(e,t){return e&&"run"in e?async function(n,r){const i=sv(n,{file:r,...t});await e.run(i,r)}:function(n,r){return sv(n,{file:r,...e||t})}}function lv(e){if(e)throw e}var go=Object.prototype.hasOwnProperty,hS=Object.prototype.toString,av=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,cv=function(t){return typeof Array.isArray=="function"?Array.isArray(t):hS.call(t)==="[object Array]"},uv=function(t){if(!t||hS.call(t)!=="[object Object]")return!1;var n=go.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&go.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var i;for(i in t);return typeof i>"u"||go.call(t,i)},dv=function(t,n){av&&n.name==="__proto__"?av(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},hv=function(t,n){if(n==="__proto__")if(go.call(t,n)){if(ov)return ov(t,n).value}else return;return t[n]},MI=function e(){var t,n,r,i,s,l,o=arguments[0],c=1,u=arguments.length,h=!1;for(typeof o=="boolean"&&(h=o,o=arguments[1]||{},c=2),(o==null||typeof o!="object"&&typeof o!="function")&&(o={});cl.length;let c;o&&l.push(i);try{c=e.apply(this,l)}catch(u){const h=u;if(o&&n)throw h;return i(h)}o||(c&&c.then&&typeof c.then=="function"?c.then(s,i):c instanceof Error?i(c):s(c))}function i(l,...o){n||(n=!0,t(l,...o))}function s(l){i(null,l)}}const $n={basename:BI,dirname:zI,extname:FI,join:$I,sep:"/"};function BI(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ra(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,o=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else l<0&&(s=!0,l=i+1),o>-1&&(e.codePointAt(i)===t.codePointAt(o--)?o<0&&(r=i):(o=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function zI(e){if(ra(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function FI(e){ra(e);let t=e.length,n=-1,r=0,i=-1,s=0,l;for(;t--;){const o=e.codePointAt(t);if(o===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),o===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function $I(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function HI(e,t){let n="",r=0,i=-1,s=0,l=-1,o,c;for(;++l<=e.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),i=l,s=0;continue}}else if(n.length>0){n="",r=0,i=l,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,l):n=e.slice(i+1,l),r=l-i-1;i=l,s=0}else o===46&&s>-1?s++:s=-1}return n}function ra(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const UI={cwd:qI};function qI(){return"/"}function Qh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function VI(e){if(typeof e=="string")e=new URL(e);else if(!Qh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return KI(e)}function KI(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[p,...m]=h;const x=r[f][1];Xh(x)&&Xh(p)&&(p=$u(!0,x,p)),r[f]=[u,p,...m]}}}}const QI=new Lp().freeze();function qu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Vu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ku(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function pv(e){if(!Xh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function mv(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Oa(e){return JI(e)?e:new fS(e)}function JI(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ZI(e){return typeof e=="string"||e3(e)}function e3(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const t3="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",gv=[],xv={allowDangerousHtml:!0},n3=/^(https?|ircs?|mailto|xmpp)$/i,r3=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function pS(e){const t=i3(e),n=s3(e);return l3(t.runSync(t.parse(n),n),e)}function i3(e){const t=e.rehypePlugins||gv,n=e.remarkPlugins||gv,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...xv}:xv;return QI().use(zM).use(n).use(RI,r).use(t)}function s3(e){const t=e.children||"",n=new fS;return typeof t=="string"&&(n.value=t),n}function l3(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||a3;for(const h of r3)Object.hasOwn(t,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+t3+h.id,void 0);return Tp(e,u),wD(e,{Fragment:a.Fragment,components:i,ignoreInvalidStyle:!0,jsx:a.jsx,jsxs:a.jsxs,passKeys:!0,passNode:!0});function u(h,d,f){if(h.type==="raw"&&f&&typeof d=="number")return l?f.children.splice(d,1):f.children[d]={type:"text",value:h.value},d;if(h.type==="element"){let p;for(p in Bu)if(Object.hasOwn(Bu,p)&&Object.hasOwn(h.properties,p)){const m=h.properties[p],x=Bu[p];(x===null||x.includes(h.tagName))&&(h.properties[p]=c(String(m||""),p,h))}}if(h.type==="element"){let p=n?!n.includes(h.tagName):s?s.includes(h.tagName):!1;if(!p&&r&&typeof d=="number"&&(p=!r(h,d,f)),p&&f&&typeof d=="number")return o&&h.children?f.children.splice(d,1,...h.children):f.children.splice(d,1),d}}}function a3(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||n3.test(e.slice(0,t))?e:""}function vv(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function o3(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function c3(e,t,n){const i=Pc((n||{}).ignore||[]),s=u3(t);let l=-1;for(;++l0?{type:"text",value:k}:void 0),k===!1?f.lastIndex=b+1:(m!==b&&_.push({type:"text",value:u.value.slice(m,b)}),Array.isArray(k)?_.push(...k):k&&_.push(k),m=b+y[0].length,v=!0),!f.global)break;y=f.exec(u.value)}return v?(m?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=vv(e,"(");let s=vv(e,")");for(;r!==-1&&i>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}function mS(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||ki(n)||jc(n))&&(!t||n!==47)}gS.peek=D3;function C3(){this.buffer()}function j3(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function N3(){this.buffer()}function E3(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function P3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Dn(this.sliceSerialize(e)).toLowerCase(),n.label=t}function A3(e){this.exit(e)}function T3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Dn(this.sliceSerialize(e)).toLowerCase(),n.label=t}function L3(e){this.exit(e)}function D3(){return"["}function gS(e,t,n,r){const i=n.createTracker(r);let s=i.move("[^");const l=n.enter("footnoteReference"),o=n.enter("reference");return s+=i.move(n.safe(n.associationId(e),{after:"]",before:s})),o(),l(),s+=i.move("]"),s}function R3(){return{enter:{gfmFootnoteCallString:C3,gfmFootnoteCall:j3,gfmFootnoteDefinitionLabelString:N3,gfmFootnoteDefinition:E3},exit:{gfmFootnoteCallString:P3,gfmFootnoteCall:A3,gfmFootnoteDefinitionLabelString:T3,gfmFootnoteDefinition:L3}}}function M3(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:gS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,s,l){const o=s.createTracker(l);let c=o.move("[^");const u=s.enter("footnoteDefinition"),h=s.enter("label");return c+=o.move(s.safe(s.associationId(r),{before:c,after:"]"})),h(),c+=o.move("]:"),r.children&&r.children.length>0&&(o.shift(4),c+=o.move((t?` -`:" ")+s.indentLines(s.containerFlow(r,o.current()),t?xS:I3))),u(),c}}function I3(e,t,n){return t===0?e:xS(e,t,n)}function xS(e,t,n){return(n?"":" ")+e}const O3=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];vS.peek=W3;function B3(){return{canContainEols:["delete"],enter:{strikethrough:F3},exit:{strikethrough:$3}}}function z3(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:O3}],handlers:{delete:vS}}}function F3(e){this.enter({type:"delete",children:[]},e)}function $3(e){this.exit(e)}function vS(e,t,n,r){const i=n.createTracker(r),s=n.enter("strikethrough");let l=i.move("~~");return l+=n.containerPhrasing(e,{...i.current(),before:l,after:"~"}),l+=i.move("~~"),s(),l}function W3(){return"~"}function H3(e){return e.length}function U3(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||H3,s=[],l=[],o=[],c=[];let u=0,h=-1;for(;++hu&&(u=e[h].length);++vc[v])&&(c[v]=y)}x.push(_)}l[h]=x,o[h]=w}let d=-1;if(typeof r=="object"&&"length"in r)for(;++dc[d]&&(c[d]=_),p[d]=_),f[d]=y}l.splice(1,0,f),o.splice(1,0,p),h=-1;const m=[];for(;++h "),s.shift(2);const l=n.indentLines(n.containerFlow(e,s.current()),K3);return i(),l}function K3(e,t,n){return">"+(n?"":" ")+e}function G3(e,t){return yv(e,t.inConstruct,!0)&&!yv(e,t.notInConstruct,!1)}function yv(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++rl&&(l=s):s=1,i=r+t.length,r=n.indexOf(t,i);return l}function X3(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Q3(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function J3(e,t,n,r){const i=Q3(n),s=e.value||"",l=i==="`"?"GraveAccent":"Tilde";if(X3(e,n)){const d=n.enter("codeIndented"),f=n.indentLines(s,Z3);return d(),f}const o=n.createTracker(r),c=i.repeat(Math.max(Y3(s,i)+1,3)),u=n.enter("codeFenced");let h=o.move(c);if(e.lang){const d=n.enter(`codeFencedLang${l}`);h+=o.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...o.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${l}`);h+=o.move(" "),h+=o.move(n.safe(e.meta,{before:h,after:` -`,encode:["`"],...o.current()})),d()}return h+=o.move(` -`),s&&(h+=o.move(s+` -`)),h+=o.move(c),u(),h}function Z3(e,t,n){return(n?"":" ")+e}function Dp(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function e5(e,t,n,r){const i=Dp(n),s=i==='"'?"Quote":"Apostrophe",l=n.enter("definition");let o=n.enter("label");const c=n.createTracker(r);let u=c.move("[");return u+=c.move(n.safe(n.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(o=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":` -`,...c.current()}))),o(),e.title&&(o=n.enter(`title${s}`),u+=c.move(" "+i),u+=c.move(n.safe(e.title,{before:u,after:i,...c.current()})),u+=c.move(i),o()),l(),u}function t5(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ul(e){return"&#x"+e.toString(16).toUpperCase()+";"}function ic(e,t,n){const r=xs(e),i=xs(t);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}_S.peek=n5;function _S(e,t,n,r){const i=t5(n),s=n.enter("emphasis"),l=n.createTracker(r),o=l.move(i);let c=l.move(n.containerPhrasing(e,{after:i,before:o,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,i);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(i);return s(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},o+c+p}function n5(e,t,n){return n.options.emphasis||"*"}function r5(e,t){let n=!1;return Tp(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Gh}),!!((!e.depth||e.depth<3)&&kp(e)&&(t.options.setext||n))}function i5(e,t,n,r){const i=Math.max(Math.min(6,e.depth||1),1),s=n.createTracker(r);if(r5(e,n)){const h=n.enter("headingSetext"),d=n.enter("phrasing"),f=n.containerPhrasing(e,{...s.current(),before:` -`,after:` -`});return d(),h(),f+` -`+(i===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(` -`))+1))}const l="#".repeat(i),o=n.enter("headingAtx"),c=n.enter("phrasing");s.move(l+" ");let u=n.containerPhrasing(e,{before:"# ",after:` -`,...s.current()});return/^[\t ]/.test(u)&&(u=Ul(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,n.options.closeAtx&&(u+=" "+l),c(),o(),u}yS.peek=s5;function yS(e){return e.value||""}function s5(){return"<"}bS.peek=l5;function bS(e,t,n,r){const i=Dp(n),s=i==='"'?"Quote":"Apostrophe",l=n.enter("image");let o=n.enter("label");const c=n.createTracker(r);let u=c.move("![");return u+=c.move(n.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(o=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),o(),e.title&&(o=n.enter(`title${s}`),u+=c.move(" "+i),u+=c.move(n.safe(e.title,{before:u,after:i,...c.current()})),u+=c.move(i),o()),u+=c.move(")"),l(),u}function l5(){return"!"}wS.peek=a5;function wS(e,t,n,r){const i=e.referenceType,s=n.enter("imageReference");let l=n.enter("label");const o=n.createTracker(r);let c=o.move("![");const u=n.safe(e.alt,{before:c,after:"]",...o.current()});c+=o.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...o.current()});return l(),n.stack=h,s(),i==="full"||!u||u!==d?c+=o.move(d+"]"):i==="shortcut"?c=c.slice(0,-1):c+=o.move("]"),c}function a5(){return"!"}SS.peek=o5;function SS(e,t,n){let r=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++s\u007F]/.test(e.url))}CS.peek=c5;function CS(e,t,n,r){const i=Dp(n),s=i==='"'?"Quote":"Apostrophe",l=n.createTracker(r);let o,c;if(kS(e,n)){const h=n.stack;n.stack=[],o=n.enter("autolink");let d=l.move("<");return d+=l.move(n.containerPhrasing(e,{before:d,after:">",...l.current()})),d+=l.move(">"),o(),n.stack=h,d}o=n.enter("link"),c=n.enter("label");let u=l.move("[");return u+=l.move(n.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(c=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),c(),e.title&&(c=n.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(n.safe(e.title,{before:u,after:i,...l.current()})),u+=l.move(i),c()),u+=l.move(")"),o(),u}function c5(e,t,n){return kS(e,n)?"<":"["}jS.peek=u5;function jS(e,t,n,r){const i=e.referenceType,s=n.enter("linkReference");let l=n.enter("label");const o=n.createTracker(r);let c=o.move("[");const u=n.containerPhrasing(e,{before:c,after:"]",...o.current()});c+=o.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...o.current()});return l(),n.stack=h,s(),i==="full"||!u||u!==d?c+=o.move(d+"]"):i==="shortcut"?c=c.slice(0,-1):c+=o.move("]"),c}function u5(){return"["}function Rp(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function d5(e){const t=Rp(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function h5(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function NS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function f5(e,t,n,r){const i=n.enter("list"),s=n.bulletCurrent;let l=e.ordered?h5(n):Rp(n);const o=e.ordered?l==="."?")":".":d5(n);let c=t&&n.bulletLastUsed?l===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),NS(n)===l&&h){let d=-1;for(;++d-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let l=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(l=Math.ceil(l/4)*4);const o=n.createTracker(r);o.move(s+" ".repeat(l-s.length)),o.shift(l);const c=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,o.current()),h);return c(),u;function h(d,f,p){return f?(p?"":" ".repeat(l))+d:(p?s:s+" ".repeat(l-s.length))+d}}function g5(e,t,n,r){const i=n.enter("paragraph"),s=n.enter("phrasing"),l=n.containerPhrasing(e,r);return s(),i(),l}const x5=Pc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function v5(e,t,n,r){return(e.children.some(function(l){return x5(l)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function _5(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}ES.peek=y5;function ES(e,t,n,r){const i=_5(n),s=n.enter("strong"),l=n.createTracker(r),o=l.move(i+i);let c=l.move(n.containerPhrasing(e,{after:i,before:o,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,i);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(i+i);return s(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},o+c+p}function y5(e,t,n){return n.options.strong||"*"}function b5(e,t,n,r){return n.safe(e.value,r)}function w5(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function S5(e,t,n){const r=(NS(n)+(n.options.ruleSpaces?" ":"")).repeat(w5(n));return n.options.ruleSpaces?r.slice(0,-1):r}const PS={blockquote:V3,break:bv,code:J3,definition:e5,emphasis:_S,hardBreak:bv,heading:i5,html:yS,image:bS,imageReference:wS,inlineCode:SS,link:CS,linkReference:jS,list:f5,listItem:m5,paragraph:g5,root:v5,strong:ES,text:b5,thematicBreak:S5};function k5(){return{enter:{table:C5,tableData:wv,tableHeader:wv,tableRow:N5},exit:{codeText:E5,table:j5,tableData:Qu,tableHeader:Qu,tableRow:Qu}}}function C5(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function j5(e){this.exit(e),this.data.inTable=void 0}function N5(e){this.enter({type:"tableRow",children:[]},e)}function Qu(e){this.exit(e)}function wv(e){this.enter({type:"tableCell",children:[]},e)}function E5(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,P5));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function P5(e,t){return t==="|"?t:e}function A5(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,s=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:c,tableRow:o}};function l(p,m,x,w){return u(h(p,x,w),p.align)}function o(p,m,x,w){const v=d(p,x,w),_=u([v]);return _.slice(0,_.indexOf(` -`))}function c(p,m,x,w){const v=x.enter("tableCell"),_=x.enter("phrasing"),y=x.containerPhrasing(p,{...w,before:s,after:s});return _(),v(),y}function u(p,m){return U3(p,{align:m,alignDelimiters:r,padding:n,stringLength:i})}function h(p,m,x){const w=p.children;let v=-1;const _=[],y=m.enter("table");for(;++v0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const G5={tokenize:nO,partial:!0};function Y5(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Z5,continuation:{tokenize:eO},exit:tO}},text:{91:{name:"gfmFootnoteCall",tokenize:J5},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:X5,resolveTo:Q5}}}}function X5(e,t,n){const r=this;let i=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let l;for(;i--;){const c=r.events[i][1];if(c.type==="labelImage"){l=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return o;function o(c){if(!l||!l._balanced)return n(c);const u=Dn(r.sliceSerialize({start:l.end,end:r.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function Q5(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",l,t],["exit",l,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...o),e}function J5(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s=0,l;return o;function o(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),c}function c(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(s>999||d===93&&!l||d===null||d===91||De(d))return n(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return i.includes(Dn(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return De(d)||(l=!0),s++,e.consume(d),d===92?h:u}function h(d){return d===91||d===92||d===93?(e.consume(d),s++,u):u(d)}}function Z5(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,l=0,o;return c;function c(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):n(m)}function h(m){if(l>999||m===93&&!o||m===null||m===91||De(m))return n(m);if(m===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return s=Dn(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return De(m)||(o=!0),l++,e.consume(m),m===92?d:h}function d(m){return m===91||m===92||m===93?(e.consume(m),l++,h):h(m)}function f(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),i.includes(s)||i.push(s),ke(e,p,"gfmFootnoteDefinitionWhitespace")):n(m)}function p(m){return t(m)}}function eO(e,t,n){return e.check(na,t,e.attempt(G5,t,n))}function tO(e){e.exit("gfmFootnoteDefinition")}function nO(e,t,n){const r=this;return ke(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const l=r.events[r.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?t(s):n(s)}}function rO(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:s,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(l,o){let c=-1;for(;++c1?c(m):(l.consume(m),d++,p);if(d<2&&!n)return c(m);const w=l.exit("strikethroughSequenceTemporary"),v=xs(m);return w._open=!v||v===2&&!!x,w._close=!x||x===2&&!!v,o(m)}}}class iO{constructor(){this.map=[]}add(t,n,r){sO(this,t,n,r)}consume(t){if(this.map.sort(function(s,l){return s[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const s of i)t.push(s);i=r.pop()}this.map.length=0}}function sO(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i-1;){const I=r.events[T][1].type;if(I==="lineEnding"||I==="linePrefix")T--;else break}const D=T>-1?r.events[T][1].type:null,P=D==="tableHead"||D==="tableRow"?k:c;return P===k&&r.parser.lazy[r.now().line]?n(S):P(S)}function c(S){return e.enter("tableHead"),e.enter("tableRow"),u(S)}function u(S){return S===124||(l=!0,s+=1),h(S)}function h(S){return S===null?n(S):ue(S)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),p):n(S):ye(S)?ke(e,h,"whitespace")(S):(s+=1,l&&(l=!1,i+=1),S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),d(S)))}function d(S){return S===null||S===124||De(S)?(e.exit("data"),h(S)):(e.consume(S),S===92?f:d)}function f(S){return S===92||S===124?(e.consume(S),d):d(S)}function p(S){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(S):(e.enter("tableDelimiterRow"),l=!1,ye(S)?ke(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):m(S))}function m(S){return S===45||S===58?w(S):S===124?(l=!0,e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),x):C(S)}function x(S){return ye(S)?ke(e,w,"whitespace")(S):w(S)}function w(S){return S===58?(s+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),v):S===45?(s+=1,v(S)):S===null||ue(S)?b(S):C(S)}function v(S){return S===45?(e.enter("tableDelimiterFiller"),_(S)):C(S)}function _(S){return S===45?(e.consume(S),_):S===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),y):(e.exit("tableDelimiterFiller"),y(S))}function y(S){return ye(S)?ke(e,b,"whitespace")(S):b(S)}function b(S){return S===124?m(S):S===null||ue(S)?!l||i!==s?C(S):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(S)):C(S)}function C(S){return n(S)}function k(S){return e.enter("tableRow"),N(S)}function N(S){return S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),N):S===null||ue(S)?(e.exit("tableRow"),t(S)):ye(S)?ke(e,N,"whitespace")(S):(e.enter("data"),R(S))}function R(S){return S===null||S===124||De(S)?(e.exit("data"),N(S)):(e.consume(S),S===92?L:R)}function L(S){return S===92||S===124?(e.consume(S),R):R(S)}}function cO(e,t){let n=-1,r=!0,i=0,s=[0,0,0,0],l=[0,0,0,0],o=!1,c=0,u,h,d;const f=new iO;for(;++nn[2]+1){const m=n[2]+1,x=n[3]-n[2]-1;e.add(m,x,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return i!==void 0&&(s.end=Object.assign({},$i(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function kv(e,t,n,r,i){const s=[],l=$i(t.events,n);i&&(i.end=Object.assign({},l),s.push(["exit",i,t])),r.end=Object.assign({},l),s.push(["exit",r,t]),e.add(n+1,0,s)}function $i(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const uO={name:"tasklistCheck",tokenize:hO};function dO(){return{text:{91:uO}}}function hO(e,t,n){const r=this;return i;function i(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),s)}function s(c){return De(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),l):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),l):n(c)}function l(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):n(c)}function o(c){return ue(c)?t(c):ye(c)?e.check({tokenize:fO},t,n)(c):n(c)}}function fO(e,t,n){return ke(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function pO(e){return Vw([z5(),Y5(),rO(e),aO(),dO()])}const mO={};function BS(e){const t=this,n=e||mO,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),s=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),l=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(pO(n)),s.push(M5()),l.push(I5(n))}function gO({template:e,profiles:t,onSave:n,onClose:r,busy:i=!1}){const[s,l]=g.useState(e?.name??""),[o,c]=g.useState(e?.contentMd??""),[u,h]=g.useState(e?.defaultProfileId??""),[d,f]=g.useState("edit"),p=s.trim().length>0&&!i;async function m(x){x.preventDefault(),p&&await n(s.trim(),o,u)}return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"template editor",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:e?`Edit template — ${e.name}`:"New template"}),a.jsx(M,{type:"button",variant:"ghost","aria-label":"close template editor",onClick:r,disabled:i,children:"✕"})]}),a.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"te-name",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(ce,{id:"te-name","aria-label":"template name",placeholder:"My template",value:s,onChange:x=>l(x.target.value),disabled:i,className:"min-w-48"})]}),a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"te-profile",className:"text-xs font-medium text-muted",children:"Default profile"}),t.length>0?a.jsxs("select",{id:"te-profile","aria-label":"template default profile",value:u,onChange:x=>h(x.target.value),disabled:i,className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"",children:"— none —"}),t.map(x=>a.jsx("option",{value:x.id,children:x.name},x.id))]}):a.jsx(ce,{id:"te-profile","aria-label":"template default profile",placeholder:"profile-id (optional)",value:u,onChange:x=>h(x.target.value),disabled:i,className:"min-w-48"})]})]}),a.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>a.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":d===x,onClick:()=>f(x),className:q("px-4 py-2 text-sm font-medium capitalize transition-colors",d===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:d==="edit"?a.jsx("textarea",{"aria-label":"template content",value:o,onChange:x=>c(x.target.value),disabled:i,className:q("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Agent instructions - -...`}):a.jsx("div",{className:q("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:o.trim()?a.jsx(pS,{remarkPlugins:[BS],children:o}):a.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[a.jsx(M,{type:"button",variant:"ghost",onClick:r,disabled:i,children:"Cancel"}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"Save template",disabled:!p,loading:i,children:"Save"})]})]})]})}function Qs(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function xO(){const{template:e}=he(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(!1),o=g.useCallback(async()=>{l(!0),i(null);try{const f=await e.listTemplates();n(f)}catch(f){i(Qs(f))}finally{l(!1)}},[e]);g.useEffect(()=>{o()},[o]);const c=g.useCallback(async f=>{l(!0),i(null);try{const p=await e.createTemplate(f);n(m=>[...m,p])}catch(p){i(Qs(p))}finally{l(!1)}},[e]),u=g.useCallback(async(f,p)=>{l(!0),i(null);try{const m=await e.updateTemplate(f,p);n(x=>x.map(w=>w.id===f?m:w))}catch(m){i(Qs(m))}finally{l(!1)}},[e]),h=g.useCallback(async f=>{l(!0),i(null);try{await e.deleteTemplate(f),n(p=>p.filter(m=>m.id!==f))}catch(p){i(Qs(p))}finally{l(!1)}},[e]),d=g.useCallback(async(f,p,m)=>{l(!0),i(null);try{await e.createAgentFromTemplate(f,p,m)}catch(x){i(Qs(x))}finally{l(!1)}},[e]);return{templates:t,error:r,busy:s,refresh:o,createTemplate:c,updateTemplate:u,deleteTemplate:h,createAgentFromTemplate:d}}function zS({projectId:e}){const t=xO(),{profile:n}=he(),[r,i]=g.useState([]),[s,l]=g.useState(!1),[o,c]=g.useState(null),[u,h]=g.useState(!1);async function d(p){if(!s){try{const m=await n.listProfiles();i(m)}catch{}l(!0)}c(p)}async function f(p,m,x){if(o){h(!0);try{o.mode==="create"?await t.createTemplate({name:p,content:m,defaultProfileId:x}):await t.updateTemplate(o.template.id,m),c(null)}finally{h(!1)}}}return a.jsxs(a.Fragment,{children:[o!==null&&a.jsx(gO,{template:o.mode==="edit"?o.template:null,profiles:r,onSave:f,onClose:()=>c(null),busy:u}),a.jsxs(we,{title:"Templates",className:"flex flex-col gap-0",children:[t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Templates"}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&a.jsx(Re,{size:14}),a.jsx(M,{type:"button",variant:"primary","aria-label":"create template",disabled:t.busy,onClick:()=>void d({mode:"create"}),children:"New template"})]})]}),a.jsx("div",{className:"p-4",children:t.templates.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No templates yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.templates.map(p=>a.jsx("li",{className:"flex flex-col gap-2 py-3 first:pt-0 last:pb-0",children:a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"font-medium text-content",children:p.name}),a.jsxs("span",{className:"text-xs text-muted",children:["v",p.version]})]}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit ${p.name}`,disabled:t.busy,onClick:()=>void d({mode:"edit",template:p}),children:"Edit"}),a.jsx(M,{size:"sm",variant:"primary","aria-label":`create agent from ${p.name}`,disabled:t.busy,onClick:()=>void t.createAgentFromTemplate(e,p.id),children:"Create agent"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete template ${p.name}`,disabled:t.busy,onClick:()=>void t.deleteTemplate(p.id),className:"text-danger hover:text-danger",children:"Delete"})]})]})},p.id))})})]})]})}function vO({skill:e,onSave:t,onClose:n,busy:r=!1}){const[i,s]=g.useState(e?.name??""),[l,o]=g.useState(e?.contentMd??""),[c,u]=g.useState(e?.scope??"project"),[h,d]=g.useState("edit"),f=e!=null,p=i.trim().length>0&&l.trim().length>0&&!r;async function m(x){x.preventDefault(),p&&await t(i.trim(),l,c)}return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"skill editor",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:f?`Edit skill — ${e.name}`:"New skill"}),a.jsx(M,{type:"button",variant:"ghost","aria-label":"close skill editor",onClick:n,disabled:r,children:"✕"})]}),a.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"se-name",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(ce,{id:"se-name","aria-label":"skill name",placeholder:"My skill",value:i,onChange:x=>s(x.target.value),disabled:r,className:"min-w-48"})]}),a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"se-scope",className:"text-xs font-medium text-muted",children:"Scope"}),a.jsxs("select",{id:"se-scope","aria-label":"skill scope",value:c,onChange:x=>u(x.target.value),disabled:r||f,className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"project",children:"Project"}),a.jsx("option",{value:"global",children:"Global"})]})]})]}),a.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>a.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":h===x,onClick:()=>d(x),className:q("px-4 py-2 text-sm font-medium capitalize transition-colors",h===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:h==="edit"?a.jsx("textarea",{"aria-label":"skill content",value:l,onChange:x=>o(x.target.value),disabled:r,className:q("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Skill workflow - -...`}):a.jsx("div",{className:q("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:l.trim()?a.jsx(pS,{remarkPlugins:[BS],children:l}):a.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[a.jsx(M,{type:"button",variant:"ghost",onClick:n,disabled:r,children:"Cancel"}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"Save skill",disabled:!p,loading:r,children:"Save"})]})]})]})}function za(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function _O(e){const{skill:t}=he(),[n,r]=g.useState([]),[i,s]=g.useState([]),[l,o]=g.useState(null),[c,u]=g.useState(!1),h=g.useCallback(async()=>{if(e){u(!0),o(null);try{const[x,w]=await Promise.all([t.listSkills(e,"global"),t.listSkills(e,"project")]);r(x),s(w)}catch(x){o(za(x))}finally{u(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=x=>x==="global"?r:s,f=g.useCallback(async x=>{u(!0),o(null);try{const w=await t.createSkill({...x,projectId:e});d(x.scope)(v=>[...v,w])}catch(w){o(za(w))}finally{u(!1)}},[t,e]),p=g.useCallback(async(x,w,v)=>{u(!0),o(null);try{const _=await t.updateSkill(e,x,w,v);d(x)(y=>y.map(b=>b.id===w?_:b))}catch(_){o(za(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async(x,w)=>{u(!0),o(null);try{await t.deleteSkill(e,x,w),d(x)(v=>v.filter(_=>_.id!==w))}catch(v){o(za(v))}finally{u(!1)}},[t,e]);return{globalSkills:n,projectSkills:i,error:l,busy:c,refresh:h,createSkill:f,updateSkill:p,deleteSkill:m}}function FS({projectId:e}){const t=_O(e),[n,r]=g.useState(null),[i,s]=g.useState(!1);async function l(c,u,h){if(n){s(!0);try{n.mode==="create"?await t.createSkill({name:c,content:u,scope:h}):await t.updateSkill(n.skill.scope,n.skill.id,u),r(null)}finally{s(!1)}}}function o(c,u){return a.jsx("div",{className:"p-4",children:u.length===0?a.jsxs("p",{className:"text-sm text-muted",children:["No ",c," skills yet."]}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.map(h=>a.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[a.jsx("span",{className:"min-w-0 font-medium text-content",children:h.name}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit skill ${h.name}`,disabled:t.busy,onClick:()=>r({mode:"edit",skill:h}),children:"Edit"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete skill ${h.name}`,disabled:t.busy,onClick:()=>void t.deleteSkill(h.scope,h.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},h.id))})})}return a.jsxs(a.Fragment,{children:[n!==null&&a.jsx(vO,{skill:n.mode==="edit"?n.skill:null,onSave:l,onClose:()=>r(null),busy:i}),a.jsxs(we,{title:"Skills",className:"flex flex-col gap-0",children:[t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Skills"}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&a.jsx(Re,{size:14}),a.jsx(M,{type:"button",variant:"primary","aria-label":"create skill",disabled:t.busy,onClick:()=>r({mode:"create"}),children:"New skill"})]})]}),a.jsx("div",{className:"border-b border-border px-4 pt-3",children:a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Project"})}),o("project",t.projectSkills),a.jsx("div",{className:"border-y border-border px-4 pt-3",children:a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Global"})}),o("global",t.globalSkills)]})]})}function Ju(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function $S(){const{embedder:e}=he(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(null),[o,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{const[p,m]=await Promise.all([e.listEmbedderProfiles(),e.describeEmbedderEngines()]);n(p),i(m)}catch(p){l(Ju(p))}finally{c(!1)}},[e]);g.useEffect(()=>{u()},[u]);const h=g.useCallback(async p=>{c(!0),l(null);try{await e.saveEmbedderProfile(p),await u()}catch(m){l(Ju(m)),c(!1)}},[e,u]),d=g.useCallback(async p=>{c(!0),l(null);try{await e.deleteEmbedderProfile(p),await u()}catch(m){l(Ju(m)),c(!1)}},[e,u]),f=t.find(p=>p.strategy!=="none")??null;return{profiles:t,engines:r,active:f,error:s,busy:o,refresh:u,saveProfile:h,deleteProfile:d}}const WS="http://localhost:11434/api/embeddings",HS="https://api.openai.com/v1/embeddings",Zu=[{strategy:"none",key:"none",label:"None (naïve recall)"},{strategy:"localOnnx",key:"localOnnx",label:"Local ONNX"},{strategy:"localServer",key:"localServer",label:"Ollama (local server)"},{strategy:"api",key:"api",label:"API"},{strategy:"api",key:"custom",label:"Custom"}],Wi={id:"",name:"",model:"",endpoint:"",apiKeyEnv:"",dimension:"",onnxEngineId:""};function yO(e,t,n){if(n)return{id:n.id,name:n.name,model:n.model??"",endpoint:n.endpoint??"",apiKeyEnv:n.apiKeyEnv??"",dimension:String(n.dimension),onnxEngineId:e==="localOnnx"?t.find(r=>r.id===n.model)?.id??t[0]?.id??"":""};switch(e){case"localOnnx":{const r=t.find(i=>i.recommended)??t[0];return{...Wi,id:"onnx-local",name:r?.displayName??"Local ONNX",model:r?.id??"",dimension:r?String(r.dimension):"",onnxEngineId:r?.id??""}}case"localServer":return{...Wi,id:"ollama",name:"Ollama",endpoint:WS,model:"nomic-embed-text",dimension:"768"};case"api":return{...Wi,id:"api",name:"API embedder",endpoint:HS,apiKeyEnv:"OPENAI_API_KEY",model:"text-embedding-3-small",dimension:"1536"};case"custom":return{...Wi,id:"custom",name:"Custom embedder"};default:return{...Wi}}}function bO(e,t){switch(e){case"none":return!0;case"localOnnx":return t.vectorOnnxEnabled;case"localServer":case"api":return t.vectorHttpEnabled}}function US(){const e=$S(),[t,n]=g.useState("localOnnx"),[r,i]=g.useState(Wi),s=e.engines?.recommendedOnnx??[],l={vectorOnnxEnabled:e.engines?.vectorOnnxEnabled??!1,vectorHttpEnabled:e.engines?.vectorHttpEnabled??!1};g.useEffect(()=>{if(!e.engines)return;const _=Zu.find(b=>b.key===t),y=e.active&&_&&e.active.strategy===_.strategy?e.active:null;i(yO(t,e.engines.recommendedOnnx,y))},[e.engines,e.active,t]);const c=Zu.find(_=>_.key===t).strategy;function u(_){i(y=>({...y,..._}))}function h(_){const y=s.find(b=>b.id===_);u({onnxEngineId:_,model:y?.id??_,dimension:y?String(y.dimension):r.dimension})}const d=Number.parseInt(r.dimension,10),f=g.useMemo(()=>c==="none"?{ok:!0}:r.id.trim()?r.name.trim()?!Number.isFinite(d)||d<=0?{ok:!1,msg:"Dimension must be a positive number."}:(c==="localServer"||c==="api")&&!r.endpoint.trim()?{ok:!1,msg:"Endpoint is required."}:{ok:!0}:{ok:!1,msg:"Name is required."}:{ok:!1,msg:"Id is required."},[c,r,d]);function p(){return{id:r.id.trim(),name:r.name.trim(),strategy:c,dimension:d,model:r.model.trim()||void 0,endpoint:(c==="localServer"||c==="api")&&r.endpoint.trim()||void 0,apiKeyEnv:c==="api"&&r.apiKeyEnv.trim()||void 0}}async function m(){f.ok&&await e.saveProfile(p())}async function x(){for(const _ of e.profiles)await e.deleteProfile(_.id);n("none")}const w=q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),v=e.active!==null;return a.jsxs(we,{title:"Memory / Embedder",className:"flex flex-col gap-0",children:[e.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),a.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[a.jsx("p",{className:"rounded-md border border-border bg-raised px-3 py-2 text-xs text-muted","data-testid":"embedder-restart-note",children:"The embedder change takes effect at the next app start."}),a.jsxs("p",{className:"text-xs text-faint","data-testid":"embedder-active",children:["Current:"," ",v?a.jsxs("span",{className:"text-content",children:["Vector — ",e.active.strategy,e.active.model?` ${e.active.model}`:""]}):a.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),a.jsxs("fieldset",{className:"flex flex-col gap-2","aria-label":"embedder strategy",children:[a.jsx("legend",{className:"mb-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Strategy"}),Zu.map(_=>{const y=bO(_.strategy,l),b=_.key==="localOnnx";return a.jsxs("label",{className:q("flex items-center gap-2 rounded-md border px-3 py-2 text-sm",t===_.key?"border-primary bg-raised":"border-border",!y&&"opacity-50"),"data-testid":`embedder-strategy-${_.key}`,children:[a.jsx("input",{type:"radio",name:"embedder-strategy",value:_.key,checked:t===_.key,disabled:!y,onChange:()=>n(_.key),"aria-label":_.label}),a.jsx("span",{className:"text-content",children:_.label}),b&&a.jsx("span",{className:"rounded border border-primary/40 bg-primary/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-primary",children:"Recommended"}),!y&&a.jsx("span",{className:"text-[11px] text-faint",children:"not available in this build"})]},_.key)})]}),c!=="none"&&a.jsxs("div",{className:"flex flex-col gap-3",children:[c==="localOnnx"&&a.jsx(qt,{label:"ONNX model",children:({id:_})=>a.jsx("select",{id:_,"aria-label":"onnx model",className:w,value:r.onnxEngineId,disabled:e.busy,onChange:y=>h(y.target.value),children:s.map(y=>a.jsxs("option",{value:y.id,children:[y.displayName,y.recommended?" — recommended":""," (dim"," ",y.dimension,", ~",y.approxSizeMb," MB)"]},y.id))})}),(c==="localServer"||c==="api")&&a.jsx(qt,{label:"Endpoint",children:({id:_})=>a.jsx(ce,{id:_,"aria-label":"endpoint",placeholder:c==="localServer"?WS:HS,value:r.endpoint,disabled:e.busy,onChange:y=>u({endpoint:y.target.value})})}),c==="api"&&a.jsx(qt,{label:"API key environment variable",hint:"Name of the env var holding the key — never the key itself.",children:({id:_,describedBy:y})=>a.jsx(ce,{id:_,"aria-label":"api key env var",placeholder:"OPENAI_API_KEY","aria-describedby":y,value:r.apiKeyEnv,disabled:e.busy,onChange:b=>u({apiKeyEnv:b.target.value})})}),c!=="localOnnx"&&a.jsx(qt,{label:"Model",children:({id:_})=>a.jsx(ce,{id:_,"aria-label":"model",placeholder:"model name",value:r.model,disabled:e.busy,onChange:y=>u({model:y.target.value})})}),a.jsx(qt,{label:"Dimension",error:f.ok?void 0:f.msg,children:({id:_,describedBy:y})=>a.jsx(ce,{id:_,"aria-label":"dimension",type:"number",min:1,value:r.dimension,"aria-describedby":y,disabled:e.busy,onChange:b=>u({dimension:b.target.value})})}),a.jsx(qt,{label:"Profile id",children:({id:_})=>a.jsx(ce,{id:_,"aria-label":"profile id",placeholder:"my-embedder",value:r.id,disabled:e.busy,onChange:y=>u({id:y.target.value})})}),a.jsx(qt,{label:"Profile name",children:({id:_})=>a.jsx(ce,{id:_,"aria-label":"profile name",placeholder:"My embedder",value:r.name,disabled:e.busy,onChange:y=>u({name:y.target.value})})})]}),a.jsxs("div",{className:"flex items-center gap-2 border-t border-border pt-3",children:[e.busy&&a.jsx(Re,{size:14}),c!=="none"&&a.jsx(M,{type:"button",variant:"primary","aria-label":"save embedder",disabled:e.busy||!f.ok,onClick:()=>void m(),children:"Save"}),a.jsx(M,{type:"button","aria-label":"back to none",disabled:e.busy,onClick:()=>void x(),children:"Back to None"})]})]})]})}const wO=["user","feedback","project","reference"];function SO({entry:e,loadContent:t,resolveLinks:n,onCreate:r,onUpdate:i,onClose:s,busy:l=!1}){const o=e!=null,[c,u]=g.useState(e?.title??""),[h,d]=g.useState(e?.hook??""),[f,p]=g.useState(e?.type??"project"),[m,x]=g.useState(""),[w,v]=g.useState([]);g.useEffect(()=>{if(!e)return;let C=!1;return(async()=>{try{if(t){const k=await t(e.slug);C||x(k)}if(n){const k=await n(e.slug);C||v(k)}}catch{}})(),()=>{C=!0}},[e,t,n]);const _=h.trim().length>0&&m.trim().length>0&&!l&&(o||c.trim().length>0);async function y(C){C.preventDefault(),_&&(o?await i(e.slug,h.trim(),f,m):await r(c.trim(),h.trim(),f,m))}const b=q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"memory editor",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:o?`Edit note — ${e.title}`:"New note"}),a.jsx(M,{type:"button",variant:"ghost","aria-label":"close memory editor",onClick:s,disabled:l,children:"✕"})]}),a.jsxs("form",{onSubmit:C=>void y(C),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o?a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Slug"}),a.jsx("code",{className:"truncate rounded-md border border-border bg-raised px-3 py-2 text-sm text-muted",children:e.slug})]}):a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"me-name",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(ce,{id:"me-name","aria-label":"memory name",placeholder:"My note",value:c,onChange:C=>u(C.target.value),disabled:l,className:"min-w-48"})]}),a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"me-type",className:"text-xs font-medium text-muted",children:"Type"}),a.jsx("select",{id:"me-type","aria-label":"memory type",value:f,onChange:C=>p(C.target.value),disabled:l,className:b,children:wO.map(C=>a.jsx("option",{value:C,children:C},C))})]})]}),a.jsxs("div",{className:"flex shrink-0 flex-col gap-1 border-b border-border px-4 py-3",children:[a.jsx("label",{htmlFor:"me-description",className:"text-xs font-medium text-muted",children:"Description"}),a.jsx(ce,{id:"me-description","aria-label":"memory description",placeholder:"One-line hook",value:h,onChange:C=>d(C.target.value),disabled:l})]}),a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:[a.jsx("label",{htmlFor:"me-content",className:"mb-1 text-xs font-medium text-muted",children:"Content"}),a.jsx("textarea",{id:"me-content","aria-label":"memory content",value:m,onChange:C=>x(C.target.value),disabled:l,className:q("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Note - -Use [[other-slug]] to link…`}),o&&a.jsxs("div",{className:"mt-3 shrink-0",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Links"}),w.length===0?a.jsx("p",{className:"mt-1 text-sm text-muted",children:"No resolved links."}):a.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:w.map(C=>a.jsx("li",{className:"rounded-md border border-border bg-raised px-2 py-0.5 text-xs text-muted",children:C},C))})]})]}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[a.jsx(M,{type:"button",variant:"ghost",onClick:s,disabled:l,children:"Cancel"}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"Save note",disabled:!_,loading:l,children:"Save"})]})]})]})}function Fa(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function kO(e){const{memory:t,system:n}=he(),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(!1),u=g.useCallback(async()=>{if(e){c(!0),l(null);try{i(await t.readIndex(e))}catch(m){l(Fa(m))}finally{c(!1)}}},[t,e]);g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let m,x=!1;return n.onDomainEvent(w=>{w.type==="memorySaved"&&u()}).then(w=>{x?w():m=w}),()=>{x=!0,m?.()}},[u,n]);const h=g.useCallback(async m=>{c(!0),l(null);try{await t.createMemory({...m,projectId:e}),await u()}catch(x){l(Fa(x)),c(!1)}},[t,e,u]),d=g.useCallback(async(m,x,w,v)=>{c(!0),l(null);try{await t.updateMemory(e,m,x,w,v),await u()}catch(_){l(Fa(_)),c(!1)}},[t,e,u]),f=g.useCallback(async m=>{c(!0),l(null);try{await t.deleteMemory(e,m),await u()}catch(x){l(Fa(x)),c(!1)}},[t,e,u]),p=g.useCallback(m=>t.resolveLinks(e,m),[t,e]);return{entries:r,error:s,busy:o,refresh:u,createMemory:h,updateMemory:d,deleteMemory:f,resolveLinks:p}}function qS({projectId:e}){const t=kO(e),n=$S(),{memory:r}=he(),[i,s]=g.useState(null),[l,o]=g.useState(!1),c=g.useCallback(async d=>(await r.getMemory(e,d)).content,[r,e]);async function u(d,f,p,m){o(!0);try{await t.createMemory({name:d,description:f,type:p,content:m}),s(null)}finally{o(!1)}}async function h(d,f,p,m){o(!0);try{await t.updateMemory(d,f,p,m),s(null)}finally{o(!1)}}return a.jsxs(a.Fragment,{children:[i!==null&&a.jsx(SO,{entry:i.mode==="edit"?i.entry:null,loadContent:c,resolveLinks:t.resolveLinks,onCreate:u,onUpdate:h,onClose:()=>s(null),busy:l}),a.jsxs(we,{title:"Memory",className:"flex flex-col gap-0",children:[a.jsxs("p",{className:"border-b border-border px-4 py-2 text-xs text-faint","data-testid":"memory-tier",children:["Tier:"," ",n.active?a.jsxs("span",{className:"text-content",children:["Vector — ",n.active.strategy,n.active.model?` ${n.active.model}`:""]}):a.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Notes"}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&a.jsx(Re,{size:14}),a.jsx(M,{type:"button",variant:"primary","aria-label":"create memory",disabled:t.busy,onClick:()=>s({mode:"create"}),children:"New note"})]})]}),a.jsx("div",{className:"p-4",children:t.entries.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No memory notes yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.entries.map(d=>a.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"min-w-0 truncate font-medium text-content",children:d.title}),a.jsx("span",{className:"shrink-0 rounded border border-border bg-raised px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted",children:d.type})]}),a.jsx("span",{className:"truncate text-xs text-muted",children:d.hook})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit memory ${d.title}`,disabled:t.busy,onClick:()=>s({mode:"edit",entry:d}),children:"Edit"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete memory ${d.title}`,disabled:t.busy,onClick:()=>void t.deleteMemory(d.slug),className:"text-danger hover:text-danger",children:"Delete"})]})]},d.slug))})})]})]})}const Cv=[{id:"readProject",label:"Lecture projet",tools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read"]},{id:"readTickets",label:"Lecture tickets",tools:["idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"]},{id:"delegation",label:"Délégation agents",tools:["idea_ask_agent","idea_launch_agent","idea_stop_agent"]},{id:"contextMemory",label:"Contexte et mémoire",tools:["idea_update_context","idea_context_propose","idea_memory_write"]},{id:"tickets",label:"Tickets",tools:["idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]},{id:"work",label:"Travail et exécution",tools:["idea_run_in_background","idea_workstate_set"]},{id:"skills",label:"Skills",tools:["idea_create_skill"]}],CO={idea_list_agents:"Lister les agents",idea_context_read:"Lire le contexte d'un agent",idea_memory_read:"Lire la mémoire projet",idea_skill_read:"Lire un skill",idea_workstate_read:"Lire l'état de travail",idea_ticket_read:"Lire un ticket",idea_ticket_list:"Lister les tickets",idea_ticket_read_carnet:"Lire le carnet d'un ticket",idea_sprint_list:"Lister les sprints",idea_ask_agent:"Déléguer à un agent",idea_launch_agent:"Lancer un agent",idea_stop_agent:"Arrêter un agent",idea_update_context:"Modifier le contexte d'un agent",idea_context_propose:"Proposer un contexte",idea_memory_write:"Écrire la mémoire projet",idea_workstate_set:"Écrire l'état de travail",idea_create_skill:"Créer un skill",idea_ticket_create:"Créer un ticket",idea_ticket_update:"Modifier un ticket",idea_ticket_update_status:"Modifier le statut d'un ticket",idea_ticket_update_priority:"Modifier la priorité d'un ticket",idea_ticket_update_carnet:"Modifier le carnet d'un ticket",idea_ticket_link:"Lier des tickets",idea_ticket_unlink:"Délier des tickets",idea_run_in_background:"Exécuter une commande en arrière-plan"};function jO(e){return CO[e]??e}function $a(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NO(e){const{permission:t}=he(),[n,r]=g.useState(null),[i,s]=g.useState(!1),[l,o]=g.useState(!1),[c,u]=g.useState(null),h=g.useCallback(async()=>{if(t){s(!0),u(null);try{r(await t.getMcpToolPermissions(e))}catch(m){u($a(m))}finally{s(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=g.useCallback(async m=>{if(t){o(!0),u(null);try{r(await t.updateProjectMcpToolPermissions(e,m))}catch(x){throw u($a(x)),x}finally{o(!1)}}},[t,e]),f=g.useCallback(async(m,x)=>{if(t){o(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,x))}catch(w){throw u($a(w)),w}finally{o(!1)}}},[t,e]),p=g.useCallback(async m=>{if(t){o(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,null))}catch(x){throw u($a(x)),x}finally{o(!1)}}},[t,e]);return{doc:n,loading:i,busy:l,error:c,refresh:h,saveProjectDefault:d,saveAgentOverride:f,resetAgentOverride:p}}const EO=new Set(["readProject","readTickets"]);function PO(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function AO(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(r=>n.has(r))}function TO({projectId:e,agents:t}){const n=NO(e),[r,i]=g.useState({type:"project"}),s=g.useRef(!1);function l(u){s.current&&!window.confirm("Des modifications non enregistrées seront perdues. Continuer ?")||(s.current=!1,i(u))}if(n.loading&&!n.doc)return a.jsxs("div",{"data-testid":"mcp-tool-permissions-skeleton",className:"flex flex-col gap-3 p-4",children:[a.jsx("div",{className:"h-4 w-40 animate-pulse rounded bg-raised"}),a.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),a.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),a.jsx("div",{className:"h-32 w-full animate-pulse rounded bg-raised"})]});if(n.error&&!n.doc)return a.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[a.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),a.jsx(M,{size:"sm",onClick:()=>void n.refresh(),children:"Réessayer"})]});if(!n.doc)return null;const o=n.doc,c=r.type==="agent"?o.agents.find(u=>u.agentId===r.agentId)??null:null;return a.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4 md:flex-row",children:[a.jsxs("nav",{"aria-label":"cibles des permissions MCP",className:"flex w-full shrink-0 flex-col gap-2 md:w-56",children:[a.jsxs("button",{type:"button","aria-pressed":r.type==="project",onClick:()=>l({type:"project"}),className:q("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",r.type==="project"?"border-primary bg-raised":"border-border bg-surface"),children:[a.jsx("span",{className:"font-medium text-content",children:"Défaut projet"}),a.jsx("span",{className:"text-xs text-muted",children:o.projectDefault?"Personnalisé":"Lecture seule"})]}),a.jsx("h4",{className:"mt-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun agent dans ce projet."}):a.jsx("ul",{className:"flex flex-col gap-1.5",children:t.map(u=>{const h=o.agents.some(f=>f.agentId===u.id),d=r.type==="agent"&&r.agentId===u.id;return a.jsx("li",{children:a.jsxs("button",{type:"button","aria-pressed":d,onClick:()=>l({type:"agent",agentId:u.id,agentName:u.name}),className:q("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",d?"border-primary bg-raised":"border-border bg-surface"),children:[a.jsx("span",{className:"truncate font-medium text-content",children:u.name}),a.jsx("span",{className:q("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",h?"bg-warning/15 text-warning":"bg-primary/10 text-muted"),children:h?"Override":"Hérité"})]})},u.id)})})]}),a.jsx("div",{className:"min-w-0 flex-1",children:r.type==="project"?a.jsx(jv,{targetKind:"project",title:"Tools MCP IdeA — Défaut projet",catalogue:o.catalogue,storedAllowed:o.projectDefault?.allowedTools??null,comparisonBaseline:o.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{s.current=u},onSaveProjectDefault:async u=>{await n.saveProjectDefault({allowedTools:u})}},"project"):a.jsx(jv,{targetKind:"agent",title:`Tools MCP IdeA — ${r.agentName}`,catalogue:o.catalogue,storedAllowed:c?.policy.allowedTools??null,comparisonBaseline:o.projectDefault?.allowedTools??o.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{s.current=u},onSaveAgentOverride:async u=>{await n.saveAgentOverride(r.agentId,{allowedTools:u})},onResetOverride:async()=>{await n.resetAgentOverride(r.agentId)}},r.agentId)})]})}function jv({targetKind:e,title:t,catalogue:n,storedAllowed:r,comparisonBaseline:i,busy:s,onDirtyChange:l,onSaveProjectDefault:o,onSaveAgentOverride:c,onResetOverride:u}){const h=r??i,[d,f]=g.useState(e==="project"||r!=null),[p,m]=g.useState(r!=null),[x,w]=g.useState(h),[v,_]=g.useState(h),[y,b]=g.useState(!1),[C,k]=g.useState(!1),[N,R]=g.useState(null),[L,S]=g.useState(()=>Object.fromEntries(Cv.map(ie=>[ie.id,EO.has(ie.id)?e==="project":!0]))),T=e==="project"||d,D=T?x:i,P=T&&!AO(x,v);g.useEffect(()=>{l(P)},[P]),g.useEffect(()=>{if(!C)return;const ie=window.setTimeout(()=>k(!1),2e3);return()=>window.clearTimeout(ie)},[C]);const I=n.readOnlyTools.filter(ie=>D.includes(ie)).length,O=n.writeActionTools.filter(ie=>D.includes(ie)).length,U=g.useMemo(()=>new Set([...n.readOnlyTools,...n.writeActionTools]),[n]),G=g.useMemo(()=>Array.from(new Set([...D,...i])).filter(ie=>!U.has(ie)),[D,i,U]);function E(ie){R(null),w(ee=>PO(ee,ie))}function z(ie){S(ee=>({...ee,[ie]:!ee[ie]}))}function j(){f(!0),w(i),_(i)}function re(){w(v),b(!1),R(null)}async function V(){if(R(null),e==="project"){if(x.some(ee=>n.writeActionTools.includes(ee)&&!v.includes(ee))&&!y){b(!0);return}b(!1);try{await o?.(x),_(x),k(!0)}catch(ee){R(ed(ee))}return}try{await c?.(x),_(x),m(!0),k(!0)}catch(ie){R(ed(ie))}}async function A(){R(null);try{await u?.(),f(!1),m(!1),w(i),_(i),k(!0)}catch(ie){R(ed(ie))}}return a.jsx(we,{title:t,className:"flex h-full flex-col",flush:!0,children:a.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e==="agent"&&a.jsx("p",{className:"text-xs text-muted",children:d?"Override personnalisé":"Hérite du défaut projet"}),e==="agent"&&!d&&a.jsx(M,{size:"sm",onClick:j,disabled:s,children:"Créer un override"}),a.jsxs("div",{children:[a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Résumé effectif"}),a.jsxs("p",{className:"text-sm text-content",children:[I," lecture autorisés · ",O," écriture autorisé",O>1?"s":""]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Détail des tools"}),Cv.map(ie=>a.jsx(Nv,{group:ie,expanded:L[ie.id]??!0,onToggle:()=>z(ie.id),catalogue:n,editable:T,targetKind:e,draftSet:x,displaySet:D,comparisonBaseline:i,onToggleTool:E},ie.id)),G.length>0&&a.jsx(Nv,{group:{id:"unknown",label:"Tools inconnus",tools:G},expanded:L.unknown??!0,onToggle:()=>z("unknown"),catalogue:n,editable:!1,targetKind:e,draftSet:x,displaySet:D,comparisonBaseline:i,onToggleTool:E,unknown:!0})]}),y&&a.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning",children:[a.jsx("p",{children:"Ce tool sera autorisé pour tous les agents sans override. Confirmer cette modification ?"}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>b(!1),children:"Annuler"}),a.jsx(M,{size:"sm",variant:"primary",onClick:()=>void V(),children:"Confirmer"})]})]}),N&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:N}),C&&a.jsx("p",{role:"status",className:"text-sm text-success",children:"Permissions enregistrées"}),a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[a.jsx("div",{children:P&&a.jsx("span",{className:"text-xs text-warning",children:"Modifications non enregistrées"})}),a.jsxs("div",{className:"flex gap-2",children:[e==="agent"&&p&&a.jsx(M,{size:"sm",variant:"ghost",disabled:s,onClick:()=>void A(),children:"Réinitialiser l'override"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:s||!P,onClick:re,children:"Annuler"}),a.jsx(M,{size:"sm",variant:"primary",disabled:s||!T||!P,loading:s&&P,onClick:()=>void V(),children:"Enregistrer"})]})]})]})})}function Nv({group:e,expanded:t,onToggle:n,catalogue:r,editable:i,targetKind:s,displaySet:l,comparisonBaseline:o,onToggleTool:c,unknown:u}){const h=e.tools.filter(f=>l.includes(f)).length,d=e.tools.length;return a.jsxs("div",{className:"rounded-md border border-border",children:[a.jsxs("button",{type:"button","aria-expanded":t,"aria-label":`${e.label}, ${h} sur ${d} autorisé${d>1?"s":""}`,onClick:n,className:"flex min-h-[32px] w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-raised",children:[a.jsx("span",{className:"font-medium text-content",children:e.label}),a.jsxs("span",{className:"text-xs text-muted",children:[h,"/",d," autorisés"]})]}),t&&a.jsx("ul",{className:"flex flex-col divide-y divide-border border-t border-border",children:e.tools.map(f=>a.jsx(RO,{tool:f,isRead:r.readOnlyTools.includes(f),unknown:u,editable:i,checked:l.includes(f),status:LO(f,i,s,l,o,u),onToggle:()=>c(f)},f))})]})}function LO(e,t,n,r,i,s){if(s)return"unknown";if(n==="agent"&&!t)return"inherited";if(n==="agent"&&t){const l=r.includes(e),o=i.includes(e);return l&&!o?"added":!l&&o?"removed":l?"allowed":"denied"}return r.includes(e)?"allowed":"denied"}const DO={allowed:"Autorisé",denied:"Refusé",inherited:"Hérité",added:"Ajouté",removed:"Retiré",unknown:"Inconnu"};function RO({tool:e,isRead:t,unknown:n,editable:r,checked:i,status:s,onToggle:l}){const o=jO(e),c=`mcp-tool-${e}`;return a.jsxs("li",{className:"flex min-h-[32px] items-center gap-2 px-3 py-1.5",children:[a.jsx("input",{id:c,type:"checkbox",checked:i,disabled:!r||n,onChange:l,"aria-label":`${o}, ${e}`}),a.jsxs("label",{htmlFor:c,className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("code",{className:"font-mono text-xs text-content",children:e}),!n&&a.jsx("span",{className:q("rounded-full px-1.5 py-0.5 text-[10px] font-medium",t?"bg-primary/10 text-primary":"bg-warning/15 text-warning"),children:t?"Lecture":"Écriture"})]}),a.jsx("span",{className:"text-xs text-muted",children:o})]}),a.jsx("span",{className:q("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",s==="allowed"||s==="added"?"bg-success/15 text-success":s==="denied"||s==="removed"?"bg-danger/10 text-muted":s==="unknown"?"bg-danger/15 text-danger":"bg-primary/10 text-muted"),children:DO[s]})]})}function ed(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Ev={fallback:"ask",read:"none",write:"none",delete:"none",executeBash:"none"},VS=["read","write","delete","executeBash"];function Js(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function KS(e){if(!e)return{...Ev};const t={...Ev,fallback:e.fallback};for(const n of VS)t[n]=MO(e.rules,n);return t}function MO(e,t){const n=e.filter(r=>r.capability===t);return n.some(r=>r.effect==="deny")?"deny":n.some(r=>r.effect==="allow")?"allow":"none"}function Pv(e){const t=[];for(const n of VS){const r=e[n];r!=="none"&&t.push(IO(n,r))}return{fallback:e.fallback,rules:t}}function IO(e,t){return e==="executeBash"?{capability:e,effect:t,commands:[]}:{capability:e,effect:t,paths:["**"]}}function Wa(e){return e?e.rules.some(t=>{if(t.capability==="executeBash")return(t.commands??[]).length>0;const n=t.paths??[];return n.length!==1||n[0]!=="**"}):!1}function OO(e){const{agent:t,permission:n}=he(),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{c(!0),h(null);try{const[_,y]=await Promise.all([t.listAgents(e),n.getProjectPermissions(e)]);i(_),l(y)}catch(_){h(Js(_))}finally{c(!1)}},[t,n,e]);g.useEffect(()=>{d()},[d]);const f=g.useMemo(()=>{const _=new Map((s?.agents??[]).map(y=>[y.agentId,y.permissions]));return r.map(y=>({agent:y,override:_.get(y.id)??null}))},[r,s]),p=g.useMemo(()=>KS(s?.projectDefaults??null),[s]),m=g.useCallback(async _=>{c(!0),h(null);try{l(await n.updateProjectPermissions(e,Pv(_)))}catch(y){h(Js(y))}finally{c(!1)}},[n,e]),x=g.useCallback(async()=>{c(!0),h(null);try{l(await n.updateProjectPermissions(e,null))}catch(_){h(Js(_))}finally{c(!1)}},[n,e]),w=g.useCallback(async(_,y)=>{c(!0),h(null);try{l(await n.updateAgentPermissions(e,_,Pv(y)))}catch(b){h(Js(b))}finally{c(!1)}},[n,e]),v=g.useCallback(async _=>{c(!0),h(null);try{l(await n.updateAgentPermissions(e,_,null))}catch(y){h(Js(y))}finally{c(!1)}},[n,e]);return{agents:r,rows:f,document:s,projectDraft:p,busy:o,error:u,refresh:d,saveProjectDefaults:m,clearProjectDefaults:x,saveAgentOverride:w,clearAgentOverride:v}}const Bi=[{id:"system",label:"Système"},{id:"mcpTools",label:"Tools MCP IdeA"}],BO=[{key:"read",label:"Read"},{key:"write",label:"Write"},{key:"delete",label:"Delete"},{key:"executeBash",label:"Bash"}],zO={ask:"Ask",allow:"Allow",deny:"Deny"};function GS({projectId:e}){const t=OO(e),[n,r]=g.useState({type:"project"}),[i,s]=g.useState("system"),l=n.type==="agent"?t.rows.find(p=>p.agent.id===n.agentId)??null:null,o=l?.override??t.document?.projectDefaults??null,c=n.type==="project"?t.projectDraft:KS(l?.override??t.document?.projectDefaults??null),u=n.type==="project"?Wa(t.document?.projectDefaults):Wa(l?.override),h=t.document?.projectDefaults!=null;async function d(p){n.type==="project"?await t.saveProjectDefaults(p):await t.saveAgentOverride(n.agentId,p)}async function f(){n.type==="project"?await t.clearProjectDefaults():await t.clearAgentOverride(n.agentId)}return a.jsxs(we,{title:"Permissions",actions:a.jsx(M,{size:"sm",variant:"ghost",disabled:t.busy,onClick:()=>void t.refresh(),children:"Refresh"}),className:"flex min-h-0 flex-1 flex-col",flush:!0,children:[a.jsx("div",{role:"tablist","aria-label":"Permissions",className:"flex gap-1 border-b border-border px-4 pt-2",children:Bi.map(p=>a.jsx("button",{type:"button",role:"tab",id:`permissions-tab-${p.id}`,"aria-selected":i===p.id,"aria-controls":`permissions-tabpanel-${p.id}`,tabIndex:i===p.id?0:-1,onClick:()=>s(p.id),onKeyDown:m=>{if(m.key!=="ArrowRight"&&m.key!=="ArrowLeft")return;m.preventDefault();const x=Bi.findIndex(v=>v.id===i),w=m.key==="ArrowRight"?(x+1)%Bi.length:(x-1+Bi.length)%Bi.length;s(Bi[w].id)},className:q("min-h-[32px] rounded-t-md border-b-2 px-3 py-1.5 text-sm font-medium transition-colors",i===p.id?"border-primary text-content":"border-transparent text-muted hover:text-content"),children:p.label},p.id))}),t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{role:"tabpanel",id:"permissions-tabpanel-system","aria-labelledby":"permissions-tab-system",hidden:i!=="system",className:"flex flex-col gap-4 p-4",children:[a.jsx(Av,{title:"Project defaults",subtitle:h?"Configured":"Native CLI behavior",active:n.type==="project",custom:Wa(t.document?.projectDefaults),onSelect:()=>r({type:"project"}),policy:t.document?.projectDefaults??null}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.busy&&a.jsx(Re,{size:14})]}),t.rows.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):a.jsx("ul",{className:"flex flex-col gap-2",children:t.rows.map(p=>{const m=n.type==="agent"&&n.agentId===p.agent.id;return a.jsx("li",{children:a.jsx(Av,{title:p.agent.name,subtitle:p.override?"Override":"Inherited",active:m,custom:Wa(p.override),onSelect:()=>r({type:"agent",agentId:p.agent.id,agentName:p.agent.name}),policy:p.override})},p.agent.id)})})]}),a.jsx(FO,{title:n.type==="project"?"Project defaults":`Override — ${n.agentName}`,draft:c,sourcePolicy:o,custom:u,canClear:n.type==="project"?t.document?.projectDefaults!=null:l?.override!=null,busy:t.busy,onSave:p=>void d(p),onClear:()=>void f()},n.type==="project"?"project":n.agentId)]}),a.jsx("div",{role:"tabpanel",id:"permissions-tabpanel-mcpTools","aria-labelledby":"permissions-tab-mcpTools",hidden:i!=="mcpTools",className:"flex min-h-0 flex-1 flex-col",children:i==="mcpTools"&&a.jsx(TO,{projectId:e,agents:t.agents})})]})}function Av({title:e,subtitle:t,active:n,custom:r,policy:i,onSelect:s}){return a.jsxs("button",{type:"button",onClick:s,"aria-pressed":n,className:q("flex w-full min-w-0 items-center justify-between gap-3 rounded-md border px-3 py-2 text-left","transition-colors hover:border-border-strong hover:bg-raised",n?"border-primary bg-raised":"border-border bg-surface"),children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:e}),a.jsx("span",{className:"text-xs text-muted",children:t})]}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[r&&a.jsx("span",{className:"rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Custom"}),i&&a.jsx("span",{className:"rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary",children:zO[i.fallback]})]})]})}function FO({title:e,draft:t,sourcePolicy:n,custom:r,canClear:i,busy:s,onSave:l,onClear:o}){const[c,u]=g.useState(t),h=g.useRef(t);g.useEffect(()=>{u(p=>JSON.stringify(p)===JSON.stringify(h.current)?t:p),h.current=t},[t]);const d=g.useMemo(()=>JSON.stringify(c)!==JSON.stringify(t),[t,c]);function f(p,m){u(x=>({...x,[p]:m}))}return a.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[a.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-3 py-2.5",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h4",{className:"truncate text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"text-xs text-muted",children:n?`${n.rules.length} rules`:"Not configured"})]}),r&&a.jsx("span",{className:"shrink-0 rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Advanced"})]}),a.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Fallback"}),a.jsxs("select",{"aria-label":`${e} fallback`,value:c.fallback,disabled:s,onChange:p=>u(m=>({...m,fallback:p.target.value})),className:q("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"ask",children:"Ask"}),a.jsx("option",{value:"allow",children:"Allow"}),a.jsx("option",{value:"deny",children:"Deny"})]})]}),a.jsx("div",{className:"grid grid-cols-1 gap-2",children:BO.map(p=>a.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] items-center gap-2",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:p.label}),a.jsx($O,{value:c[p.key],disabled:s,label:p.label,onChange:m=>f(p.key,m)})]},p.key))}),a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:s||!i,onClick:o,children:"Clear"}),a.jsx(M,{size:"sm",variant:"primary",disabled:s||!d,loading:s&&d,onClick:()=>l(c),children:"Save"})]})]})]})}function $O({value:e,disabled:t,label:n,onChange:r}){const i=[{value:"none",label:"None"},{value:"allow",label:"Allow"},{value:"deny",label:"Deny"}];return a.jsx("div",{role:"group","aria-label":`${n} permission`,className:"grid grid-cols-3 overflow-hidden rounded-md border border-border",children:i.map(s=>a.jsx("button",{type:"button",disabled:t,"aria-pressed":e===s.value,onClick:()=>r(s.value),className:q("h-8 min-w-0 border-r border-border px-2 text-xs font-medium last:border-r-0","transition-colors disabled:cursor-not-allowed disabled:opacity-50",e===s.value?s.value==="deny"?"bg-danger/20 text-danger":s.value==="allow"?"bg-success/20 text-success":"bg-raised text-content":"bg-surface text-muted hover:bg-raised hover:text-content"),children:s.label},s.value))})}function Ip(e){return e.type.startsWith("issue")}function YS(e){return e.type.startsWith("sprint")}function WO(e){return e.replace(/[\s-]+/g,"").toUpperCase()}const HO=["open","inProgress","QA","closed"],UO=["low","medium","high","critical"],qO=["number","priority","status","title"],VO=["asc","desc"];function XS(e){return`tickets:listFilters:${e}`}function KO(e){return`tickets:pickerFilters:${e}`}function QS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tv(e,t){if(!Array.isArray(e))return;const n=new Set(t),r=[];for(const i of e)typeof i=="string"&&n.has(i)&&!r.includes(i)&&r.push(i);return r.length>0?r:void 0}function GO(e){if(!QS(e))return;const{field:t,direction:n}=e;if(typeof t=="string"&&qO.includes(t)&&typeof n=="string"&&VO.includes(n))return{field:t,direction:n}}function JS(e,t={}){if(!QS(e))return{};const n={};typeof e.text=="string"&&e.text.length>0&&(n.text=e.text);const r=Tv(e.statuses,HO);r&&(n.statuses=r);const i=Tv(e.priorities,UO);if(i&&(n.priorities=i),typeof e.assignedAgentId=="string"&&e.assignedAgentId){const{validAgentIds:l}=t;(!l||l.has(e.assignedAgentId))&&(n.assignedAgentId=e.assignedAgentId)}const s=GO(e.sort);return s&&(n.sort=s),typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0&&(n.limit=e.limit),n}function YO(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.assignedAgentId&&(t.assignedAgentId=e.assignedAgentId),e.sort&&(t.sort=e.sort),typeof e.limit=="number"&&(t.limit=e.limit),Object.keys(t).length>0?t:null}function XO(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.sort&&(t.sort=e.sort),Object.keys(t).length>0?t:null}function Lv(e,t,n){return e?JS(e.read(XS(t)),n):{}}function QO(e,t,n){if(!e)return;const r=YO(n),i=XS(t);r?e.write(i,r):e.remove(i)}function kr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Op(e){const{ticket:t,system:n,uiPreferences:r}=he(),[i,s]=g.useState(null),[l,o]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(!1),[f,p]=g.useState(()=>Lv(r,e)),m=g.useRef(e);g.useEffect(()=>{m.current!==e&&(m.current=e,p(Lv(r,e)))},[e,r]),g.useEffect(()=>{QO(r,e,f)},[r,e,f]);const x=g.useMemo(()=>JSON.stringify(f),[f]),w=g.useCallback(async()=>{d(!0),u(null);try{s(await t.list(e,f))}catch(T){u(kr(T))}finally{d(!1)}},[e,t,x]),v=g.useCallback(T=>{p(D=>{const P=D.statuses??[],I=P.includes(T)?P.filter(G=>G!==T):[...P,T],{statuses:O,...U}=D;return I.length>0?{...U,statuses:I}:U})},[]),_=g.useCallback(T=>{p(D=>{const P=D.priorities??[],I=P.includes(T)?P.filter(G=>G!==T):[...P,T],{priorities:O,...U}=D;return I.length>0?{...U,priorities:I}:U})},[]),y=g.useCallback(()=>{p(({statuses:T,priorities:D,...P})=>P)},[]),b=g.useCallback(async()=>{try{o(await t.listSprints(e))}catch(T){u(kr(T))}},[e,t]),C=g.useCallback(async T=>{u(null);try{const D=await t.create(e,T);return await w(),D}catch(D){return u(kr(D)),null}},[e,t,w]),k=g.useCallback(async(T,D)=>{u(null);try{const P=await t.read(e,T);return await t.setTicketSprint(e,T,D,P.version),await Promise.all([w(),b()]),!0}catch(P){return u(kr(P)),!1}},[e,t,w,b]),N=g.useCallback(async T=>{u(null);try{const D=await t.createSprint(e,T);return await b(),D}catch(D){return u(kr(D)),null}},[e,t,b]),R=g.useCallback(async(T,D)=>{u(null);try{const P=l.find(I=>I.id===T);return P?(await t.renameSprint(e,T,D,P.version),await b(),!0):!1}catch(P){return u(kr(P)),!1}},[e,t,l,b]),L=g.useCallback(async(T,D)=>{u(null);const P=[...l].sort((G,E)=>G.order-E.order),I=P.findIndex(G=>G.id===T),O=D==="up"?I-1:I+1;if(I===-1||O<0||O>=P.length)return!1;const U=[...P];[U[I],U[O]]=[U[O],U[I]];try{return await t.reorderSprints(e,U.map(G=>G.id)),await b(),!0}catch(G){return u(kr(G)),!1}},[e,t,l,b]),S=g.useCallback(async T=>{u(null);try{return await t.deleteSprint(e,T),await Promise.all([w(),b()]),!0}catch(D){return u(kr(D)),!1}},[e,t,w,b]);return g.useEffect(()=>{w()},[w]),g.useEffect(()=>{b()},[b]),g.useEffect(()=>{if(!n)return;let T,D=!1;return n.onDomainEvent(P=>{Ip(P)&&w(),(YS(P)||P.type==="issueSprintChanged")&&b()}).then(P=>{D?P():T=P}),()=>{D=!0,T?.()}},[w,b,n]),{list:i,sprints:l,error:c,busy:h,query:f,setQuery:p,toggleStatus:v,togglePriority:_,clearFacets:y,refresh:w,create:C,assignSprint:k,createSprint:N,renameSprint:R,moveSprint:L,deleteSprint:S}}function ZS(e){const{agent:t}=he(),[n,r]=g.useState([]),[i,s]=g.useState(!1);g.useEffect(()=>{let c=!1;return s(!1),t.listAgents(e).then(u=>{c||(r(u),s(!0))}).catch(()=>{c||(r([]),s(!0))}),()=>{c=!0}},[e,t]);const l=g.useMemo(()=>new Map(n.map(c=>[c.id,c.name])),[n]);return{agents:n,nameOf:c=>l.get(c)??`${c.slice(0,8)}…`,loaded:i}}const Tc=["open","inProgress","QA","closed"],js=["low","medium","high","critical"],e0=["relatesTo","blocks","blockedBy","duplicates","dependsOn"];function Bp(e){switch(e){case"open":return"Open";case"inProgress":return"In progress";case"QA":return"QA";case"closed":return"Closed"}}function Lc(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Dv(e){switch(e){case"relatesTo":return"relates to";case"blocks":return"blocks";case"blockedBy":return"blocked by";case"duplicates":return"duplicates";case"dependsOn":return"depends on"}}function JO(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function ZO(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function t0(e){return q("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function ia({status:e}){return a.jsx("span",{className:t0(JO(e)),children:Bp(e)})}function sa({priority:e}){return a.jsx("span",{className:t0(ZO(e)),children:Lc(e)})}function vs({ticketRef:e,onOpen:t,className:n}){const r=q("inline-flex shrink-0 items-center rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",n);return t?a.jsx("button",{type:"button","aria-label":`open ticket ${e}`,className:q(r,"transition-colors hover:bg-primary/15 hover:text-primary"),onClick:()=>t(e),children:e}):a.jsx("code",{className:r,children:e})}const eB=/#\d+/g;function tB(e,t){const n=[];let r=0,i=0;for(const s of e.matchAll(eB)){const l=s.index??0;l>r&&n.push(e.slice(r,l)),n.push(a.jsx(vs,{ticketRef:s[0],onOpen:t},`ref-${i++}-${l}`)),r=l+s[0].length}return r0||r.length>0;return a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(ce,{"aria-label":"search tickets",placeholder:o,value:e,onChange:d=>t(d.target.value)}),a.jsxs("fieldset",{"aria-label":"filter by status",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[a.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Statut"}),Tc.map(d=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[a.jsx("input",{type:"checkbox","aria-label":`filter status ${Bp(d)}`,className:"accent-primary",checked:n.includes(d),onChange:()=>i(d)}),a.jsx(ia,{status:d})]},d))]}),a.jsxs("fieldset",{"aria-label":"filter by priority",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[a.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Priorité"}),js.map(d=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[a.jsx("input",{type:"checkbox","aria-label":`filter priority ${Lc(d)}`,className:"accent-primary",checked:r.includes(d),onChange:()=>s(d)}),a.jsx(sa,{priority:d})]},d))]}),u&&a.jsxs("div",{"aria-label":"sort tickets",className:"flex flex-wrap items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted",children:["Trier par",a.jsxs("select",{"aria-label":"sort tickets by",className:nB,value:c?.field??"",onChange:d=>{const f=d.target.value;u(f===""?void 0:{field:f,direction:c?.direction??"asc"})},children:[a.jsx("option",{value:"",children:"Par défaut"}),rB.map(d=>a.jsx("option",{value:d,children:n0[d]},d))]})]}),c&&a.jsx(M,{size:"sm",variant:"ghost","aria-label":`sort direction ${c.direction==="asc"?"ascending":"descending"}`,onClick:()=>u({field:c.field,direction:c.direction==="asc"?"desc":"asc"}),children:c.direction==="asc"?"Croissant ↑":"Décroissant ↓"})]}),l&&h&&a.jsx("div",{children:a.jsx(M,{size:"sm",variant:"ghost","aria-label":"clear filters",onClick:l,children:"Effacer"})})]})}function Rv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Dc(e,t={}){const{initialQuery:n,excludeRefs:r,debounceMs:i=200,refreshOnEvents:s,persistenceKey:l}=t,{ticket:o,system:c,uiPreferences:u}=he(),h=g.useRef(null);if(h.current===null){const W=l&&u?JS(u.read(l)):{};h.current={statuses:n?.statuses??W.statuses,priorities:n?.priorities??W.priorities,assignedAgentId:n?.assignedAgentId??W.assignedAgentId,text:n?.text??W.text,sort:n?.sort??W.sort}}const d=h.current,[f,p]=g.useState({statuses:d.statuses,priorities:d.priorities,assignedAgentId:d.assignedAgentId}),[m,x]=g.useState(d.text??""),[w,v]=g.useState(m),[_,y]=g.useState(d.sort),[b,C]=g.useState([]),[k,N]=g.useState(void 0),[R,L]=g.useState(!1),[S,T]=g.useState(null),[D,P]=g.useState(0),I=g.useCallback(()=>P(W=>W+1),[]),O=n?.limit,U=(r??[]).join(","),G=g.useMemo(()=>new Set(r??[]),[U]);g.useEffect(()=>{const W=setTimeout(()=>v(m),i);return()=>clearTimeout(W)},[m,i]),g.useEffect(()=>{if(!l||!u)return;const W=w.trim(),Y=XO({...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...W?{text:W}:{},..._?{sort:_}:{}});Y?u.write(l,Y):u.remove(l)},[l,u,f,w,_]);const E=g.useMemo(()=>JSON.stringify({facets:f,text:w.trim(),sort:_,limit:O}),[f,w,_,O]),z=g.useRef(0),j=g.useCallback(W=>{const Y=w.trim();return{...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...f.assignedAgentId?{assignedAgentId:f.assignedAgentId}:{},...Y?{text:Y}:{},..._?{sort:_}:{},...O?{limit:O}:{},...W?{cursor:W}:{}}},[f,w,_,O]);g.useEffect(()=>{const W=++z.current;L(!0),T(null),o.list(e,j()).then(Y=>{W===z.current&&(C(Y.items),N(Y.nextCursor))}).catch(Y=>{W===z.current&&(T(Rv(Y)),C([]),N(void 0))}).finally(()=>{W===z.current&&L(!1)})},[E,e,o,D]),g.useEffect(()=>{if(!s||!c)return;let W,Y=!1;return c.onDomainEvent(B=>{(Ip(B)||YS(B))&&P(le=>le+1)}).then(B=>{Y?B():W=B}),()=>{Y=!0,W?.()}},[s,c]);const re=g.useCallback(()=>{if(R||!k)return;const W=++z.current;L(!0),T(null),o.list(e,j(k)).then(Y=>{W===z.current&&(C(B=>[...B,...Y.items]),N(Y.nextCursor))}).catch(Y=>{W===z.current&&T(Rv(Y))}).finally(()=>{W===z.current&&L(!1)})},[R,k,o,e,j]),V=g.useCallback(W=>{p(Y=>{const B=Y.statuses??[],le=B.includes(W)?B.filter(je=>je!==W):[...B,W];return{...Y,statuses:le.length>0?le:void 0}})},[]),A=g.useCallback(W=>{p(Y=>{const B=Y.priorities??[],le=B.includes(W)?B.filter(je=>je!==W):[...B,W];return{...Y,priorities:le.length>0?le:void 0}})},[]),ie=g.useCallback(()=>{p(W=>({...W,statuses:void 0,priorities:void 0}))},[]),ee=g.useCallback(async W=>{const Y=await o.read(e,W);return{ref:Y.ref,id:Y.id,number:Y.number,title:Y.title,status:Y.status,priority:Y.priority}},[o,e]);return{rows:g.useMemo(()=>G.size===0?b:b.filter(W=>!G.has(W.ref)),[b,G]),busy:R,error:S,text:m,setText:x,statuses:f.statuses??[],priorities:f.priorities??[],toggleStatus:V,togglePriority:A,clearFacets:ie,sort:_,setSort:y,hasMore:k!==void 0,loadMore:re,refresh:I,resolve:ee}}const Mv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function r0({open:e,projectId:t,title:n="Sélectionner un ticket",confirmLabel:r="Sélectionner",selectionMode:i="single",excludeRefs:s,initialQuery:l,persistFilters:o=!0,onSelect:c,onClose:u}){return e?a.jsx(iB,{projectId:t,title:n,confirmLabel:r,selectionMode:i,excludeRefs:s,initialQuery:l,persistFilters:o,onSelect:c,onClose:u}):null}function iB({projectId:e,title:t,confirmLabel:n,selectionMode:r,excludeRefs:i,initialQuery:s,persistFilters:l,onSelect:o,onClose:c}){const u=Dc(e,{initialQuery:s,excludeRefs:i,persistenceKey:l?KO(e):void 0}),h=g.useRef(null),[d,f]=g.useState(!1),[p,m]=g.useState(null),[x,w]=g.useState(()=>new Set),v=r==="multi";g.useEffect(()=>{const k=document.activeElement,N=h.current;N?.querySelector(Mv)?.focus();function L(S){if(S.key==="Escape"){S.preventDefault(),c();return}if(S.key!=="Tab"||!N)return;const T=Array.from(N.querySelectorAll(Mv)).filter(O=>O.offsetParent!==null||O===document.activeElement);if(T.length===0)return;const D=T[0],P=T[T.length-1],I=document.activeElement;S.shiftKey&&I===D?(S.preventDefault(),P.focus()):!S.shiftKey&&I===P&&(S.preventDefault(),D.focus())}return document.addEventListener("keydown",L),()=>{document.removeEventListener("keydown",L),k?.focus?.()}},[c]);function _(k){return k&&typeof k=="object"&&"message"in k?String(k.message):String(k)}function y(k){w(N=>{const R=new Set(N);return R.has(k)?R.delete(k):R.add(k),R})}async function b(k){if(!d){f(!0),m(null);try{const N=await u.resolve(k);o(N),c()}catch(N){m(_(N)),f(!1)}}}async function C(){if(!(d||x.size===0)){f(!0),m(null);try{const k=await Promise.all(Array.from(x).map(N=>u.resolve(N)));o(k),c()}catch(k){m(_(k)),f(!1)}}}return a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:kn.floatingWindowNested},onMouseDown:k=>{k.target===k.currentTarget&&c()},children:a.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-label":t,className:"flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:t}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"close ticket picker",onClick:c,children:"Close"})]}),a.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:a.jsx(zp,{text:u.text,onTextChange:u.setText,statuses:u.statuses,priorities:u.priorities,onToggleStatus:u.toggleStatus,onTogglePriority:u.togglePriority,onClearFacets:u.clearFacets,sort:u.sort,onSortChange:u.setSort})}),(u.error||p)&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??u.error}),a.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[u.busy&&u.rows.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Loading tickets…"})]}):u.rows.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No matching tickets."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.rows.map(k=>{const N=x.has(k.ref);return a.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:a.jsxs("button",{type:"button","aria-label":`select ticket ${k.ref}`,...v?{role:"checkbox","aria-checked":N}:{},disabled:d,onClick:()=>v?y(k.ref):void b(k.ref),className:q("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none","disabled:cursor-not-allowed disabled:opacity-60",v&&N&&"bg-raised"),children:[v&&a.jsx("span",{"aria-hidden":"true",className:q("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",N?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),a.jsx(vs,{ticketRef:k.ref,className:"mt-0.5"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:k.title}),a.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[a.jsx(ia,{status:k.status}),a.jsx(sa,{priority:k.priority})]})]})},k.ref)})}),u.hasMore&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:u.busy,onClick:()=>u.loadMore(),children:"Load more"})})]}),v&&a.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3",children:[a.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[x.size," sélectionné",x.size>1?"s":""]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel ticket selection",onClick:c,children:"Annuler"}),a.jsx(M,{size:"sm","aria-label":"confirm ticket selection",loading:d,disabled:x.size===0||d,onClick:()=>void C(),children:x.size>0?`${n} (${x.size})`:n})]})]})]})})}function sB({projectId:e,vm:t,onClose:n}){const r=Dc(e,{refreshOnEvents:!0}),i=r.rows,s=[...t.sprints].sort((x,w)=>x.order-w.order),[l,o]=g.useState(""),[c,u]=g.useState({}),[h,d]=g.useState(null),[f,p]=g.useState(null);async function m(x){x.preventDefault();const w=l.trim()||`Sprint ${s.length+1}`;await t.createSprint(w)&&o("")}return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"manage sprints",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:"Manage sprints"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"Close"})]}),t.error&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-5 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex-1 overflow-auto p-5",children:[a.jsxs("form",{onSubmit:m,className:"mb-5 flex items-center gap-2 rounded-md border border-border bg-raised/50 p-2",children:[a.jsx(ce,{"aria-label":"new sprint name",placeholder:"Sprint name (optional)",value:l,onChange:x=>o(x.target.value),className:"max-w-xs"}),a.jsx(M,{type:"submit",size:"sm",disabled:t.busy,children:"Create sprint"})]}),a.jsx("div",{className:"mb-5",children:a.jsx(zp,{text:r.text,onTextChange:r.setText,statuses:r.statuses,priorities:r.priorities,onToggleStatus:r.toggleStatus,onTogglePriority:r.togglePriority,onClearFacets:r.clearFacets,sort:r.sort,onSortChange:r.setSort})}),r.error&&a.jsx("p",{role:"alert",className:"mb-4 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),s.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No sprints yet."}):a.jsx("ul",{className:"flex flex-col gap-4",children:s.map((x,w)=>{const v=i.filter(y=>y.sprintId===x.id),_=c[x.id]??x.name;return a.jsxs("li",{"aria-label":`sprint row ${x.name}`,className:"rounded-md border border-border p-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",x.order]}),a.jsx(ce,{"aria-label":`rename sprint ${x.name}`,value:_,disabled:t.busy,onChange:y=>u(b=>({...b,[x.id]:y.target.value})),className:"max-w-xs"}),a.jsx(M,{size:"sm","aria-label":`save sprint ${x.name}`,disabled:t.busy||_.trim()===""||_.trim()===x.name,onClick:async()=>{await t.renameSprint(x.id,_.trim())&&u(b=>{const{[x.id]:C,...k}=b;return k})},children:"Save"}),a.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} up`,disabled:t.busy||w===0,onClick:()=>void t.moveSprint(x.id,"up"),children:"↑"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} down`,disabled:t.busy||w===s.length-1,onClick:()=>void t.moveSprint(x.id,"down"),children:"↓"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete sprint ${x.name}`,disabled:t.busy,className:"text-danger hover:text-danger",onClick:()=>d({id:x.id,name:x.name}),children:"Delete"})]})]}),a.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[v.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No tickets in this sprint."}):a.jsx("ul",{className:"flex flex-col gap-1",children:v.map(y=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx(vs,{ticketRef:y.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:y.title}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[a.jsx(ia,{status:y.status}),a.jsx(sa,{priority:y.priority})]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`remove ${y.ref} from sprint`,disabled:t.busy,onClick:()=>void t.assignSprint(y.ref,null),children:"Remove"})]},y.ref))}),a.jsx("div",{className:"mt-1",children:a.jsx(M,{size:"sm",variant:"ghost","aria-label":`add ticket to sprint ${x.name}`,disabled:t.busy,onClick:()=>p({id:x.id,name:x.name}),children:"Ajouter des tickets"})})]})]},x.id)})}),r.hasMore&&a.jsx("div",{className:"mt-4 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:r.busy,onClick:()=>r.loadMore(),children:"Load more tickets"})})]}),h&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"delete sprint confirmation",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Supprimer le sprint « ",h.name," » ?"]}),a.jsx("p",{className:"mt-2 text-sm text-muted",children:"Les tickets de ce sprint ne seront pas supprimés : ils seront simplement désassignés et retourneront au backlog « Sans sprint »."}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete sprint",disabled:t.busy,onClick:()=>d(null),children:"Annuler"}),a.jsx(M,{size:"sm","aria-label":"confirm delete sprint",className:"text-danger hover:text-danger",disabled:t.busy,onClick:async()=>{await t.deleteSprint(h.id),d(null)},children:"Supprimer"})]})]})}),a.jsx(r0,{open:f!==null,projectId:e,title:f?`Ajouter des tickets au sprint « ${f.name} »`:"Ajouter des tickets",confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:i.filter(x=>x.sprintId===f?.id).map(x=>x.ref),onSelect:x=>{const w=Array.isArray(x)?x:[x];if(f)for(const v of w)t.assignSprint(v.ref,f.id)},onClose:()=>p(null)})]})}const Iv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function lB({open:e,projectId:t,selectedSprintId:n,title:r="Sélectionner un sprint",onSelect:i,onClose:s}){return e?a.jsx(oB,{projectId:t,selectedSprintId:n??null,title:r,onSelect:i,onClose:s}):null}function aB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function oB({projectId:e,selectedSprintId:t,title:n,onSelect:r,onClose:i}){const{ticket:s}=he(),l=g.useRef(null),[o,c]=g.useState(null),[u,h]=g.useState(null);g.useEffect(()=>{let p=!1;return h(null),s.listSprints(e).then(m=>{p||c(m)}).catch(m=>{p||(h(aB(m)),c([]))}),()=>{p=!0}},[s,e]),g.useEffect(()=>{const p=document.activeElement,m=l.current;m?.querySelector(Iv)?.focus();function w(v){if(v.key==="Escape"){v.preventDefault(),i();return}if(v.key!=="Tab"||!m)return;const _=Array.from(m.querySelectorAll(Iv)).filter(k=>k.offsetParent!==null||k===document.activeElement);if(_.length===0)return;const y=_[0],b=_[_.length-1],C=document.activeElement;v.shiftKey&&C===y?(v.preventDefault(),b.focus()):!v.shiftKey&&C===b&&(v.preventDefault(),y.focus())}return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w),p?.focus?.()}},[i]);const d=o?[...o].sort((p,m)=>p.order-m.order):[];function f(p){r(p),i()}return a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:kn.floatingWindowNested},onMouseDown:p=>{p.target===p.currentTarget&&i()},children:a.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":n,className:"flex max-h-[80vh] w-full max-w-sm flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:n}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"close sprint picker",onClick:i,children:"Close"})]}),u&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:u}),a.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[a.jsxs("ul",{className:"flex flex-col divide-y divide-border",children:[a.jsx("li",{className:"py-1.5 first:pt-0",children:a.jsx(Ov,{label:"Sans sprint",ariaLabel:"select no sprint",selected:t===null,onClick:()=>f(null)})}),o===null?a.jsxs("li",{className:"flex items-center gap-2 py-2 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Loading sprints…"})]}):d.map(p=>a.jsx("li",{className:"py-1.5 last:pb-0",children:a.jsx(Ov,{label:p.name,ariaLabel:`select sprint ${p.name}`,count:p.ticketCount,selected:t===p.id,onClick:()=>f(p)})},p.id))]}),o!==null&&d.length===0&&!u&&a.jsx("p",{className:"mt-2 text-sm text-muted",children:"No sprints yet."})]})]})})}function Ov({label:e,ariaLabel:t,count:n,selected:r,onClick:i}){return a.jsxs("button",{type:"button",role:"option","aria-selected":r,"aria-label":t,onClick:i,className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none",r&&"bg-raised"),children:[a.jsx("span",{"aria-hidden":"true",className:q("flex h-4 w-4 shrink-0 items-center justify-center text-[10px] font-bold",r?"text-primary":"text-transparent"),children:"✓"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e}),n!==void 0&&a.jsx("span",{className:"shrink-0 rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:n})]})}const Zh=q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function cB({projectId:e,onOpen:t}){const n=Op(e),{agents:r,nameOf:i,loaded:s}=ZS(e);g.useEffect(()=>{if(!s)return;const N=n.query.assignedAgentId;if(N&&!r.some(R=>R.id===N)){const{assignedAgentId:R,...L}=n.query;n.setQuery(L)}},[s,r,n.query,n.setQuery]);const[l,o]=g.useState(!1),[c,u]=g.useState(!1),[h,d]=g.useState(""),[f,p]=g.useState("medium"),[m,x]=g.useState(null),[w,v]=g.useState(!1),_=n.list?.items??[],y=new Set(n.sprints.map(N=>N.id)),b=n.sprints.map(N=>({sprint:N,tickets:_.filter(R=>R.sprintId===N.id)})).filter(N=>N.tickets.length>0),C=_.filter(N=>!N.sprintId||!y.has(N.sprintId));async function k(N){if(N.preventDefault(),!h.trim())return;const R=await n.create({title:h.trim(),priority:f});R&&(m&&await n.assignSprint(R.ref,m.id),d(""),p("medium"),x(null),o(!1),t(R.ref))}return a.jsxs(we,{title:"Tickets",actions:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>o(N=>!N),children:l?"Cancel":"New"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"manage sprints",onClick:()=>u(!0),children:"Sprints"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"})]}),children:[n.error&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),l&&a.jsxs("form",{onSubmit:k,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[a.jsx(ce,{"aria-label":"new ticket title",placeholder:"Ticket title",value:h,onChange:N=>d(N.target.value)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("select",{"aria-label":"new ticket priority",className:Zh,value:f,onChange:N=>p(N.target.value),children:js.map(N=>a.jsx("option",{value:N,children:Lc(N)},N))}),a.jsx(M,{type:"submit",size:"sm",disabled:!h.trim()||n.busy,children:"Create"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-muted",children:"Sprint"}),a.jsx(M,{type:"button",size:"sm",variant:"ghost","aria-label":"choose sprint for new ticket",disabled:n.busy,onClick:()=>v(!0),className:"border border-border",children:m?m.name:"Sans sprint"})]})]}),a.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[a.jsx(zp,{text:n.query.text??"",onTextChange:N=>n.setQuery({...n.query,text:N||void 0}),statuses:n.query.statuses??[],priorities:n.query.priorities??[],onToggleStatus:n.toggleStatus,onTogglePriority:n.togglePriority,onClearFacets:n.clearFacets,sort:n.query.sort,onSortChange:N=>{const{sort:R,...L}=n.query;n.setQuery(N?{...L,sort:N}:L)}}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:a.jsxs("select",{"aria-label":"filter by assignee",className:Zh,value:n.query.assignedAgentId??"",onChange:N=>n.setQuery({...n.query,assignedAgentId:N.target.value||void 0}),children:[a.jsx("option",{value:"",children:"All assignees"}),r.map(N=>a.jsx("option",{value:N.id,children:N.name},N.id))]})})]}),n.busy&&n.list===null?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Loading tickets…"})]}):_.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No tickets."}):a.jsxs("div",{className:"flex flex-col gap-4",children:[b.map(N=>a.jsx(Bv,{heading:N.sprint.name,count:N.tickets.length,tickets:N.tickets,sprints:n.sprints,onOpen:t,nameOf:i,onAssignSprint:n.assignSprint},N.sprint.id)),C.length>0&&a.jsx(Bv,{heading:"Sans sprint",count:C.length,tickets:C,sprints:n.sprints,onOpen:t,nameOf:i,onAssignSprint:n.assignSprint})]}),n.list?.nextCursor&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Load more"})}),c&&a.jsx(sB,{projectId:e,vm:n,onClose:()=>u(!1)}),a.jsx(lB,{open:w,projectId:e,selectedSprintId:m?.id??null,title:"Sprint du nouveau ticket",onSelect:N=>x(N),onClose:()=>v(!1)})]})}function Bv({heading:e,count:t,tickets:n,sprints:r,onOpen:i,nameOf:s,onAssignSprint:l}){return a.jsxs("section",{"aria-label":`sprint section ${e}`,children:[a.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,a.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t})]}),a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.map(o=>a.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(vs,{ticketRef:o.ref,onOpen:i,className:"mt-0.5"}),a.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>i(o.ref),children:[a.jsx("span",{className:"block truncate text-sm font-medium text-content hover:underline",children:o.title}),o.assignedAgentIds.length>0&&a.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted",children:o.assignedAgentIds.map(s).join(", ")})]}),a.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[a.jsx(ia,{status:o.status}),a.jsx(sa,{priority:o.priority})]})]}),a.jsx("div",{className:"mt-1 pl-6",children:a.jsxs("select",{"aria-label":`sprint for ${o.ref}`,className:Zh,value:o.sprintId??"",onChange:c=>l(o.ref,c.target.value||null),children:[a.jsx("option",{value:"",children:"— No sprint —"}),r.map(c=>a.jsx("option",{value:c.id,children:c.name},c.id))]})})]},o.ref))})]})}function Ha(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function uB(e){return!!e&&typeof e=="object"&&typeof e.message=="string"&&e.message.includes("version conflict")}function i0(e,t){const{ticket:n,system:r}=he(),[i,s]=g.useState(null),[l,o]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(0),w=g.useCallback(async()=>{p(!0),o(null);try{s(await n.read(e,t,!0)),u(!1),x(L=>L+1)}catch(L){o(Ha(L))}finally{p(!1)}},[e,t,n]);g.useEffect(()=>{w()},[w]),g.useEffect(()=>{if(!r)return;let L,S=!1;return r.onDomainEvent(T=>{if(T.type==="issueDeleted"&&T.issueRef===t){d(!0);return}Ip(T)&&T.issueRef===t&&w()}).then(T=>{S?T():L=T}),()=>{S=!0,L?.()}},[w,r,t]);const v=g.useCallback(async(L,S)=>{if(!i)return!1;p(!0),o(null);try{const T=await L(i.version);return s({...T,carnet:S!==void 0?S:i.carnet}),u(!1),!0}catch(T){if(uB(T)){o("This ticket was modified elsewhere. It has been reloaded — re-apply your change.");try{s(await n.read(e,t,!0))}catch(D){o(Ha(D))}u(!0),x(D=>D+1)}else o(Ha(T));return!1}finally{p(!1)}},[i,n,e,t]),_=g.useCallback(L=>v(S=>n.update(e,t,{...L,expectedVersion:S})),[v,n,e,t]),y=g.useCallback(L=>v(S=>n.updateCarnet(e,t,L,S),L),[v,n,e,t]),b=g.useCallback((L,S)=>v(T=>n.link(e,t,L,S,T)),[v,n,e,t]),C=g.useCallback((L,S)=>v(T=>n.unlink(e,t,L,T,S)),[v,n,e,t]),k=g.useCallback((L,S)=>v(T=>n.assign(e,t,L,S,T)),[v,n,e,t]),N=g.useCallback(L=>v(S=>n.setTicketSprint(e,t,L,S)),[v,n,e,t]),R=g.useCallback(async()=>{p(!0),o(null);try{return await n.delete(e,t),!0}catch(L){return o(Ha(L)),!1}finally{p(!1)}},[n,e,t]);return{ticket:i,error:l,conflict:c,deleted:h,busy:f,reloadCount:m,refresh:w,updateFields:_,saveCarnet:y,link:b,unlink:C,assign:k,setSprint:N,remove:R}}function Ua(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function dB(e,t){const{ticket:n,profile:r}=he(),[i,s]=g.useState([]),[l,o]=g.useState(null),[c,u]=g.useState([]),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef(null);w.current=l,g.useEffect(()=>{let b=!1;return(async()=>{try{const C=await r?.listProfiles()??[];b||s(C)}catch(C){b||x(Ua(C))}})(),()=>{b=!0}},[r]);const v=g.useCallback(async b=>{if(b){d(!0),x(null);try{const C=await n.openTicketChat(e,t,b);o(C.sessionId),u([])}catch(C){x(Ua(C))}finally{d(!1)}}},[n,e,t]),_=g.useCallback(async()=>{if(w.current){o(null),u([]);try{await n.closeTicketChat(e,t)}catch(b){x(Ua(b))}}},[n,e,t]),y=g.useCallback(async b=>{const C=b.trim();if(!l||!C||f)return;x(null),p(!0),u(N=>[...N,{role:"user",text:C},{role:"assistant",text:"",pending:!0}]);const k=N=>{u(R=>{const L=[...R],S=L.length-1;return S<0||L[S].role!=="assistant"?R:(N.kind==="textDelta"?L[S]={...L[S],text:L[S].text+N.text}:N.kind==="toolActivity"?L[S]={...L[S],text:`${L[S].text} -· ${N.label}`}:N.kind==="error"?L[S]={role:"assistant",text:`⚠️ ${N.message}`,pending:!1}:L[S]={role:"assistant",text:N.content,pending:!1},L)}),(N.kind==="final"||N.kind==="error")&&p(!1)};try{await n.sendTicketChat(l,C,k)}catch(N){x(Ua(N)),u(R=>{const L=[...R],S=L.length-1;return S>=0&&L[S].role==="assistant"&&L[S].pending&&(L[S]={...L[S],pending:!1}),L}),p(!1)}},[n,l,f]);return g.useEffect(()=>()=>{w.current&&n.closeTicketChat(e,t).catch(()=>{})},[n,e,t]),{profiles:i,sessionId:l,turns:c,opening:h,busy:f,error:m,open:v,close:_,send:y}}const hB=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function fB({projectId:e,ticketRef:t}){const n=dB(e,t),[r,i]=g.useState(""),[s,l]=g.useState(""),o=g.useRef(null);g.useEffect(()=>{const h=o.current;h&&(h.scrollTop=h.scrollHeight)},[n.turns]);const c=n.sessionId!==null;function u(){const h=s.trim();!h||n.busy||(n.send(h),l(""))}return a.jsxs("div",{className:"flex flex-col gap-3",children:[c?a.jsxs("div",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-xs text-muted",children:"Conversation ouverte — l'assistant peut lire le projet et éditer ce ticket."}),a.jsx(M,{size:"sm",variant:"ghost",disabled:n.busy,onClick:()=>void n.close(),children:"Fermer la conversation"})]}),a.jsx("div",{ref:o,className:"flex max-h-96 min-h-32 flex-col gap-2 overflow-auto rounded-md border border-border bg-raised/40 p-3",children:n.turns.length===0?a.jsx("p",{className:"m-auto text-xs text-muted",children:"Démarrez la conversation en décrivant ce que l'assistant doit faire sur ce ticket."}):n.turns.map((h,d)=>a.jsx("div",{className:q("flex",h.role==="user"?"justify-end":"justify-start"),children:a.jsxs("div",{className:q("max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm",h.role==="user"?"bg-primary/15 text-content":"bg-surface text-content"),children:[h.text,h.pending&&a.jsx("span",{className:"ml-1 inline-flex items-center align-middle text-muted",children:a.jsx(Re,{size:12})})]})},d))}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsx("textarea",{"aria-label":"message à l'assistant",className:q("min-h-10 flex-1 resize-none rounded-md bg-raised p-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),rows:2,placeholder:"Votre message…",value:s,disabled:n.busy,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),u())}}),a.jsx(M,{size:"sm",disabled:!s.trim()||n.busy,loading:n.busy,onClick:u,children:"Envoyer"})]})]}):a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("select",{"aria-label":"profil de l'assistant",className:hB,value:r,disabled:n.opening||n.profiles.length===0,onChange:h=>i(h.target.value),children:[a.jsx("option",{value:"",children:n.profiles.length===0?"Aucun profil disponible":"Choisir un profil IA…"}),n.profiles.map(h=>a.jsx("option",{value:h.id,children:h.name},h.id))]}),a.jsx(M,{size:"sm",disabled:!r||n.opening,loading:n.opening,onClick:()=>void n.open(r),children:"Ouvrir la conversation"})]}),n.error&&a.jsx("p",{role:"alert",className:"text-xs text-danger",children:n.error})]})}const qa=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),zv=q("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");async function pB(e){return typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):!1}function Zs({title:e,hint:t,children:n}){return a.jsxs("section",{className:"flex flex-col gap-2 border-b border-border px-5 py-4",children:[a.jsxs("div",{children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:e}),t&&a.jsx("p",{className:"mt-0.5 text-xs text-muted",children:t})]}),n]})}function mB({projectId:e,ticketRef:t,onClose:n,onOpenRef:r}){const i=i0(e,t),{agents:s,nameOf:l}=ZS(e),o=i.ticket,[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState("relatesTo"),[w,v]=g.useState(""),[_,y]=g.useState(!1),[b,C]=g.useState(!1),[k,N]=g.useState(!1),[R,L]=g.useState(!1),[S,T]=g.useState(!1);g.useEffect(()=>{i.deleted&&n()},[i.deleted,n]);const D=i.reloadCount,P=g.useRef(-1),I=g.useRef(null);g.useEffect(()=>{if(!o||P.current===D)return;P.current=D;const V=o.carnet??"",A=I.current;A===null||i.conflict?(u(o.title),d(o.description),p(V)):(u(ee=>ee===A.title?o.title:ee),d(ee=>ee===A.description?o.description:ee),p(ee=>ee===A.carnet?V:ee)),I.current={title:o.title,description:o.description,carnet:V}},[o,D,i.conflict]);const O=!!o&&(c!==o.title||h!==o.description),U=!!o&&f!==(o.carnet??""),G=O||U,E=s.filter(V=>!o?.assignedAgentIds.includes(V.id));function z(){G?C(!0):n()}async function j(){let V=!0;O&&(V=await i.updateFields({title:c,description:h})&&V),V&&U&&(V=await i.saveCarnet(f)&&V),C(!1),V&&n()}async function re(){if(!o)return;await pB(`Travaille sur le ticket ${o.ref} : ${o.title}`)&&(y(!0),window.setTimeout(()=>y(!1),1200))}return a.jsxs(Bh,{open:!0,title:`ticket ${t}`,size:"xl",onClose:z,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(vs,{ticketRef:t}),o&&a.jsx(ia,{status:o.status}),o&&a.jsx(sa,{priority:o.priority}),a.jsx("span",{className:"truncate text-sm font-medium text-content",children:o?.title??t})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:!o,onClick:()=>void re(),title:"Copy a delegation prompt to hand this ticket to an agent",children:_?"Copied":"Delegation context"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!o||i.busy,onClick:()=>N(!0),className:"text-danger hover:text-danger",title:"Supprimer définitivement ce ticket",children:"Supprimer"})]})]}),i.conflict&&a.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-1 py-2 text-sm text-warning",children:"This ticket was modified elsewhere and reloaded. Re-apply your change."}),i.error&&!i.conflict&&a.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-1 py-2 text-sm text-danger",children:i.error}),i.busy&&!o?a.jsxs("div",{className:"flex items-center gap-2 py-5 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Loading ticket…"})]}):o?a.jsxs("div",{className:"-mx-4",children:[a.jsxs(Zs,{title:"Details",children:[a.jsx("label",{className:"text-xs font-medium text-muted",htmlFor:"td-title",children:"Title"}),a.jsx(ce,{id:"td-title",value:c,onChange:V=>u(V.target.value),disabled:i.busy}),a.jsx("label",{className:"mt-2 text-xs font-medium text-muted",htmlFor:"td-desc",children:"Description"}),a.jsx("textarea",{id:"td-desc",className:q(zv,"min-h-24"),value:h,onChange:V=>d(V.target.value),disabled:i.busy}),h.trim()&&a.jsx("p",{className:"whitespace-pre-wrap break-words rounded-md bg-raised/40 px-3 py-2 text-xs text-muted",children:tB(h,r)}),a.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[a.jsx(M,{size:"sm",disabled:!O||i.busy,loading:i.busy&&O,onClick:()=>void i.updateFields({title:c,description:h}),children:"Save changes"}),O&&a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:()=>{u(o.title),d(o.description)},children:"Reset"})]})]}),a.jsx(Zs,{title:"Status & priority",children:a.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[a.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Status",a.jsx("select",{"aria-label":"ticket status",className:qa,value:o.status,disabled:i.busy,onChange:V=>void i.updateFields({status:V.target.value}),children:Tc.map(V=>a.jsx("option",{value:V,children:Bp(V)},V))})]}),a.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Priority",a.jsx("select",{"aria-label":"ticket priority",className:qa,value:o.priority,disabled:i.busy,onChange:V=>void i.updateFields({priority:V.target.value}),children:js.map(V=>a.jsx("option",{value:V,children:Lc(V)},V))})]})]})}),a.jsxs(Zs,{title:"Carnet",hint:"Markdown notebook scoped to this ticket only — separate from project memory. Saving replaces the whole carnet.",children:[a.jsx("textarea",{"aria-label":"ticket carnet",className:q(zv,"min-h-40 font-mono"),value:f,onChange:V=>p(V.target.value),disabled:i.busy}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(M,{size:"sm",disabled:!U||i.busy,loading:i.busy&&U,onClick:()=>void i.saveCarnet(f),children:"Save carnet"}),U&&a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:()=>p(o.carnet??""),children:"Reset"})]})]}),a.jsxs(Zs,{title:"Linked tickets",children:[o.links.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No linked tickets."}):a.jsx("ul",{className:"flex flex-col gap-1",children:o.links.map(V=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-xs text-muted",children:Dv(V.kind)}),a.jsx(vs,{ticketRef:V.targetRef,onOpen:r}),a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:()=>void i.unlink(V.targetRef,V.kind),children:"Remove"})]},`${V.kind}-${V.targetRef}`))}),a.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[a.jsx("select",{"aria-label":"link kind",className:qa,value:m,disabled:i.busy,onChange:V=>x(V.target.value),children:e0.map(V=>a.jsx("option",{value:V,children:Dv(V)},V))}),a.jsx(M,{size:"sm","aria-label":"add link",disabled:i.busy,onClick:()=>L(!0),children:"Add link"})]})]}),a.jsxs(Zs,{title:"Assigned agents",hint:"Only agents known to this project can be assigned.",children:[o.assignedAgentIds.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No agents assigned."}):a.jsx("ul",{className:"flex flex-wrap gap-2",children:o.assignedAgentIds.map(V=>a.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[l(V),a.jsx("button",{type:"button","aria-label":`unassign ${l(V)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:i.busy,onClick:()=>void i.assign(V,!1),children:"×"})]},V))}),a.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[a.jsxs("select",{"aria-label":"assign agent",className:qa,value:w,disabled:i.busy||E.length===0,onChange:V=>v(V.target.value),children:[a.jsx("option",{value:"",children:E.length===0?"No more agents":"Select an agent…"}),E.map(V=>a.jsx("option",{value:V.id,children:V.name},V.id))]}),a.jsx(M,{size:"sm",disabled:!w||i.busy,onClick:async()=>{await i.assign(w,!0)&&v("")},children:"Assign"})]})]}),a.jsx(r0,{open:R,projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...o.links.map(V=>V.targetRef)],onSelect:V=>{const A=Array.isArray(V)?V[0]:V;A&&i.link(A.ref,m),L(!1)},onClose:()=>L(!1)})]}):a.jsx("div",{className:"flex items-center justify-center py-10 text-sm text-muted",children:"Ticket not found."}),o&&a.jsx("div",{className:"pointer-events-none sticky bottom-0 z-10 -mx-4 -mb-4 flex justify-end px-4 pb-4 pt-2",children:a.jsx(M,{"aria-label":"ouvrir l'assistant IA",className:"pointer-events-auto shadow-lg",onClick:()=>T(!0),children:"🤖 Assistant IA"})}),a.jsx(Bh,{open:S,title:`Assistant IA — ${t}`,size:"lg",onClose:()=>T(!1),children:a.jsx(fB,{projectId:e,ticketRef:t})}),b&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"unsaved changes",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsx("h4",{className:"text-sm font-semibold text-content",children:"Modifications non sauvegardées"}),a.jsx("p",{className:"mt-2 text-sm text-muted",children:"Vous avez des modifications non sauvegardées. Voulez-vous les sauvegarder avant de fermer ?"}),a.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel close",disabled:i.busy,onClick:()=>C(!1),children:"Annuler"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"close without saving",disabled:i.busy,onClick:n,className:"text-danger hover:text-danger",children:"Fermer sans sauvegarder"}),a.jsx(M,{size:"sm","aria-label":"save and close",loading:i.busy,disabled:i.busy,onClick:()=>void j(),children:"Sauvegarder"})]})]})}),k&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"confirmer la suppression",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsx("h4",{className:"text-sm font-semibold text-content",children:"Supprimer le ticket"}),a.jsxs("p",{className:"mt-2 text-sm text-muted",children:["Supprimer définitivement le ticket ",t," ? Cette action est irréversible."]}),a.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete",disabled:i.busy,onClick:()=>N(!1),children:"Annuler"}),a.jsx(M,{size:"sm",variant:"danger","aria-label":"confirm delete",loading:i.busy,disabled:i.busy,onClick:async()=>{await i.remove()&&N(!1)},children:"Supprimer"})]})]})})]})}function gB({projectId:e}){const[t,n]=g.useState(null);return a.jsxs(a.Fragment,{children:[a.jsx(cB,{projectId:e,onOpen:n}),t&&a.jsx(mB,{projectId:e,ticketRef:t,onClose:()=>n(null),onOpenRef:n},`${e}-${t}`)]})}function Fv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function s0({projectId:e}){const{project:t}=he(),[n,r]=g.useState(""),[i,s]=g.useState(""),[l,o]=g.useState(!1),[c,u]=g.useState(null);g.useEffect(()=>{let f=!1;return o(!0),u(null),t.readProjectContext(e).then(p=>{f||(r(p),s(p))}).catch(p=>{f||u(Fv(p))}).finally(()=>{f||o(!1)}),()=>{f=!0}},[t,e]);async function h(){o(!0),u(null);try{await t.updateProjectContext(e,n),s(n)}catch(f){u(Fv(f))}finally{o(!1)}}const d=n!==i;return a.jsxs(we,{title:"Project Context",className:"flex flex-col gap-0",children:[c&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:c}),a.jsx("div",{className:"border-b border-border px-4 py-2",children:a.jsx("code",{className:"text-xs text-muted",children:".ideai/CONTEXT.md"})}),a.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[a.jsx("textarea",{"aria-label":"project context",value:n,onChange:f=>r(f.target.value),rows:18,className:q("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:l}),a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l&&a.jsx(Re,{size:14}),a.jsx(M,{variant:"primary",disabled:l||!d,onClick:()=>void h(),children:"Save"})]})]})]})}function l0({panel:e,projectId:t,projectRoot:n,onOpenConversation:r}){switch(e){case"context":return a.jsx(s0,{projectId:t});case"work":return a.jsx(nT,{projectId:t,onOpenConversation:r});case"tickets":return a.jsx(gB,{projectId:t});case"agents":return a.jsx(xw,{projectId:t,projectRoot:n});case"templates":return a.jsx(zS,{projectId:t});case"skills":return a.jsx(FS,{projectId:t});case"permissions":return a.jsx(GS,{projectId:t});case"memory":return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx(qS,{projectId:t}),a.jsx(US,{})]});case"git":return a.jsx(Tw,{projectId:t})}}const Hn={projects:"Projects",context:"Project context",work:"Work state",tickets:"Tickets",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Memory",git:"Git"};function Tr(e,t){return e[t]??"closed"}function li(e,t){return typeof e=="object"&&e.dock===t}function $v(e,t){return Object.keys(Hn).filter(n=>li(Tr(e,n),t))}function xB(e){return Object.keys(Hn).filter(t=>Tr(e,t)==="floating")}function td(e){return e==="detached"}function vB(e){return e!=="projects"&&e in Hn}function _B(e,t){let n=!1;const r={...e};for(const i of t){if(!i.visible||!vB(i.panel))continue;const s=i.panel;Tr(e,s)==="closed"&&(r[s]="detached",n=!0)}return n?r:e}const yB={projects:"md",context:"lg",work:"lg",tickets:"lg",agents:"lg",templates:"lg",skills:"lg",permissions:"md",memory:"lg",git:"lg"};function bB(e){return e.type==="backgroundTaskChanged"&&(e.state==="completed"||e.state==="failed"||e.state==="cancelled"||e.state==="delivered")}function wB(){const e=kL(),{system:t,window:n,focusedProject:r,git:i}=he(),[s,l]=g.useState(""),[o,c]=g.useState(""),[u,h]=g.useState({}),[d,f]=g.useState(340),[p,m]=g.useState(340),[x,w]=g.useState(null),[v,_]=g.useState(null),[y,b]=g.useState(null),[C,k]=g.useState([]),N=e.openTabs.find($=>$.id===e.activeTabId)??null,[R,L]=g.useState(!1);g.useEffect(()=>{if(!N){L(!1);return}let $=!1;return i.branches(N.id).then(()=>{$||L(!0)}).catch(()=>{$||L(!1)}),()=>{$=!0}},[i,N?.id]);const{registry:S}=pp(),D=pA(S,{projectOpen:N!==null,gitRepository:R,agentSelected:!1,terminalFocused:!1,layoutCellFocused:!1});g.useEffect(()=>{_(null),b(null)},[N?.id]),g.useEffect(()=>{r?.setFocusedProject(N?{id:N.id,name:N.name,root:N.root}:null)},[r,N?.id,N?.name,N?.root]),g.useEffect(()=>{let $,ge=!1;return t.onDomainEvent(de=>{if(!bB(de))return;const Ne={id:`${de.taskId}-${de.state}-${Date.now()}`,projectId:de.projectId,agentId:de.agentId,taskId:de.taskId,state:de.state};k(_t=>[..._t.slice(-2),Ne]),window.setTimeout(()=>{k(_t=>_t.filter(Xr=>Xr.id!==Ne.id))},7e3)}).then(de=>{ge?de():$=de}),()=>{ge=!0,$?.()}},[t]);const P=v?.kind??"terminal",I=s.trim().length>0&&o.trim().length>0&&!e.busy;async function O($){$.preventDefault(),I&&(await e.createProject(s.trim(),o.trim()),l(""),c(""))}async function U(){const $=await t.pickFolder();$!==null&&c($)}function G($,ge){h(de=>{const Ne={...de};if(ge==="floating")for(const _t of Object.keys(Ne))_t!==$&&Ne[_t]==="floating"&&delete Ne[_t];return Ne[$]=ge,Ne})}function E($){h(ge=>{if(!($ in ge))return ge;const de={...ge};return delete de[$],de})}function z(){h($=>{let ge=!1;const de={...$};for(const Ne of Object.keys(de))de[Ne]==="floating"&&(delete de[Ne],ge=!0);return ge?de:$})}function j($){N&&n.openViewWindow($).then(()=>G($,"detached")).catch(()=>{})}g.useEffect(()=>{let $,ge=!1;return n.onViewWindowClosed(({panel:de})=>{h(Ne=>Ne[de]==="detached"?(()=>{const _t={...Ne};return delete _t[de],_t})():Ne)}).then(de=>{ge?de():$=de}),()=>{ge=!0,$?.()}},[n]),g.useEffect(()=>{let $=!1;return n.listOpenViewWindows().then(ge=>{$||h(de=>_B(de,ge))}).catch(()=>{}),()=>{$=!0}},[n]);function re($){b($),z()}const V=["context","work","tickets","agents","templates","skills","permissions","memory","git","projects"];function A($){const ge=Tr(u,$),de=[{id:"closed",label:"Fermé",active:ge==="closed",onSelect:()=>E($)},{id:"floating",label:"Flottant",active:ge==="floating",onSelect:()=>G($,"floating")},{id:"dock-left",label:"Ancré à gauche",active:li(ge,"left"),onSelect:()=>G($,{dock:"left"})},{id:"dock-right",label:"Ancré à droite",active:li(ge,"right"),onSelect:()=>G($,{dock:"right"})}];return $!=="projects"&&de.push({id:"detached",label:"Fenêtre détachée",active:td(ge),disabled:!N,onSelect:()=>j($)}),de}const ie=[{id:"panels",label:"Panneaux",items:[...V.map($=>({id:$,label:Hn[$],active:Tr(u,$)!=="closed",onSelect:()=>{},submenu:A($)})),...D.itemsFor("panels")]},...D.topLevelMenus,{id:"settings",label:"Paramètres",items:[...Pw.map($=>({id:$,label:Ew[$],active:x===$,onSelect:()=>{w($),z()}})),...D.itemsFor("settings")]}],ee=a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("form",{onSubmit:O,className:"flex flex-col gap-2",children:[a.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"New project"}),a.jsx(ce,{"aria-label":"project name",placeholder:"Project name",value:s,onChange:$=>l($.target.value)}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(ce,{"aria-label":"project root",placeholder:"/absolute/project/root",value:o,onChange:$=>c($.target.value),className:"flex-1"}),a.jsx(M,{type:"button","aria-label":"browse project folder",onClick:()=>void U(),disabled:e.busy,children:"Browse…"})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{type:"submit",variant:"primary",disabled:!I,className:"flex-1",children:"Create project"}),a.jsx(M,{type:"button",onClick:()=>void e.refresh(),disabled:e.busy,children:"Refresh"})]})]}),a.jsx(we,{title:"Known projects",children:e.projects.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No projects yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:e.projects.map($=>a.jsxs("li",{className:"flex items-center justify-between gap-2 py-2 first:pt-0 last:pb-0",children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"font-medium text-content",children:$.name}),a.jsx("code",{className:"truncate text-xs text-muted",children:$.root})]}),a.jsx(M,{size:"sm",onClick:()=>void e.openProject($.id),children:"Open"})]},$.id))})})]});function J($){return $==="projects"?ee:N?a.jsx(l0,{panel:$,projectId:N.id,projectRoot:N.root,onOpenConversation:re}):a.jsx("p",{className:"text-sm text-muted",children:"Open a project to use this panel."})}const W=!N&&Tr(u,"projects")==="closed",Y=$v(u,"left"),B=$v(u,"right"),le=xB(u);function je({panel:$}){const ge=Tr(u,$),de=Hn[$],Ne="bg-raised text-content ring-1 ring-border-strong";return a.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[a.jsx(ir,{size:"sm",title:"Ancré à gauche","aria-label":`Ancré à gauche — ${de}`,"aria-pressed":li(ge,"left"),className:q(li(ge,"left")&&Ne),onClick:()=>G($,{dock:"left"}),children:"⇤"}),a.jsx(ir,{size:"sm",title:"Ancré à droite","aria-label":`Ancré à droite — ${de}`,"aria-pressed":li(ge,"right"),className:q(li(ge,"right")&&Ne),onClick:()=>G($,{dock:"right"}),children:"⇥"}),a.jsx(ir,{size:"sm",title:"Flottant","aria-label":`Flottant — ${de}`,"aria-pressed":ge==="floating",className:q(ge==="floating"&&Ne),onClick:()=>G($,"floating"),children:"□"}),$!=="projects"&&a.jsx(ir,{size:"sm",title:"Fenêtre détachée","aria-label":`Fenêtre détachée — ${de}`,"aria-pressed":td(ge),disabled:!N,className:q(td(ge)&&Ne),onClick:()=>j($),children:"↗"}),a.jsx(ir,{size:"sm",title:"Fermé","aria-label":`Fermé — ${de}`,onClick:()=>E($),children:"×"})]})}function Ie($){return a.jsxs("section",{"aria-label":`${Hn[$]} panel`,className:"flex min-h-0 flex-1 flex-col border-b border-border last:border-b-0",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:Hn[$]}),a.jsx(je,{panel:$})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3",children:J($)})]},$)}return a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),a.jsx(CL,{items:e.openTabs.map($=>({id:$.id,label:$.name})),activeTabId:e.activeTabId,onSelect:$=>e.activateTab($),onClose:$=>void e.closeTab($),projectsPanelOpen:Tr(u,"projects")!=="closed",onOpenProjectsPanel:()=>{w(null),G("projects","floating")}}),a.jsx(UP,{menus:ie}),a.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[Y.length>0&&a.jsx(cx,{side:"left",width:d,onResize:f,"aria-label":"left dock",children:Y.map(Ie)}),a.jsx("main",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:x?a.jsx(fL,{section:x,onSectionChange:w,onClose:()=>w(null)}):N&&y?a.jsx(aT,{projectId:N.id,conversationId:y,onClose:()=>b(null)},`${N.id}-${y}`):N?a.jsxs(a.Fragment,{children:[a.jsx(FA,{projectId:N.id,onActiveLayoutChange:_}),P==="gitGraph"?a.jsx(SL,{projectId:N.id},`${N.id}-${v?.id??"default"}-graph`):a.jsx(DA,{projectId:N.id,cwd:N.root,layoutId:v?.id,onOpenConversation:re,onOpenPluginsSettings:()=>{w("plugins"),z()}},`${N.id}-${v?.id??"default"}`)]}):a.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:a.jsx("div",{className:"w-full max-w-xl",children:W?ee:a.jsx("p",{className:"text-sm text-muted",children:"Select or create a project to get started."})})})}),B.length>0&&a.jsx(cx,{side:"right",width:p,onResize:m,"aria-label":"right dock",children:B.map(Ie)})]}),le.map($=>a.jsxs(Bh,{open:!0,title:Hn[$],size:yB[$],onClose:()=>E($),children:[a.jsx("div",{className:"mb-3 flex justify-end border-b border-border pb-3",children:a.jsx(je,{panel:$})}),J($)]},$)),C.length>0&&a.jsx("div",{className:"fixed bottom-4 right-4 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",style:{zIndex:kn.toast},children:C.map($=>a.jsxs("button",{type:"button",className:"rounded-md border border-border bg-surface px-3 py-2 text-left shadow-lg hover:border-border-strong",onClick:()=>{e.openTabs.some(de=>de.id===$.projectId)&&e.activateTab($.projectId),w(null),b(null),G("work","floating"),k(de=>de.filter(Ne=>Ne.id!==$.id))},children:[a.jsxs("span",{className:"block text-sm font-medium text-content",children:["Background task ",$.state]}),a.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted",children:[$.agentId.slice(0,8)," · ",$.taskId.slice(0,8)]})]},$.id))})]})}const SB=5;function kB(e){if(e.totalWorkCount===1)return"1 travail actif sera interrompu si vous quittez IdeA maintenant.";const t=[];return e.busyAgentCount>0&&t.push(e.busyAgentCount===1?"1 agent travaille encore":`${e.busyAgentCount} agents travaillent encore`),e.activeBackgroundTaskCount>0&&t.push(e.activeBackgroundTaskCount===1?"1 tâche de fond est encore active":`${e.activeBackgroundTaskCount} tâches de fond sont encore actives`),`${t.join(" et ")}. Ces travaux seront interrompus si vous quittez IdeA maintenant.`}function CB(e){return e.kind==="busyAgent"?`Agent ${e.agentName} — ${e.projectName}`:`Tâche de fond ${e.taskId.slice(0,8)} — ${e.projectName}`}function jB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Wv="app-exit-confirm-title",Hv="app-exit-confirm-desc";function NB(){const{system:e}=he(),[t,n]=g.useState(null),[r,i]=g.useState(!1),[s,l]=g.useState(null),o=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{let p=!1,m;return e.onAppExitWorkGuard(x=>{n(x)}).then(x=>{p?x():m=x}).catch(()=>{}),()=>{p=!0,m?.()}},[e]),g.useEffect(()=>{t&&o.current?.focus()},[t!=null]);function u(){r||(n(null),l(null))}async function h(){i(!0),l(null);try{await e.confirmAppExit()}catch(p){l(jB(p))}finally{i(!1)}}if(g.useEffect(()=>{if(!t)return;function p(m){if(m.key==="Escape"){m.preventDefault(),u();return}if(m.key!=="Tab")return;const x=c.current?.querySelectorAll('button:not(:disabled), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(!x||x.length===0)return;const w=x[0],v=x[x.length-1];m.shiftKey&&document.activeElement===w?(m.preventDefault(),v.focus()):!m.shiftKey&&document.activeElement===v&&(m.preventDefault(),w.focus())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t!=null,r]),!t)return null;const d=t.details.slice(0,SB),f=t.details.length-d.length;return a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.toast},children:a.jsxs("div",{ref:c,role:"alertdialog","aria-modal":"true","aria-labelledby":Wv,"aria-describedby":Hv,onClick:p=>p.stopPropagation(),className:"flex w-full max-w-[520px] min-w-[440px] flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{id:Wv,className:"text-sm font-semibold text-content",children:"Du travail est encore en cours"}),a.jsx("p",{id:Hv,className:"text-sm text-content",children:kB(t)}),a.jsx("p",{className:"text-sm text-muted",children:"Annulez la fermeture pour laisser les agents et les tâches se terminer."}),d.length>0&&a.jsxs("ul",{className:"flex flex-col gap-1 rounded-md bg-canvas p-2 text-xs text-muted",children:[d.map((p,m)=>a.jsx("li",{children:`• ${CB(p)}`},m)),f>0&&a.jsxs("li",{children:["+ ",f," autre",f>1?"s":""]})]}),s&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:"IdeA n'a pas pu quitter correctement. Réessayez ou consultez les logs."}),a.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[a.jsx(M,{ref:o,size:"sm",variant:"ghost",disabled:r,onClick:u,children:"Annuler"}),a.jsx(M,{size:"sm",variant:"danger",disabled:r,loading:r,onClick:()=>void h(),children:r?"Fermeture…":"Quitter quand même"})]})]})})}function EB(){const{system:e,profile:t}=he(),[n,r]=g.useState(null),[i,s]=g.useState(null),[l,o]=g.useState([]),[c,u]=g.useState(null);return g.useEffect(()=>{let h,d=!1;return e.onDomainEvent(f=>o(p=>[...p,f])).then(f=>{d?f():h=f}).catch(()=>{}),e.health("ui-boot").then(f=>r(f)).catch(f=>s(PB(f))),()=>{d=!0,h?.()}},[e]),g.useEffect(()=>{let h=!1;return t.firstRunState().then(d=>{h||u(d.isFirstRun)}).catch(()=>{h||u(!1)}),()=>{h=!0}},[t]),a.jsx(LP,{children:a.jsxs(aA,{children:[a.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between border-b border-border px-6 py-3",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"IdeA"}),a.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"tauri"})]}),a.jsx(pw,{justify:"end",children:a.jsx("span",{className:"text-xs text-faint",children:n?a.jsxs(a.Fragment,{children:["backend ",a.jsx("span",{className:"text-success",children:"●"})," v",n.version," ·"," ",l.length," events"]}):i?a.jsx("span",{className:"text-danger",children:"backend unavailable"}):a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[a.jsx(Re,{size:12})," checking…"]})})})]}),a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[i&&a.jsx(we,{className:"mx-4 mt-4 border-danger/40",children:a.jsxs("p",{className:"text-sm text-danger",children:["Error: ",i]})}),c?a.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:a.jsx("div",{className:"w-full max-w-xl",children:a.jsx(Sw,{onDone:()=>u(!1)})})}):a.jsx(wB,{})]})]}),a.jsx(NB,{})]})})}function PB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const AB=new Set(Object.keys(Hn).filter(e=>e!=="projects"));function TB(e){const n=new URLSearchParams(e).get("panel");return!n||!AB.has(n)?null:{panel:n}}function LB({panel:e}){const{focusedProject:t}=he(),[n,r]=g.useState(void 0);return g.useEffect(()=>{let i=!1,s;return t.getFocusedProject().then(l=>{i||r(l)}).catch(()=>{i||r(null)}),t.onFocusedProjectChanged(l=>{i||r(l)}).then(l=>{i?l():s=l}),()=>{i=!0,s?.()}},[t]),a.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[a.jsxs("header",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5",children:[a.jsx("h1",{className:"text-sm font-semibold text-content",children:Hn[e]}),n&&a.jsxs("span",{className:"truncate text-xs text-muted",children:["· ",n.name]})]}),a.jsx("main",{className:"min-h-0 flex-1 overflow-auto p-4",children:n?a.jsx(l0,{panel:e,projectId:n.id,projectRoot:n.root}):a.jsx(we,{children:a.jsx("p",{className:"text-sm text-muted",children:"Ouvrez un projet dans la fenêtre principale pour afficher ce panneau."})})})]})}function DB(e){if(e&&typeof e=="object"&&"message"in e){const t=e;return{code:String(t.code??"ERROR"),message:String(t.message)}}return{code:"ERROR",message:String(e)}}function RB({session:e,onPaired:t}){const[n,r]=g.useState(""),[i,s]=g.useState(()=>Sx(nL())),[l,o]=g.useState(null),[c,u]=g.useState(!1),h=WO(n),d=i.trim(),f=h.length>0&&d.length>0,p=l?.code==="invalidName"?l.message:null,m=l&&!p?l.message:null;async function x(w){if(w.preventDefault(),!(!f||c)){u(!0),o(null);try{await e.pair(h,Sx(d)),t()}catch(v){o(DB(v))}finally{u(!1)}}}return a.jsx("div",{className:"flex h-full items-center justify-center overflow-y-auto bg-canvas p-4 sm:p-6",children:a.jsx(we,{className:"w-full max-w-sm",children:a.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Appairer cet appareil"}),a.jsx("p",{className:"text-sm text-muted",children:"Saisissez le code affiché par le serveur IdeA pour connecter ce navigateur."})]}),a.jsx(qt,{label:"Code d'appairage",hint:"8 caractères : chiffres et lettres A-F",children:({id:w,describedBy:v})=>a.jsx(ce,{id:w,"aria-describedby":v,value:n,onChange:_=>r(_.target.value),placeholder:"p. ex. AB12CD34",autoFocus:!0,autoComplete:"one-time-code",inputMode:"text",autoCapitalize:"characters",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!m})}),a.jsx(qt,{label:"Nom de cet appareil",hint:"Pour le reconnaître dans la liste des appareils.",error:p??void 0,children:({id:w,describedBy:v})=>a.jsx(ce,{id:w,"aria-describedby":v,value:i,onChange:_=>s(_.target.value),maxLength:gp,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!p})}),m&&a.jsx("p",{role:"alert","data-testid":"pairing-error",className:"text-sm text-danger",children:m}),a.jsx(M,{type:"submit",disabled:c||!f,children:c?"Appairage…":"Appairer"})]})})})}const MB=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Ctrl-C",aria:"Ctrl-C (interrompre)",data:""},{label:"Ctrl-D",aria:"Ctrl-D (fin de saisie)",data:""},{label:"↑",aria:"Flèche haut",data:"\x1B[A"},{label:"↓",aria:"Flèche bas",data:"\x1B[B"},{label:"←",aria:"Flèche gauche",data:"\x1B[D"},{label:"→",aria:"Flèche droite",data:"\x1B[C"}];function IB({api:e,className:t}){return a.jsx("div",{role:"toolbar","aria-label":"Touches du terminal","data-testid":"terminal-key-bar",className:q("flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-raised/40 px-2 py-1.5",t),children:MB.map(n=>a.jsx(M,{size:"sm",variant:"secondary","aria-label":n.aria??n.label,disabled:!e,onPointerDown:r=>r.preventDefault(),onClick:()=>{e?.send(n.data),e?.focus()},className:"min-h-11 shrink-0 font-mono",children:n.label},n.label))})}function OB({projectId:e,agentId:t,cwd:n,nodeId:r,refitSignal:i}){const{agent:s}=he(),[l,o]=g.useState(null),[c,u]=g.useState(null),h=g.useCallback((f,p)=>s.launchAgent(e,t,r?{...f,nodeId:r}:f,p),[s,e,t,r]),d=g.useCallback((f,p)=>s.reattach(f,p),[s]);return a.jsxs("div",{"data-testid":"web-agent-cell",className:"flex h-[60dvh] min-h-64 w-full flex-col overflow-hidden rounded-md border border-border sm:h-80",children:[a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(up,{cwd:n,agentMode:!0,open:h,reattach:d,sessionId:l,onSessionId:o,onReady:u,refitSignal:i})}),a.jsx(IB,{api:c})]})}function BB(e){g.useEffect(()=>{const t=Ih();if(!t)return;let n=t.getConnectionState();return t.onConnectionStateChange(r=>{r==="connected"&&n==="reconnecting"&&e(),n=r})},[e])}function zB(){const[e,t]=g.useState(()=>Ih()?.getConnectionState()??null);return g.useEffect(()=>{const n=Ih();if(n)return t(n.getConnectionState()),n.onConnectionStateChange(t)},[]),e}function Rc(e){switch(e){case"open":return"Ouvert";case"inProgress":return"En cours";case"QA":return"QA";case"closed":return"Fermé"}}function la(e){switch(e){case"low":return"Faible";case"medium":return"Moyenne";case"high":return"Haute";case"critical":return"Critique"}}function Uv(e){switch(e){case"relatesTo":return"en relation avec";case"blocks":return"bloque";case"blockedBy":return"bloqué par";case"duplicates":return"duplique";case"dependsOn":return"dépend de"}}function FB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function $B(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function a0(e){return q("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function Fp({status:e}){return a.jsx("span",{className:a0(FB(e)),children:Rc(e)})}function $p({priority:e}){return a.jsx("span",{className:a0($B(e)),children:la(e)})}const qv=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),WB=q("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function HB({sprints:e,busy:t,error:n,onCancel:r,onCreate:i}){const[s,l]=g.useState(""),[o,c]=g.useState(""),[u,h]=g.useState("medium"),[d,f]=g.useState("");async function p(m){m.preventDefault();const x=s.trim();x&&await i({title:x,priority:u,...o.trim()?{description:o.trim()}:{}},d||null)}return a.jsxs(we,{title:"Nouveau ticket",actions:a.jsx(M,{size:"sm",variant:"ghost",onClick:r,children:"Annuler"}),children:[n&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n}),a.jsxs("form",{onSubmit:p,className:"flex flex-col gap-3",children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),a.jsx(ce,{"aria-label":"Titre",value:s,onChange:m=>l(m.target.value),disabled:t,autoFocus:!0})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Priorité"}),a.jsx("select",{"aria-label":"Priorité",className:qv,value:u,disabled:t,onChange:m=>h(m.target.value),children:js.map(m=>a.jsx("option",{value:m,children:la(m)},m))})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Sprint"}),a.jsxs("select",{"aria-label":"Sprint",className:qv,value:d,disabled:t,onChange:m=>f(m.target.value),children:[a.jsx("option",{value:"",children:"Sans sprint"}),e.map(m=>a.jsx("option",{value:m.id,children:m.name},m.id))]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),a.jsx("textarea",{"aria-label":"Description",className:q(WB,"min-h-20"),value:o,onChange:m=>c(m.target.value),disabled:t})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[a.jsx(M,{type:"button",variant:"ghost",size:"sm",disabled:t,onClick:r,children:"Annuler"}),a.jsx(M,{type:"submit",size:"sm",disabled:!s.trim()||t,loading:t,children:"Créer"})]})]})]})}function o0({title:e,body:t,confirmLabel:n,busy:r=!1,onConfirm:i,onCancel:s}){const l=g.useRef(null);return g.useEffect(()=>{l.current?.focus()},[]),g.useEffect(()=>{function o(c){c.key==="Escape"&&s()}return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[s]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.toast},children:a.jsxs("div",{role:"alertdialog","aria-modal":"true","aria-label":e,onClick:o=>o.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"text-sm text-muted",children:t}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{ref:l,size:"sm",variant:"ghost",disabled:r,onClick:s,children:"Annuler"}),a.jsx(M,{size:"sm",variant:"danger",loading:r,disabled:r,onClick:()=>void i(),children:n})]})]})})}function c0({projectId:e,title:t,confirmLabel:n="Ajouter",selectionMode:r,excludeRefs:i,onSelect:s,onClose:l}){const o=Dc(e,{excludeRefs:i}),c=r==="multi",[u,h]=g.useState(()=>new Set),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useRef(null);g.useEffect(()=>{x.current?.focus()},[]),g.useEffect(()=>{function b(C){C.key==="Escape"&&l()}return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[l]);function w(b){return b&&typeof b=="object"&&"message"in b?String(b.message):String(b)}function v(b){h(C=>{const k=new Set(C);return k.has(b)?k.delete(b):k.add(b),k})}async function _(b){if(!d){f(!0),m(null);try{s(await o.resolve(b)),l()}catch(C){m(w(C)),f(!1)}}}async function y(){if(!(d||u.size===0)){f(!0),m(null);try{const b=await Promise.all(Array.from(u).map(C=>o.resolve(C)));s(b),l()}catch(b){m(w(b)),f(!1)}}}return a.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":t,style:{zIndex:kn.floatingWindowNested},children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[a.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:t}),a.jsx(M,{ref:x,size:"sm",variant:"ghost",onClick:l,children:"Fermer"})]}),a.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:a.jsx(ce,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:o.text,onChange:b=>o.setText(b.target.value),autoFocus:!0})}),(o.error||p)&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??o.error}),a.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[o.busy&&o.rows.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Chargement des tickets…"})]}):o.rows.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:o.rows.map(b=>{const C=u.has(b.ref);return a.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:a.jsxs("button",{type:"button","aria-label":`${b.ref}, ${b.title}`,...c?{role:"checkbox","aria-checked":C}:{},disabled:d,onClick:()=>c?v(b.ref):void _(b.ref),className:q("flex min-h-[40px] w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-60",c&&C&&"bg-raised"),children:[c&&a.jsx("span",{"aria-hidden":"true",className:q("flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",C?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),a.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:b.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:b.title}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[a.jsx(Fp,{status:b.status}),a.jsx($p,{priority:b.priority})]})]})},b.ref)})}),o.hasMore&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:o.busy,onClick:()=>o.loadMore(),children:"Charger plus"})})]}),c&&a.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]",children:[a.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[u.size," sélectionné",u.size>1?"s":""]}),a.jsxs(M,{size:"sm",loading:d,disabled:u.size===0||d,onClick:()=>void y(),children:[n," ",u.size>0?`(${u.size})`:""]})]})]})}const zi=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Vv=q("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function Fi({title:e,defaultOpen:t,children:n}){const[r,i]=g.useState(t);return a.jsxs("section",{className:"border-b border-border py-2 last:border-b-0",children:[a.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>i(s=>!s),className:"flex min-h-[32px] w-full items-center justify-between text-left text-xs font-semibold uppercase tracking-wide text-muted",children:[e,a.jsx("span",{"aria-hidden":"true",children:r?"▾":"▸"})]}),r&&a.jsx("div",{className:"mt-2 flex flex-col gap-2",children:n})]})}function UB({projectId:e,ticketRef:t,nameOf:n,assignableAgents:r,sprints:i,onBack:s,onOpenRef:l}){const o=i0(e,t),c=o.ticket,[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState("relatesTo"),[v,_]=g.useState(""),[y,b]=g.useState(!1),[C,k]=g.useState(!1),[N,R]=g.useState(!1);g.useEffect(()=>{o.deleted&&s()},[o.deleted,s]);const L=o.reloadCount,S=g.useRef(-1),T=g.useRef(null);g.useEffect(()=>{if(!c||S.current===L)return;S.current=L;const E=c.carnet??"",z=T.current;z===null||o.conflict?(h(c.title),f(c.description),m(E)):(h(re=>re===z.title?c.title:re),f(re=>re===z.description?c.description:re),m(re=>re===z.carnet?E:re)),T.current={title:c.title,description:c.description,carnet:E}},[c,L,o.conflict]);const D=!!c&&(u!==c.title||d!==c.description),P=!!c&&p!==(c.carnet??""),I=D||P,O=r.filter(E=>!c?.assignedAgentIds.includes(E.id));function U(){I?k(!0):s()}async function G(){let E=!0;D&&(E=await o.updateFields({title:u,description:d})&&E),E&&P&&(E=await o.saveCarnet(p)&&E),k(!1),E&&s()}return a.jsxs(we,{className:"flex flex-col",flush:!0,children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:U,children:"← Tickets"}),a.jsx("code",{className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:t})]}),o.conflict&&a.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-4 py-2 text-sm text-warning",children:"Ce ticket a été modifié ailleurs et rechargé. Réappliquez votre modification."}),o.error&&!o.conflict&&a.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:o.error}),o.busy&&!c?a.jsxs("div",{className:"flex items-center gap-2 px-4 py-5 text-sm text-muted",children:[a.jsx(Re,{size:14}),a.jsx("span",{children:"Chargement du ticket…"})]}):c?a.jsxs("div",{className:"flex flex-col px-4 py-2",children:[a.jsxs("div",{className:"flex flex-col gap-1 border-b border-border pb-3",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),a.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[a.jsx(Fp,{status:c.status}),a.jsx($p,{priority:c.priority}),c.sprintId&&a.jsxs("span",{children:["· ",i.find(E=>E.id===c.sprintId)?.name??"Sprint"]})]})]}),a.jsxs(Fi,{title:"Résumé",defaultOpen:!0,children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),a.jsx("input",{"aria-label":"Titre",className:q(zi,"w-full"),value:u,onChange:E=>h(E.target.value),disabled:o.busy})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),a.jsx("textarea",{"aria-label":"Description",className:q(Vv,"min-h-24"),value:d,onChange:E=>f(E.target.value),disabled:o.busy})]}),a.jsx("div",{children:a.jsx(M,{size:"sm",disabled:!D||o.busy,loading:o.busy&&D,onClick:()=>void o.updateFields({title:u,description:d}),children:"Enregistrer"})})]}),a.jsxs(Fi,{title:"Statut et priorité",defaultOpen:!0,children:[a.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[a.jsx("span",{className:"text-muted",children:"Statut"}),a.jsx("select",{"aria-label":"Statut",className:zi,value:c.status,disabled:o.busy,onChange:E=>void o.updateFields({status:E.target.value}),children:Tc.map(E=>a.jsx("option",{value:E,children:Rc(E)},E))})]}),a.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[a.jsx("span",{className:"text-muted",children:"Priorité"}),a.jsx("select",{"aria-label":"Priorité",className:zi,value:c.priority,disabled:o.busy,onChange:E=>void o.updateFields({priority:E.target.value}),children:js.map(E=>a.jsx("option",{value:E,children:la(E)},E))})]}),a.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[a.jsx("span",{className:"text-muted",children:"Sprint"}),a.jsxs("select",{"aria-label":"Sprint",className:zi,value:c.sprintId??"",disabled:o.busy,onChange:E=>void o.setSprint(E.target.value||null),children:[a.jsx("option",{value:"",children:"Sans sprint"}),i.map(E=>a.jsx("option",{value:E.id,children:E.name},E.id))]})]}),o.busy&&a.jsx(Re,{size:12})]}),a.jsxs(Fi,{title:"Carnet",defaultOpen:!0,children:[a.jsx("textarea",{"aria-label":"Carnet",className:q(Vv,"min-h-32 font-mono"),value:p,onChange:E=>m(E.target.value),disabled:o.busy}),a.jsx("div",{children:a.jsx(M,{size:"sm",disabled:!P||o.busy,loading:o.busy&&P,onClick:()=>void o.saveCarnet(p),children:"Enregistrer le carnet"})})]}),a.jsxs(Fi,{title:"Agents assignés",defaultOpen:!1,children:[c.assignedAgentIds.length===0?a.jsx("p",{className:"text-xs text-muted",children:"Aucun agent assigné."}):a.jsx("ul",{className:"flex flex-wrap gap-2",children:c.assignedAgentIds.map(E=>a.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[n(E),a.jsx("button",{type:"button","aria-label":`Désassigner ${n(E)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:o.busy,onClick:()=>void o.assign(E,!1),children:"×"})]},E))}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{"aria-label":"Assigner un agent",className:zi,value:v,disabled:o.busy||O.length===0,onChange:E=>_(E.target.value),children:[a.jsx("option",{value:"",children:O.length===0?"Aucun autre agent":"Choisir un agent…"}),O.map(E=>a.jsx("option",{value:E.id,children:E.name},E.id))]}),a.jsx(M,{size:"sm",disabled:!v||o.busy,onClick:async()=>{await o.assign(v,!0)&&_("")},children:"Assigner"})]})]}),a.jsxs(Fi,{title:"Liens",defaultOpen:!1,children:[c.links.length===0?a.jsx("p",{className:"text-xs text-muted",children:"Aucun ticket lié."}):a.jsx("ul",{className:"flex flex-col gap-1",children:c.links.map(E=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-xs text-muted",children:Uv(E.kind)}),a.jsx("button",{type:"button",className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content hover:text-primary",onClick:()=>l(E.targetRef),children:E.targetRef}),a.jsx(M,{size:"sm",variant:"ghost",disabled:o.busy,onClick:()=>void o.unlink(E.targetRef,E.kind),children:"Retirer"})]},`${E.kind}-${E.targetRef}`))}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("select",{"aria-label":"Type de lien",className:zi,value:x,disabled:o.busy,onChange:E=>w(E.target.value),children:e0.map(E=>a.jsx("option",{value:E,children:Uv(E)},E))}),a.jsx(M,{size:"sm",disabled:o.busy,onClick:()=>R(!0),children:"+ Lier"})]})]}),a.jsxs(Fi,{title:"Zone dangereuse",defaultOpen:!1,children:[a.jsxs("p",{className:"text-xs text-muted",children:["Le ticket ",t," sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés."]}),a.jsx("div",{children:a.jsx(M,{size:"sm",variant:"danger",disabled:o.busy,onClick:()=>b(!0),children:"Supprimer"})})]})]}):a.jsx("p",{className:"px-4 py-5 text-sm text-muted",children:"Ticket introuvable."}),N&&c&&a.jsx(c0,{projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...c.links.map(E=>E.targetRef)],onSelect:E=>{const z=Array.isArray(E)?E[0]:E;z&&o.link(z.ref,x)},onClose:()=>R(!1)}),y&&a.jsx(o0,{title:"Supprimer ce ticket ?",body:`Le ticket ${t} sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés.`,confirmLabel:"Supprimer",busy:o.busy,onCancel:()=>b(!1),onConfirm:async()=>{await o.remove()&&b(!1)}}),C&&a.jsx("div",{role:"alertdialog","aria-modal":"true","aria-label":"Modifications non enregistrées",className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",children:a.jsxs("div",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:"Des modifications ne sont pas enregistrées."}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:o.busy,onClick:()=>k(!1),children:"Continuer l'édition"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:o.busy,onClick:s,children:"Ignorer"}),a.jsx(M,{size:"sm",loading:o.busy,disabled:o.busy,onClick:()=>void G(),children:"Enregistrer et quitter"})]})]})})]})}function qB(e){const t=ea(e),n=g.useMemo(()=>(t.state?.agents??[]).map(s=>({id:s.agentId,name:s.name})),[t.state]),r=g.useMemo(()=>new Map(n.map(s=>[s.id,s.name])),[n]);return{agents:n,nameOf:s=>r.get(s)??`${s.slice(0,8)}…`,loaded:t.state!==null}}const Va=q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Kv={number:"Numéro",priority:"Priorité",status:"Statut",title:"Titre"};function VB({projectId:e,focusSprintId:t=null}){const n=Op(e),r=qB(e),[i,s]=g.useState({type:"list"}),[l,o]=g.useState(t);if(i.type==="detail")return a.jsx(UB,{projectId:e,ticketRef:i.ref,nameOf:r.nameOf,assignableAgents:r.agents,sprints:n.sprints,onBack:()=>s({type:"list"}),onOpenRef:x=>s({type:"detail",ref:x})},i.ref);if(i.type==="create")return a.jsx(HB,{sprints:n.sprints,busy:n.busy,error:n.error,onCancel:()=>s({type:"list"}),onCreate:async(x,w)=>{const v=await n.create(x);v&&(w&&await n.assignSprint(v.ref,w),s({type:"detail",ref:v.ref}))}});const c=n.list?.items??[],u=!!n.query.text||(n.query.statuses?.length??0)>0||(n.query.priorities?.length??0)>0||!!n.query.assignedAgentId||!!l,h=new Set(n.sprints.map(x=>x.id)),f=(l?n.sprints.filter(x=>x.id===l):n.sprints).map(x=>({sprint:x,tickets:c.filter(w=>w.sprintId===x.id)})).filter(x=>x.tickets.length>0),p=l?[]:c.filter(x=>!x.sprintId||!h.has(x.sprintId));function m(){n.setQuery({}),o(null)}return a.jsxs(we,{className:"flex flex-col",title:"Tickets",actions:a.jsx(M,{size:"sm",onClick:()=>s({type:"create"}),children:"+ Ticket"}),children:[n.error&&a.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[a.jsx("span",{children:n.error}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),children:"Réessayer"})]}),l&&a.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 rounded-md border border-border bg-raised/50 px-3 py-2 text-xs text-muted",children:[a.jsxs("span",{children:["Filtré sur le sprint « ",n.sprints.find(x=>x.id===l)?.name??l," »"]}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>o(null),children:"Voir tous les tickets"})]}),a.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[a.jsx(ce,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:n.query.text??"",onChange:x=>n.setQuery({...n.query,text:x.target.value||void 0})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("select",{"aria-label":"Filtrer par statut",className:Va,value:n.query.statuses?.[0]??"",onChange:x=>n.setQuery({...n.query,statuses:x.target.value?[x.target.value]:void 0}),children:[a.jsx("option",{value:"",children:"Tous les statuts"}),Tc.map(x=>a.jsx("option",{value:x,children:Rc(x)},x))]}),a.jsxs("select",{"aria-label":"Filtrer par priorité",className:Va,value:n.query.priorities?.[0]??"",onChange:x=>n.setQuery({...n.query,priorities:x.target.value?[x.target.value]:void 0}),children:[a.jsx("option",{value:"",children:"Toutes les priorités"}),js.map(x=>a.jsx("option",{value:x,children:la(x)},x))]}),a.jsxs("select",{"aria-label":"Filtrer par agent assigné",className:Va,value:n.query.assignedAgentId??"",onChange:x=>n.setQuery({...n.query,assignedAgentId:x.target.value||void 0}),children:[a.jsx("option",{value:"",children:"Tous les agents"}),r.agents.map(x=>a.jsx("option",{value:x.id,children:x.name},x.id))]}),a.jsxs("select",{"aria-label":"Trier les tickets",className:Va,value:n.query.sort?.field??"",onChange:x=>{const w=x.target.value,{sort:v,..._}=n.query;n.setQuery(w?{..._,sort:{field:w,direction:"asc"}}:_)},children:[a.jsx("option",{value:"",children:"Tri par défaut"}),Object.keys(Kv).map(x=>a.jsx("option",{value:x,children:Kv[x]},x))]})]})]}),n.busy&&n.list===null?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Re,{size:12})," Chargement des tickets…"]}):c.length===0&&!u?a.jsxs("div",{className:"flex flex-col items-start gap-2",children:[a.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket dans ce projet."}),a.jsx(M,{size:"sm",onClick:()=>s({type:"create"}),children:"Créer un ticket"})]}):c.length===0?a.jsxs("div",{className:"flex flex-col items-start gap-2",children:[a.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond aux filtres."}),a.jsx(M,{size:"sm",variant:"ghost",onClick:m,children:"Réinitialiser les filtres"})]}):a.jsxs("div",{className:"flex flex-col gap-4","data-testid":"web-ticket-list",children:[f.map(x=>a.jsx(Gv,{heading:x.sprint.name,tickets:x.tickets,sprints:n.sprints,nameOf:r.nameOf,onOpen:w=>s({type:"detail",ref:w})},x.sprint.id)),p.length>0&&a.jsx(Gv,{heading:"Sans sprint",tickets:p,sprints:n.sprints,nameOf:r.nameOf,onOpen:x=>s({type:"detail",ref:x})})]}),n.list?.nextCursor&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Charger plus"})})]})}function Gv({heading:e,tickets:t,sprints:n,nameOf:r,onOpen:i}){const s=l=>l?n.find(o=>o.id===l)?.name:void 0;return a.jsxs("section",{"aria-label":`Tickets — ${e}`,children:[a.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,a.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t.length})]}),a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(l=>{const o=s(l.sprintId),c=l.assignedAgentIds.map(r).join(", ");return a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>i(l.ref),"aria-label":`${l.ref}, ${l.title}, statut ${Rc(l.status)}, priorité ${la(l.priority)}`,className:"flex w-full min-w-0 flex-col items-start gap-0.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-raised",children:[a.jsxs("span",{className:"flex w-full min-w-0 items-baseline gap-2",children:[a.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:l.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:l.title})]}),a.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[a.jsx(Fp,{status:l.status}),a.jsx($p,{priority:l.priority}),o&&a.jsxs("span",{children:["· ",o]}),c&&a.jsxs("span",{children:["· ",c]})]})]})},l.ref)})})]})}function KB({projectId:e,onViewSprintTickets:t}){const n=Op(e),r=Dc(e,{refreshOnEvents:!0}),[i,s]=g.useState(!1),[l,o]=g.useState(""),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState(null),[m,x]=g.useState(null),w=[...n.sprints].sort((_,y)=>_.order-y.order);async function v(_){_.preventDefault();const y=l.trim();if(!y)return;await n.createSprint(y)&&(o(""),s(!1))}return a.jsxs(we,{title:"Sprints",actions:a.jsx(M,{size:"sm",onClick:()=>s(_=>!_),children:"+ Sprint"}),children:[n.error&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),i&&a.jsxs("form",{onSubmit:v,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Nom du sprint"}),a.jsx(ce,{"aria-label":"Nom du sprint",value:l,onChange:_=>o(_.target.value),autoFocus:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:()=>s(!1),children:"Annuler"}),a.jsx(M,{type:"submit",size:"sm",disabled:!l.trim()||n.busy,children:"Créer"})]})]}),n.busy&&n.sprints.length===0?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Re,{size:12})," Chargement des sprints…"]}):w.length===0?a.jsxs("div",{className:"flex flex-col items-start gap-2",children:[a.jsx("p",{className:"text-sm text-muted",children:"Aucun sprint."}),a.jsx(M,{size:"sm",onClick:()=>s(!0),children:"Créer un sprint"})]}):a.jsx("ul",{className:"flex flex-col gap-3",children:w.map((_,y)=>a.jsx(GB,{sprint:_,index:y,lastIndex:w.length-1,tickets:r.rows.filter(b=>b.sprintId===_.id),vm:n,renaming:c===_.id,renameDraft:h,onStartRename:()=>{u(_.id),d(_.name)},onRenameDraftChange:d,onCancelRename:()=>u(null),onSaveRename:async()=>{await n.renameSprint(_.id,h.trim())&&u(null)},onViewTickets:()=>t(_.id),onAddTickets:()=>x({id:_.id,name:_.name}),onRequestDelete:()=>p({id:_.id,name:_.name})},_.id))}),f&&a.jsx(o0,{title:`Supprimer le sprint « ${f.name} » ?`,body:"Les tickets de ce sprint seront conservés et passeront en « Sans sprint ».",confirmLabel:"Supprimer",busy:n.busy,onCancel:()=>p(null),onConfirm:async()=>{await n.deleteSprint(f.id),p(null)}}),m&&a.jsx(c0,{projectId:e,title:`Ajouter des tickets au sprint « ${m.name} »`,confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:r.rows.filter(_=>_.sprintId===m.id).map(_=>_.ref),onSelect:_=>{const y=Array.isArray(_)?_:[_];for(const b of y)n.assignSprint(b.ref,m.id)},onClose:()=>x(null)})]})}function GB({sprint:e,index:t,lastIndex:n,tickets:r,vm:i,renaming:s,renameDraft:l,onStartRename:o,onRenameDraftChange:c,onCancelRename:u,onSaveRename:h,onViewTickets:d,onAddTickets:f,onRequestDelete:p}){return a.jsxs("li",{className:"rounded-md border border-border p-3",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",e.order]}),!s&&a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e.name})]}),s?a.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[a.jsx(ce,{"aria-label":`Renommer le sprint ${e.name}`,value:l,onChange:m=>c(m.target.value),disabled:i.busy}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:u,children:"Annuler"}),a.jsx(M,{size:"sm",disabled:i.busy||!l.trim()||l.trim()===e.name,onClick:()=>void h(),children:"Enregistrer"})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:"mt-1 text-xs text-muted",children:[e.ticketCount," ticket",e.ticketCount>1?"s":""]}),r.length>0&&a.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:r.map(m=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:m.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:m.title}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Retirer ${m.ref} du sprint ${e.name}`,disabled:i.busy,onClick:()=>void i.assignSprint(m.ref,null),children:"Retirer du sprint"})]},m.ref))}),a.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:d,children:"Voir tickets"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:f,children:"Ajouter tickets"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Renommer ${e.name}`,disabled:i.busy,onClick:o,children:"Renommer"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Monter ${e.name}`,disabled:i.busy||t===0,onClick:()=>void i.moveSprint(e.id,"up"),children:"Monter"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Descendre ${e.name}`,disabled:i.busy||t===n,onClick:()=>void i.moveSprint(e.id,"down"),children:"Descendre"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Supprimer ${e.name}`,disabled:i.busy,className:"text-danger hover:text-danger",onClick:p,children:"Supprimer"})]})]})]})}function YB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function XB({projects:e,openId:t,onOpen:n,onCreate:r,onRefresh:i}){const[s,l]=g.useState(""),[o,c]=g.useState(""),[u,h]=g.useState(!1),[d,f]=g.useState(null),p=s.trim().length>0&&o.trim().length>0&&!u;async function m(x){if(x.preventDefault(),!!p){h(!0),f(null);try{const w=await r(s.trim(),o.trim());l(""),c(""),n(w.id)}catch(w){f(YB(w))}finally{h(!1)}}}return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Projets"}),a.jsx(M,{variant:"ghost",size:"sm",onClick:i,children:"Rafraîchir"})]}),a.jsx(we,{title:"Nouveau projet",children:a.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-col gap-2",children:[a.jsx(ce,{"aria-label":"Nom du projet",placeholder:"Nom du projet",value:s,onChange:x=>l(x.target.value)}),a.jsx(ce,{"aria-label":"Chemin du projet",placeholder:"/chemin/absolu/du/projet",value:o,onChange:x=>c(x.target.value)}),a.jsx("p",{className:"text-xs text-muted",children:"Saisir un chemin absolu accessible depuis le serveur IdeA."}),d&&a.jsx("p",{role:"alert",className:"text-xs text-danger",children:d}),a.jsx(M,{type:"submit",variant:"primary",disabled:!p,loading:u,children:"Créer le projet"})]})}),e===null?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Re,{size:12})," Chargement des projets…"]}):e.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun projet."}):a.jsx("ul",{className:"flex flex-col gap-2","data-testid":"web-project-list",children:e.map(x=>a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>n(x.id),"aria-pressed":t===x.id,className:"flex w-full flex-col items-start rounded-md border border-border bg-raised px-3 py-2 text-left transition-colors hover:border-primary aria-pressed:border-primary",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:x.name}),a.jsx("span",{className:"text-xs text-faint",children:x.root})]})},x.id))})]})}function u0({title:e,entries:t,note:n,onClose:r}){const i=g.useRef(null);return g.useEffect(()=>{i.current?.focus()},[]),g.useEffect(()=>{function s(l){l.key==="Escape"&&r()}return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[r]),a.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":e,style:{zIndex:kn.floatingWindowNested},children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[a.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:e}),a.jsx(M,{ref:i,size:"sm",variant:"ghost",onClick:r,children:"Fermer"})]}),n&&a.jsx("p",{className:"shrink-0 border-b border-border px-4 py-2 text-xs text-muted",children:n}),a.jsx("ul",{className:"min-h-0 flex-1 overflow-auto px-2 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:t.map(s=>a.jsx("li",{children:a.jsxs("button",{type:"button",disabled:s.disabled,title:s.hint,"aria-current":s.active?"true":void 0,onClick:()=>{s.disabled||s.onSelect()},className:q("flex min-h-[44px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-50 disabled:hover:bg-transparent",s.active&&"bg-raised font-medium text-content"),children:[a.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-primary",children:s.active?"●":""}),a.jsx("span",{className:"min-w-0 flex-1 truncate",children:s.label}),s.secondaryLabel&&a.jsx("span",{className:"shrink-0 text-xs text-muted",children:s.secondaryLabel})]})},s.id))})]})}function xo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const QB=["context","work","tickets","sprints","agents","templates","skills","permissions","memory","git","projects"],Yv={context:"Contexte projet",work:"Travail",tickets:"Tickets",sprints:"Sprints",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Mémoire",git:"Git",projects:"Projets"};function JB(){const{project:e}=he(),[t,n]=g.useState(null),[r,i]=g.useState(null),[s,l]=g.useState(null),[o,c]=g.useState("projects"),[u,h]=g.useState(null),d=t?.find(x=>x.id===s)?.root??null,f=g.useCallback(async()=>{i(null);try{n(await e.listProjects())}catch(x){i(xo(x))}},[e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async x=>{i(null),l(null);try{await e.openProject(x),l(x),c("work")}catch(w){i(xo(w))}},[e]),m=g.useCallback(async(x,w)=>{i(null);try{const v=await e.createProject(x,w);return await f(),v}catch(v){throw i(xo(v)),v}},[e,f]);return a.jsxs("div",{"data-testid":"web-workspace",className:"flex h-full flex-col gap-4 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:[a.jsx(t4,{}),a.jsx(ZB,{activePanel:o,hasProject:!!s,onSelect:c}),r&&a.jsx(we,{className:"border-danger/40",children:a.jsx("p",{className:"text-sm text-danger",children:r})}),o==="projects"?a.jsx(XB,{projects:t,openId:s,onOpen:x=>void p(x),onCreate:m,onRefresh:()=>void f()}):s?a.jsx(e4,{panel:o,projectId:s,root:d,focusSprintId:u,onViewSprintTickets:x=>{h(x),c("tickets")}}):a.jsx("p",{className:"text-sm text-muted",children:"Ouvrir un projet pour utiliser ce panneau."})]})}function ZB({activePanel:e,hasProject:t,onSelect:n}){const[r,i]=g.useState(!1);return a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>i(!0),children:["Panneaux : ",Yv[e]]}),r&&a.jsx(u0,{title:"Panneaux",note:t?void 0:"Ouvrir un projet pour utiliser ce panneau.",onClose:()=>i(!1),entries:QB.map(s=>{const l=s!=="projects"&&!t;return{id:s,label:Yv[s],active:s===e,disabled:l,hint:l?"Ouvrir un projet pour utiliser ce panneau.":void 0,onSelect:()=>{n(s),i(!1)}}})})]})}function e4({panel:e,projectId:t,root:n,focusSprintId:r,onViewSprintTickets:i}){switch(e){case"context":return a.jsx(s0,{projectId:t});case"work":return a.jsx(n4,{projectId:t,root:n});case"tickets":return a.jsx(VB,{projectId:t,focusSprintId:r});case"sprints":return a.jsx(KB,{projectId:t,onViewSprintTickets:i});case"agents":return a.jsx(xw,{projectId:t,projectRoot:n??""});case"templates":return a.jsx(zS,{projectId:t});case"skills":return a.jsx(FS,{projectId:t});case"permissions":return a.jsx(GS,{projectId:t});case"memory":return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx(qS,{projectId:t}),a.jsx(US,{})]});case"git":return a.jsx(Tw,{projectId:t})}}function t4(){return zB()!=="reconnecting"?null:a.jsxs("div",{role:"status","data-testid":"web-reconnect-banner",className:"flex items-center gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:[a.jsx(Re,{size:12}),"Connexion perdue — reconnexion en cours…"]})}function n4({projectId:e,root:t}){const n=ea(e);BB(n.refresh);const[r,i]=g.useState(null),[s,l]=g.useState(0),o=g.useCallback(()=>l(f=>f+1),[]),c=n.state?.agents??[],[u,h]=g.useState(new Set);g.useEffect(()=>{const f=new Set(c.filter(p=>(p.backgroundTasks??[]).length>0).map(p=>p.agentId));h(p=>{const m=new Set([...p].filter(x=>f.has(x)));return m.size===p.size?p:m})},[c]);const d=g.useCallback(f=>{h(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return a.jsxs(we,{className:"mt-2",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[a.jsxs("h3",{className:"text-sm font-semibold",children:["État live",a.jsx("span",{className:"ml-2 rounded bg-canvas px-1.5 py-0.5 text-[0.6rem] uppercase text-muted",children:"read-only"})]}),a.jsx(M,{variant:"ghost",size:"sm",loading:n.busy,onClick:()=>void n.refresh(),children:"Rafraîchir"})]}),n.error&&a.jsx("p",{role:"alert",className:"mb-2 text-xs text-danger",children:n.error}),n.busy&&n.state===null?a.jsx("p",{className:"text-xs text-muted",children:"Chargement de l'état…"}):c.length===0?a.jsx("p",{className:"text-xs text-muted",children:"Aucun agent actif."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"web-workstate",children:c.map(f=>a.jsx(r4,{agent:f,open:r===f.agentId,onToggleOpen:()=>{i(p=>p===f.agentId?null:f.agentId),o()},onRefresh:n.refresh,bgExpanded:u.has(f.agentId),onToggleBgExpanded:()=>d(f.agentId)},f.agentId))}),t&&r&&a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[a.jsx("span",{className:"text-xs font-semibold text-muted",children:"Agent"}),a.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{i(null),o()},children:"Fermer"})]}),a.jsx(OB,{projectId:e,agentId:r,cwd:t,refitSignal:s},r)]})]})}function r4({agent:e,open:t,onToggleOpen:n,onRefresh:r,bgExpanded:i,onToggleBgExpanded:s}){const l=e.live!==void 0,o=e.busy?.state==="busy",c=[...e.inbox??[]].sort((h,d)=>h.createdAtMs-d.createdAtMs),u=[...e.backgroundTasks??[]].sort((h,d)=>d.updatedAtMs-h.updatedAtMs||h.taskId.localeCompare(d.taskId));return a.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between sm:gap-2",children:[a.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:e.name}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-xs",children:[a.jsx("span",{className:q("rounded-full px-2 py-0.5 font-medium",l?"bg-success/15 text-success":"bg-raised text-muted"),children:l?"Live":"Offline"}),a.jsx("span",{className:q("rounded-full px-2 py-0.5 font-medium",o?"bg-warning/15 text-warning":"bg-raised text-muted"),children:o?"Busy":"Idle"}),a.jsx(M,{variant:"ghost",size:"sm","aria-pressed":t,onClick:n,children:t?"Fermer":"Ouvrir"})]})]}),c.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),a.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:c.map(h=>a.jsxs("li",{className:"flex min-w-0 items-start gap-2 text-xs text-muted",children:[a.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium",children:h.kind}),a.jsx("span",{className:"min-w-0 flex-1 break-words",children:h.body})]},h.id))})]}),u.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsxs("button",{type:"button","aria-expanded":i,"aria-controls":`web-bg-tasks-${e.agentId}`,"aria-label":i?`Masquer les background tasks de ${e.name}`:`Afficher les background tasks de ${e.name}`,onClick:s,className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-faint hover:text-muted",children:[a.jsx("span",{"aria-hidden":"true",children:i?"▾":"▸"}),"Background tasks",a.jsx("span",{className:"rounded-full bg-raised px-1.5 py-0.5 font-medium normal-case tracking-normal text-muted",children:u.length})]}),i&&a.jsx("ul",{id:`web-bg-tasks-${e.agentId}`,"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:u.map(h=>a.jsx(l4,{task:h,onRefresh:r},h.taskId))})]})]})}const i4={running:"Running",completed:"Completed",failed:"Failed",cancelled:"Cancelled",pending:"Pending",delivered:"Delivered"};function s4(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function l4({task:e,onRefresh:t}){const{workState:n}=he(),[r,i]=g.useState(!1),[s,l]=g.useState(null),o=e.status==="running"||e.status==="pending",c=e.status==="failed"||e.status==="cancelled";async function u(h){i(!0),l(null);try{await h(e.taskId),await t()}catch(d){l(xo(d))}finally{i(!1)}}return a.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx("span",{className:q("shrink-0 rounded-full px-1.5 py-0.5 font-medium",s4(e.status)),children:i4[e.status]}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:e.kind})]}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-1",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:!o||r,loading:r,onClick:()=>void u(h=>n.cancelBackgroundTask(h)),children:"Cancel"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!c||r,loading:r,onClick:()=>void u(h=>n.retryBackgroundTask(h)),children:"Retry"})]})]}),s&&a.jsx("p",{role:"alert",className:"mt-1 text-danger",children:s})]})}const Ka={aiProfiles:"Profils IA",devices:"Appareils"};function a4({session:e}={}){const t=e??ow(),[n,r]=g.useState(()=>t.isPaired()),[i,s]=g.useState(!1),[l,o]=g.useState(null),[c,u]=g.useState(!1);g.useEffect(()=>t.onUnauthorized(()=>{o(null),u(!1),r(!1)}),[t]);async function h(){if(!i){s(!0);try{await t.logout()}finally{sx(),s(!1),o(null),u(!1),r(!1)}}}const d=g.useCallback(()=>{t.forget(),sx(),o(null),u(!1),r(!1)},[t]);return a.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[a.jsxs("header",{"data-testid":"web-header",className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:px-6",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("h1",{className:"text-base font-semibold tracking-tight sm:text-lg",children:"IdeA"}),a.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"web"})]}),n&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(M,{variant:"ghost",size:"sm","aria-pressed":c,onClick:()=>u(!0),children:"Paramètres"}),a.jsx(M,{variant:"ghost",size:"sm",loading:i,onClick:()=>void h(),children:"Se déconnecter"})]})]}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:n?l==="aiProfiles"?a.jsx(Xv,{title:Ka.aiProfiles,onBack:()=>o(null),children:a.jsx(kw,{})}):l==="devices"?a.jsx(Xv,{title:Ka.devices,onBack:()=>o(null),children:a.jsx(Nw,{onSessionEnded:d})}):a.jsx(JB,{}):a.jsx(RB,{session:t,onPaired:()=>r(!0)})}),c&&a.jsx(u0,{title:"Paramètres",onClose:()=>u(!1),entries:[{id:"aiProfiles",label:Ka.aiProfiles,active:l==="aiProfiles",onSelect:()=>{o("aiProfiles"),u(!1)}},{id:"devices",label:Ka.devices,active:l==="devices",onSelect:()=>{o("devices"),u(!1)}},{id:"deployment",label:"Déploiement",active:!1,disabled:!0,secondaryLabel:"Desktop uniquement",hint:"Desktop uniquement",onSelect:()=>{}}]})]})}function Xv({title:e,onBack:t,children:n}){return a.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2 pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))]",children:[a.jsx(M,{variant:"ghost",size:"sm",onClick:t,children:"← Retour"}),a.jsx("span",{className:"text-sm font-medium text-content",children:e})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:a.jsx("div",{className:"mx-auto w-full max-w-xl",children:n})})]})}const d0=document.getElementById("root");if(!d0)throw new Error("missing #root element");const Qv=TB(window.location.search);window.__IDEA_TRANSPORT__="http";const o4=uw()==="http";nd.createRoot(d0).render(a.jsx(P0.StrictMode,{children:a.jsx(uP,{children:o4?a.jsx(a4,{}):Qv?a.jsx(LB,{panel:Qv.panel}):a.jsx(EB,{})})})); diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-DylfUO7l.css b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-DylfUO7l.css deleted file mode 100644 index 9c37aae..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-DylfUO7l.css +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2014 The xterm.js authors. All rights reserved. - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * https://github.com/chjj/term.js - * @license MIT - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - * The original design remains. The terminal itself - * has been extended to include xterm CSI codes, among - * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;inset:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;inset:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--font-mono:"JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-normal:0em;--tracking-wide:.025em;--radius-md:.375rem;--radius-lg:.5rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-canvas:#0e1116;--color-surface:#161b22;--color-raised:#1c2430;--color-border:#2b3440;--color-border-strong:#3b4757;--color-content:#e6edf3;--color-muted:#9aa7b4;--color-faint:#6b7785;--color-primary:#4c8dff;--color-primary-hover:#3b7bf0;--color-on-primary:#fff;--color-danger:#f85149;--color-success:#3fb950;--color-warning:#d29922}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}:root{color-scheme:dark}html,body,#root{height:100%}@supports (height:100dvh){html,body,#root{height:100dvh}}body{background-color:var(--color-canvas);color:var(--color-content);font-family:var(--font-sans);-webkit-font-smoothing:antialiased;overscroll-behavior-y:none;margin:0}:focus-visible{outline:2px solid var(--color-primary);outline-offset:1px}}@layer components;@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing) * 0)}.top-0{top:calc(var(--spacing) * 0)}.top-full{top:100%}.right-0{right:calc(var(--spacing) * 0)}.right-4{right:calc(var(--spacing) * 4)}.bottom-0{bottom:calc(var(--spacing) * 0)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:calc(var(--spacing) * 0)}.left-full{left:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[4\]{z-index:4}.z-\[60\]{z-index:60}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-auto{margin:auto}.-mx-4{margin-inline:calc(var(--spacing) * -4)}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.-mb-4{margin-bottom:calc(var(--spacing) * -4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.size-1\.5{width:calc(var(--spacing) * 1.5);height:calc(var(--spacing) * 1.5)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-4{height:calc(var(--spacing) * 4)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-32{height:calc(var(--spacing) * 32)}.h-64{height:calc(var(--spacing) * 64)}.h-96{height:calc(var(--spacing) * 96)}.h-\[60dvh\]{height:60dvh}.h-full{height:100%}.max-h-40{max-height:calc(var(--spacing) * 40)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[80vh\]{max-height:80vh}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-10{min-height:calc(var(--spacing) * 10)}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-20{min-height:calc(var(--spacing) * 20)}.min-h-24{min-height:calc(var(--spacing) * 24)}.min-h-32{min-height:calc(var(--spacing) * 32)}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-64{min-height:calc(var(--spacing) * 64)}.min-h-\[32px\]{min-height:32px}.min-h-\[40px\]{min-height:40px}.min-h-\[44px\]{min-height:44px}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-3{width:calc(var(--spacing) * 3)}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-24{width:calc(var(--spacing) * 24)}.w-28{width:calc(var(--spacing) * 28)}.w-40{width:calc(var(--spacing) * 40)}.w-48{width:calc(var(--spacing) * 48)}.w-52{width:calc(var(--spacing) * 52)}.w-80{width:calc(var(--spacing) * 80)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[80\%\]{max-width:80%}.max-w-\[85\%\]{max-width:85%}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100vw-2rem\)\]{max-width:calc(100vw - 2rem)}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-32{min-width:calc(var(--spacing) * 32)}.min-w-36{min-width:calc(var(--spacing) * 36)}.min-w-44{min-width:calc(var(--spacing) * 44)}.min-w-48{min-width:calc(var(--spacing) * 48)}.min-w-80{min-width:calc(var(--spacing) * 80)}.min-w-\[6rem\]{min-width:6rem}.min-w-\[8rem\]{min-width:8rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[440px\]{min-width:440px}.min-w-max{min-width:max-content}.flex-1{flex:1}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-col-resize{cursor:col-resize}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-\[4\.5rem_1fr\]{grid-template-columns:4.5rem 1fr}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0{gap:calc(var(--spacing) * 0)}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-border>:not(:last-child)){border-color:var(--color-border)}.self-end{align-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-md{border-top-left-radius:var(--radius-md);border-top-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-border{border-color:var(--color-border)}.border-border-strong{border-color:var(--color-border-strong)}.border-border\/50{border-color:#2b344080}@supports (color:color-mix(in lab,red,red)){.border-border\/50{border-color:color-mix(in oklab,var(--color-border) 50%,transparent)}}.border-border\/60{border-color:#2b344099}@supports (color:color-mix(in lab,red,red)){.border-border\/60{border-color:color-mix(in oklab,var(--color-border) 60%,transparent)}}.border-border\/70{border-color:#2b3440b3}@supports (color:color-mix(in lab,red,red)){.border-border\/70{border-color:color-mix(in oklab,var(--color-border) 70%,transparent)}}.border-current{border-color:currentColor}.border-danger{border-color:var(--color-danger)}.border-danger\/40{border-color:#f8514966}@supports (color:color-mix(in lab,red,red)){.border-danger\/40{border-color:color-mix(in oklab,var(--color-danger) 40%,transparent)}}.border-primary{border-color:var(--color-primary)}.border-primary\/20{border-color:#4c8dff33}@supports (color:color-mix(in lab,red,red)){.border-primary\/20{border-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.border-primary\/25{border-color:#4c8dff40}@supports (color:color-mix(in lab,red,red)){.border-primary\/25{border-color:color-mix(in oklab,var(--color-primary) 25%,transparent)}}.border-primary\/40{border-color:#4c8dff66}@supports (color:color-mix(in lab,red,red)){.border-primary\/40{border-color:color-mix(in oklab,var(--color-primary) 40%,transparent)}}.border-transparent{border-color:#0000}.border-warning\/40{border-color:#d2992266}@supports (color:color-mix(in lab,red,red)){.border-warning\/40{border-color:color-mix(in oklab,var(--color-warning) 40%,transparent)}}.border-t-transparent{border-top-color:#0000}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-black\/55{background-color:#0000008c}@supports (color:color-mix(in lab,red,red)){.bg-black\/55{background-color:color-mix(in oklab,var(--color-black) 55%,transparent)}}.bg-border{background-color:var(--color-border)}.bg-canvas{background-color:var(--color-canvas)}.bg-canvas\/85{background-color:#0e1116d9}@supports (color:color-mix(in lab,red,red)){.bg-canvas\/85{background-color:color-mix(in oklab,var(--color-canvas) 85%,transparent)}}.bg-danger{background-color:var(--color-danger)}.bg-danger\/10{background-color:#f851491a}@supports (color:color-mix(in lab,red,red)){.bg-danger\/10{background-color:color-mix(in oklab,var(--color-danger) 10%,transparent)}}.bg-danger\/15{background-color:#f8514926}@supports (color:color-mix(in lab,red,red)){.bg-danger\/15{background-color:color-mix(in oklab,var(--color-danger) 15%,transparent)}}.bg-danger\/20{background-color:#f8514933}@supports (color:color-mix(in lab,red,red)){.bg-danger\/20{background-color:color-mix(in oklab,var(--color-danger) 20%,transparent)}}.bg-faint{background-color:var(--color-faint)}.bg-muted\/15{background-color:#9aa7b426}@supports (color:color-mix(in lab,red,red)){.bg-muted\/15{background-color:color-mix(in oklab,var(--color-muted) 15%,transparent)}}.bg-muted\/20{background-color:#9aa7b433}@supports (color:color-mix(in lab,red,red)){.bg-muted\/20{background-color:color-mix(in oklab,var(--color-muted) 20%,transparent)}}.bg-primary{background-color:var(--color-primary)}.bg-primary\/5{background-color:#4c8dff0d}@supports (color:color-mix(in lab,red,red)){.bg-primary\/5{background-color:color-mix(in oklab,var(--color-primary) 5%,transparent)}}.bg-primary\/10{background-color:#4c8dff1a}@supports (color:color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}}.bg-primary\/15{background-color:#4c8dff26}@supports (color:color-mix(in lab,red,red)){.bg-primary\/15{background-color:color-mix(in oklab,var(--color-primary) 15%,transparent)}}.bg-primary\/20{background-color:#4c8dff33}@supports (color:color-mix(in lab,red,red)){.bg-primary\/20{background-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.bg-raised{background-color:var(--color-raised)}.bg-raised\/40{background-color:#1c243066}@supports (color:color-mix(in lab,red,red)){.bg-raised\/40{background-color:color-mix(in oklab,var(--color-raised) 40%,transparent)}}.bg-raised\/50{background-color:#1c243080}@supports (color:color-mix(in lab,red,red)){.bg-raised\/50{background-color:color-mix(in oklab,var(--color-raised) 50%,transparent)}}.bg-success{background-color:var(--color-success)}.bg-success\/10{background-color:#3fb9501a}@supports (color:color-mix(in lab,red,red)){.bg-success\/10{background-color:color-mix(in oklab,var(--color-success) 10%,transparent)}}.bg-success\/15{background-color:#3fb95026}@supports (color:color-mix(in lab,red,red)){.bg-success\/15{background-color:color-mix(in oklab,var(--color-success) 15%,transparent)}}.bg-success\/20{background-color:#3fb95033}@supports (color:color-mix(in lab,red,red)){.bg-success\/20{background-color:color-mix(in oklab,var(--color-success) 20%,transparent)}}.bg-surface{background-color:var(--color-surface)}.bg-surface\/60{background-color:#161b2299}@supports (color:color-mix(in lab,red,red)){.bg-surface\/60{background-color:color-mix(in oklab,var(--color-surface) 60%,transparent)}}.bg-surface\/80{background-color:#161b22cc}@supports (color:color-mix(in lab,red,red)){.bg-surface\/80{background-color:color-mix(in oklab,var(--color-surface) 80%,transparent)}}.bg-warning{background-color:var(--color-warning)}.bg-warning\/10{background-color:#d299221a}@supports (color:color-mix(in lab,red,red)){.bg-warning\/10{background-color:color-mix(in oklab,var(--color-warning) 10%,transparent)}}.bg-warning\/15{background-color:#d2992226}@supports (color:color-mix(in lab,red,red)){.bg-warning\/15{background-color:color-mix(in oklab,var(--color-warning) 15%,transparent)}}.bg-warning\/20{background-color:#d2992233}@supports (color:color-mix(in lab,red,red)){.bg-warning\/20{background-color:color-mix(in oklab,var(--color-warning) 20%,transparent)}}.fill-canvas{fill:var(--color-canvas)}.p-0{padding:calc(var(--spacing) * 0)}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-10{padding-block:calc(var(--spacing) * 10)}.pt-1{padding-top:calc(var(--spacing) * 1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-\[max\(0\.75rem\,env\(safe-area-inset-top\)\)\]{padding-top:max(.75rem,env(safe-area-inset-top))}.pr-\[max\(1rem\,env\(safe-area-inset-right\)\)\]{padding-right:max(1rem,env(safe-area-inset-right))}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pb-\[max\(0\.5rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.5rem,env(safe-area-inset-bottom))}.pb-\[max\(0\.75rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.75rem,env(safe-area-inset-bottom))}.pb-\[max\(1rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(1rem,env(safe-area-inset-bottom))}.pl-1{padding-left:calc(var(--spacing) * 1)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-\[max\(1rem\,env\(safe-area-inset-left\)\)\]{padding-left:max(1rem,env(safe-area-inset-left))}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[0\.6rem\]{font-size:.6rem}.text-\[0\.7rem\]{font-size:.7rem}.text-\[0\.65rem\]{font-size:.65rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.2em\]{--tw-tracking:.2em;letter-spacing:.2em}.tracking-normal{--tw-tracking:var(--tracking-normal);letter-spacing:var(--tracking-normal)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.text-content{color:var(--color-content)}.text-content\/90{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.text-content\/90{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.text-danger{color:var(--color-danger)}.text-danger\/80{color:#f85149cc}@supports (color:color-mix(in lab,red,red)){.text-danger\/80{color:color-mix(in oklab,var(--color-danger) 80%,transparent)}}.text-faint{color:var(--color-faint)}.text-muted{color:var(--color-muted)}.text-on-primary{color:var(--color-on-primary)}.text-primary{color:var(--color-primary)}.text-success{color:var(--color-success)}.text-transparent{color:#0000}.text-warning{color:var(--color-warning)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.normal-case{text-transform:none}.uppercase{text-transform:uppercase}.italic{font-style:italic}.underline{text-decoration-line:underline}.accent-primary{accent-color:var(--color-primary)}.opacity-20{opacity:.2}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-border-strong{--tw-ring-color:var(--color-border-strong)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.placeholder\:text-faint::placeholder{color:var(--color-faint)}.first\:pt-0:first-child{padding-top:calc(var(--spacing) * 0)}.last\:border-r-0:last-child{border-right-style:var(--tw-border-style);border-right-width:0}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.last\:pb-0:last-child{padding-bottom:calc(var(--spacing) * 0)}@media (hover:hover){.hover\:border-border:hover{border-color:var(--color-border)}.hover\:border-border-strong:hover{border-color:var(--color-border-strong)}.hover\:border-primary:hover{border-color:var(--color-primary)}.hover\:bg-border-strong:hover{background-color:var(--color-border-strong)}.hover\:bg-canvas:hover{background-color:var(--color-canvas)}.hover\:bg-primary-hover:hover{background-color:var(--color-primary-hover)}.hover\:bg-primary\/15:hover{background-color:#4c8dff26}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/15:hover{background-color:color-mix(in oklab,var(--color-primary) 15%,transparent)}}.hover\:bg-raised:hover{background-color:var(--color-raised)}.hover\:text-content:hover{color:var(--color-content)}.hover\:text-danger:hover{color:var(--color-danger)}.hover\:text-muted:hover{color:var(--color-muted)}.hover\:text-primary:hover{color:var(--color-primary)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:brightness-110:hover{--tw-brightness:brightness(110%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}}.focus\:border-primary:focus{border-color:var(--color-primary)}.focus\:bg-raised:focus{background-color:var(--color-raised)}.focus\:ring-1:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-primary:focus{--tw-ring-color:var(--color-primary)}.focus\:outline-none:focus,.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}@media (hover:hover){.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}.aria-pressed\:border-primary[aria-pressed=true]{border-color:var(--color-primary)}@media (min-width:40rem){.sm\:h-80{height:calc(var(--spacing) * 80)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:calc(var(--spacing) * 2)}.sm\:p-6{padding:calc(var(--spacing) * 6)}.sm\:px-6{padding-inline:calc(var(--spacing) * 6)}.sm\:text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.sm\:text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}}@media (min-width:48rem){.md\:w-56{width:calc(var(--spacing) * 56)}.md\:flex-row{flex-direction:row}}.\[\&_a\]\:text-primary a{color:var(--color-primary)}.\[\&_a\:hover\]\:underline a:hover{text-decoration-line:underline}.\[\&_blockquote\]\:border-l-2 blockquote{border-left-style:var(--tw-border-style);border-left-width:2px}.\[\&_blockquote\]\:border-primary blockquote{border-color:var(--color-primary)}.\[\&_blockquote\]\:text-muted blockquote{color:var(--color-muted)}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-canvas code{background-color:var(--color-canvas)}.\[\&_code\]\:px-1 code{padding-inline:calc(var(--spacing) * 1)}.\[\&_code\]\:text-primary code{color:var(--color-primary)}.\[\&_h1\]\:text-content h1,.\[\&_h2\]\:text-content h2,.\[\&_h3\]\:text-content h3{color:var(--color-content)}.\[\&_hr\]\:border-border hr{border-color:var(--color-border)}.\[\&_li\]\:text-content\/90 li{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.\[\&_li\]\:text-content\/90 li{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.\[\&_p\]\:text-content\/90 p{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.\[\&_p\]\:text-content\/90 p{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.\[\&_pre\]\:rounded-md pre{border-radius:var(--radius-md)}.\[\&_pre\]\:border pre{border-style:var(--tw-border-style);border-width:1px}.\[\&_pre\]\:border-border pre{border-color:var(--color-border)}.\[\&_pre\]\:bg-canvas pre{background-color:var(--color-canvas)}}@keyframes model-server-indeterminate{0%{left:-40%}to{left:100%}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}} diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-exS7kWj-.css b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-exS7kWj-.css deleted file mode 100644 index 8f17035..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-exS7kWj-.css +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2014 The xterm.js authors. All rights reserved. - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * https://github.com/chjj/term.js - * @license MIT - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - * The original design remains. The terminal itself - * has been extended to include xterm CSI codes, among - * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;inset:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;inset:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--font-mono:"JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-normal:0em;--tracking-wide:.025em;--radius-md:.375rem;--radius-lg:.5rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-canvas:#0e1116;--color-surface:#161b22;--color-raised:#1c2430;--color-border:#2b3440;--color-border-strong:#3b4757;--color-content:#e6edf3;--color-muted:#9aa7b4;--color-faint:#6b7785;--color-primary:#4c8dff;--color-primary-hover:#3b7bf0;--color-on-primary:#fff;--color-danger:#f85149;--color-success:#3fb950;--color-warning:#d29922}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}:root{color-scheme:dark}html,body,#root{height:100%}@supports (height:100dvh){html,body,#root{height:100dvh}}body{background-color:var(--color-canvas);color:var(--color-content);font-family:var(--font-sans);-webkit-font-smoothing:antialiased;overscroll-behavior-y:none;margin:0}:focus-visible{outline:2px solid var(--color-primary);outline-offset:1px}}@layer components;@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing) * 0)}.top-0{top:calc(var(--spacing) * 0)}.top-full{top:100%}.right-0{right:calc(var(--spacing) * 0)}.right-4{right:calc(var(--spacing) * 4)}.bottom-0{bottom:calc(var(--spacing) * 0)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:calc(var(--spacing) * 0)}.left-full{left:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[4\]{z-index:4}.z-\[60\]{z-index:60}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-auto{margin:auto}.-mx-4{margin-inline:calc(var(--spacing) * -4)}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.-mb-4{margin-bottom:calc(var(--spacing) * -4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.size-1\.5{width:calc(var(--spacing) * 1.5);height:calc(var(--spacing) * 1.5)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-4{height:calc(var(--spacing) * 4)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-32{height:calc(var(--spacing) * 32)}.h-64{height:calc(var(--spacing) * 64)}.h-96{height:calc(var(--spacing) * 96)}.h-\[60dvh\]{height:60dvh}.h-full{height:100%}.max-h-40{max-height:calc(var(--spacing) * 40)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[80vh\]{max-height:80vh}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-10{min-height:calc(var(--spacing) * 10)}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-20{min-height:calc(var(--spacing) * 20)}.min-h-24{min-height:calc(var(--spacing) * 24)}.min-h-32{min-height:calc(var(--spacing) * 32)}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-64{min-height:calc(var(--spacing) * 64)}.min-h-\[32px\]{min-height:32px}.min-h-\[40px\]{min-height:40px}.min-h-\[44px\]{min-height:44px}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-3{width:calc(var(--spacing) * 3)}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-24{width:calc(var(--spacing) * 24)}.w-28{width:calc(var(--spacing) * 28)}.w-40{width:calc(var(--spacing) * 40)}.w-48{width:calc(var(--spacing) * 48)}.w-52{width:calc(var(--spacing) * 52)}.w-80{width:calc(var(--spacing) * 80)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[80\%\]{max-width:80%}.max-w-\[85\%\]{max-width:85%}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100vw-2rem\)\]{max-width:calc(100vw - 2rem)}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-32{min-width:calc(var(--spacing) * 32)}.min-w-36{min-width:calc(var(--spacing) * 36)}.min-w-44{min-width:calc(var(--spacing) * 44)}.min-w-48{min-width:calc(var(--spacing) * 48)}.min-w-80{min-width:calc(var(--spacing) * 80)}.min-w-\[6rem\]{min-width:6rem}.min-w-\[8rem\]{min-width:8rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[440px\]{min-width:440px}.min-w-max{min-width:max-content}.flex-1{flex:1}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-col-resize{cursor:col-resize}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-\[4\.5rem_1fr\]{grid-template-columns:4.5rem 1fr}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0{gap:calc(var(--spacing) * 0)}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-border>:not(:last-child)){border-color:var(--color-border)}.self-end{align-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-md{border-top-left-radius:var(--radius-md);border-top-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-border{border-color:var(--color-border)}.border-border-strong{border-color:var(--color-border-strong)}.border-border\/50{border-color:#2b344080}@supports (color:color-mix(in lab,red,red)){.border-border\/50{border-color:color-mix(in oklab,var(--color-border) 50%,transparent)}}.border-border\/60{border-color:#2b344099}@supports (color:color-mix(in lab,red,red)){.border-border\/60{border-color:color-mix(in oklab,var(--color-border) 60%,transparent)}}.border-border\/70{border-color:#2b3440b3}@supports (color:color-mix(in lab,red,red)){.border-border\/70{border-color:color-mix(in oklab,var(--color-border) 70%,transparent)}}.border-current{border-color:currentColor}.border-danger{border-color:var(--color-danger)}.border-danger\/40{border-color:#f8514966}@supports (color:color-mix(in lab,red,red)){.border-danger\/40{border-color:color-mix(in oklab,var(--color-danger) 40%,transparent)}}.border-primary{border-color:var(--color-primary)}.border-primary\/20{border-color:#4c8dff33}@supports (color:color-mix(in lab,red,red)){.border-primary\/20{border-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.border-primary\/25{border-color:#4c8dff40}@supports (color:color-mix(in lab,red,red)){.border-primary\/25{border-color:color-mix(in oklab,var(--color-primary) 25%,transparent)}}.border-primary\/40{border-color:#4c8dff66}@supports (color:color-mix(in lab,red,red)){.border-primary\/40{border-color:color-mix(in oklab,var(--color-primary) 40%,transparent)}}.border-transparent{border-color:#0000}.border-warning\/40{border-color:#d2992266}@supports (color:color-mix(in lab,red,red)){.border-warning\/40{border-color:color-mix(in oklab,var(--color-warning) 40%,transparent)}}.border-t-transparent{border-top-color:#0000}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-black\/55{background-color:#0000008c}@supports (color:color-mix(in lab,red,red)){.bg-black\/55{background-color:color-mix(in oklab,var(--color-black) 55%,transparent)}}.bg-border{background-color:var(--color-border)}.bg-canvas{background-color:var(--color-canvas)}.bg-canvas\/85{background-color:#0e1116d9}@supports (color:color-mix(in lab,red,red)){.bg-canvas\/85{background-color:color-mix(in oklab,var(--color-canvas) 85%,transparent)}}.bg-danger{background-color:var(--color-danger)}.bg-danger\/10{background-color:#f851491a}@supports (color:color-mix(in lab,red,red)){.bg-danger\/10{background-color:color-mix(in oklab,var(--color-danger) 10%,transparent)}}.bg-danger\/15{background-color:#f8514926}@supports (color:color-mix(in lab,red,red)){.bg-danger\/15{background-color:color-mix(in oklab,var(--color-danger) 15%,transparent)}}.bg-danger\/20{background-color:#f8514933}@supports (color:color-mix(in lab,red,red)){.bg-danger\/20{background-color:color-mix(in oklab,var(--color-danger) 20%,transparent)}}.bg-faint{background-color:var(--color-faint)}.bg-muted\/15{background-color:#9aa7b426}@supports (color:color-mix(in lab,red,red)){.bg-muted\/15{background-color:color-mix(in oklab,var(--color-muted) 15%,transparent)}}.bg-muted\/20{background-color:#9aa7b433}@supports (color:color-mix(in lab,red,red)){.bg-muted\/20{background-color:color-mix(in oklab,var(--color-muted) 20%,transparent)}}.bg-primary{background-color:var(--color-primary)}.bg-primary\/5{background-color:#4c8dff0d}@supports (color:color-mix(in lab,red,red)){.bg-primary\/5{background-color:color-mix(in oklab,var(--color-primary) 5%,transparent)}}.bg-primary\/10{background-color:#4c8dff1a}@supports (color:color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}}.bg-primary\/15{background-color:#4c8dff26}@supports (color:color-mix(in lab,red,red)){.bg-primary\/15{background-color:color-mix(in oklab,var(--color-primary) 15%,transparent)}}.bg-primary\/20{background-color:#4c8dff33}@supports (color:color-mix(in lab,red,red)){.bg-primary\/20{background-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.bg-raised{background-color:var(--color-raised)}.bg-raised\/40{background-color:#1c243066}@supports (color:color-mix(in lab,red,red)){.bg-raised\/40{background-color:color-mix(in oklab,var(--color-raised) 40%,transparent)}}.bg-raised\/50{background-color:#1c243080}@supports (color:color-mix(in lab,red,red)){.bg-raised\/50{background-color:color-mix(in oklab,var(--color-raised) 50%,transparent)}}.bg-success{background-color:var(--color-success)}.bg-success\/10{background-color:#3fb9501a}@supports (color:color-mix(in lab,red,red)){.bg-success\/10{background-color:color-mix(in oklab,var(--color-success) 10%,transparent)}}.bg-success\/15{background-color:#3fb95026}@supports (color:color-mix(in lab,red,red)){.bg-success\/15{background-color:color-mix(in oklab,var(--color-success) 15%,transparent)}}.bg-success\/20{background-color:#3fb95033}@supports (color:color-mix(in lab,red,red)){.bg-success\/20{background-color:color-mix(in oklab,var(--color-success) 20%,transparent)}}.bg-surface{background-color:var(--color-surface)}.bg-surface\/60{background-color:#161b2299}@supports (color:color-mix(in lab,red,red)){.bg-surface\/60{background-color:color-mix(in oklab,var(--color-surface) 60%,transparent)}}.bg-surface\/80{background-color:#161b22cc}@supports (color:color-mix(in lab,red,red)){.bg-surface\/80{background-color:color-mix(in oklab,var(--color-surface) 80%,transparent)}}.bg-warning{background-color:var(--color-warning)}.bg-warning\/10{background-color:#d299221a}@supports (color:color-mix(in lab,red,red)){.bg-warning\/10{background-color:color-mix(in oklab,var(--color-warning) 10%,transparent)}}.bg-warning\/15{background-color:#d2992226}@supports (color:color-mix(in lab,red,red)){.bg-warning\/15{background-color:color-mix(in oklab,var(--color-warning) 15%,transparent)}}.bg-warning\/20{background-color:#d2992233}@supports (color:color-mix(in lab,red,red)){.bg-warning\/20{background-color:color-mix(in oklab,var(--color-warning) 20%,transparent)}}.fill-canvas{fill:var(--color-canvas)}.p-0{padding:calc(var(--spacing) * 0)}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-10{padding-block:calc(var(--spacing) * 10)}.pt-1{padding-top:calc(var(--spacing) * 1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-\[max\(0\.75rem\,env\(safe-area-inset-top\)\)\]{padding-top:max(.75rem,env(safe-area-inset-top))}.pr-\[max\(1rem\,env\(safe-area-inset-right\)\)\]{padding-right:max(1rem,env(safe-area-inset-right))}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pb-\[max\(0\.5rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.5rem,env(safe-area-inset-bottom))}.pb-\[max\(0\.75rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.75rem,env(safe-area-inset-bottom))}.pb-\[max\(1rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(1rem,env(safe-area-inset-bottom))}.pl-1{padding-left:calc(var(--spacing) * 1)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-\[max\(1rem\,env\(safe-area-inset-left\)\)\]{padding-left:max(1rem,env(safe-area-inset-left))}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[0\.6rem\]{font-size:.6rem}.text-\[0\.7rem\]{font-size:.7rem}.text-\[0\.65rem\]{font-size:.65rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.2em\]{--tw-tracking:.2em;letter-spacing:.2em}.tracking-normal{--tw-tracking:var(--tracking-normal);letter-spacing:var(--tracking-normal)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.text-content{color:var(--color-content)}.text-content\/90{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.text-content\/90{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.text-danger{color:var(--color-danger)}.text-danger\/80{color:#f85149cc}@supports (color:color-mix(in lab,red,red)){.text-danger\/80{color:color-mix(in oklab,var(--color-danger) 80%,transparent)}}.text-faint{color:var(--color-faint)}.text-muted{color:var(--color-muted)}.text-on-primary{color:var(--color-on-primary)}.text-primary{color:var(--color-primary)}.text-success{color:var(--color-success)}.text-transparent{color:#0000}.text-warning{color:var(--color-warning)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.normal-case{text-transform:none}.uppercase{text-transform:uppercase}.italic{font-style:italic}.underline{text-decoration-line:underline}.accent-primary{accent-color:var(--color-primary)}.opacity-20{opacity:.2}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-border-strong{--tw-ring-color:var(--color-border-strong)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.placeholder\:text-faint::placeholder{color:var(--color-faint)}.first\:pt-0:first-child{padding-top:calc(var(--spacing) * 0)}.last\:border-r-0:last-child{border-right-style:var(--tw-border-style);border-right-width:0}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.last\:pb-0:last-child{padding-bottom:calc(var(--spacing) * 0)}@media (hover:hover){.hover\:border-border:hover{border-color:var(--color-border)}.hover\:border-border-strong:hover{border-color:var(--color-border-strong)}.hover\:border-primary:hover{border-color:var(--color-primary)}.hover\:bg-border-strong:hover{background-color:var(--color-border-strong)}.hover\:bg-canvas:hover{background-color:var(--color-canvas)}.hover\:bg-primary-hover:hover{background-color:var(--color-primary-hover)}.hover\:bg-primary\/15:hover{background-color:#4c8dff26}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/15:hover{background-color:color-mix(in oklab,var(--color-primary) 15%,transparent)}}.hover\:bg-raised:hover{background-color:var(--color-raised)}.hover\:text-content:hover{color:var(--color-content)}.hover\:text-danger:hover{color:var(--color-danger)}.hover\:text-muted:hover{color:var(--color-muted)}.hover\:text-primary:hover{color:var(--color-primary)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:brightness-110:hover{--tw-brightness:brightness(110%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}}.focus\:border-primary:focus{border-color:var(--color-primary)}.focus\:bg-raised:focus{background-color:var(--color-raised)}.focus\:ring-1:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-primary:focus{--tw-ring-color:var(--color-primary)}.focus\:outline-none:focus,.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}@media (hover:hover){.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}.aria-pressed\:border-primary[aria-pressed=true]{border-color:var(--color-primary)}@media (min-width:40rem){.sm\:h-80{height:calc(var(--spacing) * 80)}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:calc(var(--spacing) * 2)}.sm\:p-6{padding:calc(var(--spacing) * 6)}.sm\:px-6{padding-inline:calc(var(--spacing) * 6)}.sm\:text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.sm\:text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}}@media (min-width:48rem){.md\:w-56{width:calc(var(--spacing) * 56)}.md\:flex-row{flex-direction:row}}.\[\&_a\]\:text-primary a{color:var(--color-primary)}.\[\&_a\:hover\]\:underline a:hover{text-decoration-line:underline}.\[\&_blockquote\]\:border-l-2 blockquote{border-left-style:var(--tw-border-style);border-left-width:2px}.\[\&_blockquote\]\:border-primary blockquote{border-color:var(--color-primary)}.\[\&_blockquote\]\:text-muted blockquote{color:var(--color-muted)}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-canvas code{background-color:var(--color-canvas)}.\[\&_code\]\:px-1 code{padding-inline:calc(var(--spacing) * 1)}.\[\&_code\]\:text-primary code{color:var(--color-primary)}.\[\&_h1\]\:text-content h1,.\[\&_h2\]\:text-content h2,.\[\&_h3\]\:text-content h3{color:var(--color-content)}.\[\&_hr\]\:border-border hr{border-color:var(--color-border)}.\[\&_li\]\:text-content\/90 li{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.\[\&_li\]\:text-content\/90 li{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.\[\&_p\]\:text-content\/90 p{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.\[\&_p\]\:text-content\/90 p{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.\[\&_pre\]\:rounded-md pre{border-radius:var(--radius-md)}.\[\&_pre\]\:border pre{border-style:var(--tw-border-style);border-width:1px}.\[\&_pre\]\:border-border pre{border-color:var(--color-border)}.\[\&_pre\]\:bg-canvas pre{background-color:var(--color-canvas)}}@keyframes model-server-indeterminate{0%{left:-40%}to{left:100%}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}} diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-nGdqV2l7.js b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-nGdqV2l7.js deleted file mode 100644 index 5e93d4b..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-nGdqV2l7.js +++ /dev/null @@ -1,128 +0,0 @@ -var h0=Object.defineProperty;var f0=(e,t,n)=>t in e?h0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var X=(e,t,n)=>f0(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const l of s.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var vo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ef(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jv={exports:{}},sc={},Zv={exports:{}},be={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ql=Symbol.for("react.element"),p0=Symbol.for("react.portal"),m0=Symbol.for("react.fragment"),g0=Symbol.for("react.strict_mode"),x0=Symbol.for("react.profiler"),v0=Symbol.for("react.provider"),_0=Symbol.for("react.context"),y0=Symbol.for("react.forward_ref"),b0=Symbol.for("react.suspense"),w0=Symbol.for("react.memo"),S0=Symbol.for("react.lazy"),Wp=Symbol.iterator;function k0(e){return e===null||typeof e!="object"?null:(e=Wp&&e[Wp]||e["@@iterator"],typeof e=="function"?e:null)}var e_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},t_=Object.assign,n_={};function _s(e,t,n){this.props=e,this.context=t,this.refs=n_,this.updater=n||e_}_s.prototype.isReactComponent={};_s.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};_s.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function r_(){}r_.prototype=_s.prototype;function tf(e,t,n){this.props=e,this.context=t,this.refs=n_,this.updater=n||e_}var nf=tf.prototype=new r_;nf.constructor=tf;t_(nf,_s.prototype);nf.isPureReactComponent=!0;var Hp=Array.isArray,i_=Object.prototype.hasOwnProperty,rf={current:null},s_={key:!0,ref:!0,__self:!0,__source:!0};function l_(e,t,n){var r,i={},s=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(s=""+t.key),t)i_.call(t,r)&&!s_.hasOwnProperty(r)&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1>>1,V=E[re];if(0>>1;rei(ee,j))Ji(W,ee)?(E[re]=W,E[J]=j,re=J):(E[re]=ee,E[ie]=j,re=ie);else if(Ji(W,j))E[re]=W,E[J]=j,re=J;else break e}}return F}function i(E,F){var j=E.sortIndex-F.sortIndex;return j!==0?j:E.id-F.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var l=Date,o=l.now();e.unstable_now=function(){return l.now()-o}}var c=[],u=[],h=1,d=null,f=3,p=!1,m=!1,x=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(E){for(var F=n(u);F!==null;){if(F.callback===null)r(u);else if(F.startTime<=E)r(u),F.sortIndex=F.expirationTime,t(c,F);else break;F=n(u)}}function b(E){if(x=!1,y(E),!m)if(n(c)!==null)m=!0,U(C);else{var F=n(u);F!==null&&K(b,F.startTime-E)}}function C(E,F){m=!1,x&&(x=!1,v(R),R=-1),p=!0;var j=f;try{for(y(F),d=n(c);d!==null&&(!(d.expirationTime>F)||E&&!L());){var re=d.callback;if(typeof re=="function"){d.callback=null,f=d.priorityLevel;var V=re(d.expirationTime<=F);F=e.unstable_now(),typeof V=="function"?d.callback=V:d===n(c)&&r(c),y(F)}else r(c);d=n(c)}if(d!==null)var T=!0;else{var ie=n(u);ie!==null&&K(b,ie.startTime-F),T=!1}return T}finally{d=null,f=j,p=!1}}var S=!1,N=null,R=-1,D=5,k=-1;function L(){return!(e.unstable_now()-kE||125re?(E.sortIndex=j,t(u,E),n(c)===null&&E===n(u)&&(x?(v(R),R=-1):x=!0,K(b,j-re))):(E.sortIndex=V,t(c,E),m||p||(m=!0,U(C))),E},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(E){var F=f;return function(){var j=f;f=F;try{return E.apply(this,arguments)}finally{f=j}}}})(d_);u_.exports=d_;var I0=u_.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var O0=g,on=I0;function Q(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rd=Object.prototype.hasOwnProperty,B0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,qp={},Vp={};function z0(e){return rd.call(Vp,e)?!0:rd.call(qp,e)?!1:B0.test(e)?Vp[e]=!0:(qp[e]=!0,!1)}function F0(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $0(e,t,n,r){if(t===null||typeof t>"u"||F0(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function zt(e,t,n,r,i,s,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=l}var St={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){St[e]=new zt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];St[t]=new zt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){St[e]=new zt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){St[e]=new zt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){St[e]=new zt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){St[e]=new zt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){St[e]=new zt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){St[e]=new zt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){St[e]=new zt(e,5,!1,e.toLowerCase(),null,!1,!1)});var lf=/[\-:]([a-z])/g;function af(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(lf,af);St[t]=new zt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(lf,af);St[t]=new zt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(lf,af);St[t]=new zt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){St[e]=new zt(e,1,!1,e.toLowerCase(),null,!1,!1)});St.xlinkHref=new zt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){St[e]=new zt(e,1,!1,e.toLowerCase(),null,!0,!0)});function of(e,t,n,r){var i=St.hasOwnProperty(t)?St[t]:null;(i!==null?i.type!==0:r||!(2o||i[l]!==s[o]){var c=` -`+i[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=o);break}}}finally{Oc=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?el(e):""}function W0(e){switch(e.tag){case 5:return el(e.type);case 16:return el("Lazy");case 13:return el("Suspense");case 19:return el("SuspenseList");case 0:case 2:case 15:return e=Bc(e.type,!1),e;case 11:return e=Bc(e.type.render,!1),e;case 1:return e=Bc(e.type,!0),e;default:return""}}function ad(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ui:return"Fragment";case Hi:return"Portal";case id:return"Profiler";case cf:return"StrictMode";case sd:return"Suspense";case ld:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case p_:return(e.displayName||"Context")+".Consumer";case f_:return(e._context.displayName||"Context")+".Provider";case uf:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case df:return t=e.displayName||null,t!==null?t:ad(e.type)||"Memo";case Cr:t=e._payload,e=e._init;try{return ad(e(t))}catch{}}return null}function H0(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ad(t);case 8:return t===cf?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ur(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function g_(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function U0(e){var t=g_(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(l){r=""+l,s.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ca(e){e._valueTracker||(e._valueTracker=U0(e))}function x_(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=g_(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _o(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function od(e,t){var n=t.checked;return Ke({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Gp(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ur(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function v_(e,t){t=t.checked,t!=null&&of(e,"checked",t,!1)}function cd(e,t){v_(e,t);var n=Ur(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ud(e,t.type,n):t.hasOwnProperty("defaultValue")&&ud(e,t.type,Ur(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Yp(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ud(e,t,n){(t!=="number"||_o(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var tl=Array.isArray;function ns(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=ua.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sl(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var cl={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},q0=["Webkit","ms","Moz","O"];Object.keys(cl).forEach(function(e){q0.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),cl[t]=cl[e]})});function w_(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||cl.hasOwnProperty(e)&&cl[e]?(""+t).trim():t+"px"}function S_(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=w_(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var V0=Ke({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function fd(e,t){if(t){if(V0[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Q(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Q(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Q(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Q(62))}}function pd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var md=null;function hf(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var gd=null,rs=null,is=null;function Jp(e){if(e=Gl(e)){if(typeof gd!="function")throw Error(Q(280));var t=e.stateNode;t&&(t=uc(t),gd(e.stateNode,e.type,t))}}function k_(e){rs?is?is.push(e):is=[e]:rs=e}function C_(){if(rs){var e=rs,t=is;if(is=rs=null,Jp(e),t)for(e=0;e>>=0,e===0?32:31-(rk(e)/ik|0)|0}var da=64,ha=4194304;function nl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function So(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,l=n&268435455;if(l!==0){var o=l&~i;o!==0?r=nl(o):(s&=l,s!==0&&(r=nl(s)))}else l=n&~i,l!==0?r=nl(l):s!==0&&(r=nl(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,s=t&-t,i>=s||i===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Vl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-An(t),e[t]=n}function ok(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=dl),am=" ",om=!1;function q_(e,t){switch(e){case"keyup":return Ik.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function V_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var qi=!1;function Bk(e,t){switch(e){case"compositionend":return V_(t);case"keypress":return t.which!==32?null:(om=!0,am);case"textInput":return e=t.data,e===am&&om?null:e;default:return null}}function zk(e,t){if(qi)return e==="compositionend"||!yf&&q_(e,t)?(e=H_(),Qa=xf=Lr=null,qi=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=hm(n)}}function X_(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?X_(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Q_(){for(var e=window,t=_o();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_o(e.document)}return t}function bf(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Gk(e){var t=Q_(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&X_(n.ownerDocument.documentElement,n)){if(r!==null&&bf(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=fm(n,s);var l=fm(n,r);i&&l&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Vi=null,wd=null,fl=null,Sd=!1;function pm(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Sd||Vi==null||Vi!==_o(r)||(r=Vi,"selectionStart"in r&&bf(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),fl&&Pl(fl,r)||(fl=r,r=jo(wd,"onSelect"),0Yi||(e.current=Pd[Yi],Pd[Yi]=null,Yi--)}function Ie(e,t){Yi++,Pd[Yi]=e.current,e.current=t}var qr={},Tt=Kr(qr),Gt=Kr(!1),xi=qr;function us(e,t){var n=e.type.contextTypes;if(!n)return qr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Yt(e){return e=e.childContextTypes,e!=null}function Eo(){ze(Gt),ze(Tt)}function bm(e,t,n){if(Tt.current!==qr)throw Error(Q(168));Ie(Tt,t),Ie(Gt,n)}function ly(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(Q(108,H0(e)||"Unknown",i));return Ke({},n,r)}function Po(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||qr,xi=Tt.current,Ie(Tt,e),Ie(Gt,Gt.current),!0}function wm(e,t,n){var r=e.stateNode;if(!r)throw Error(Q(169));n?(e=ly(e,t,xi),r.__reactInternalMemoizedMergedChildContext=e,ze(Gt),ze(Tt),Ie(Tt,e)):ze(Gt),Ie(Gt,n)}var rr=null,dc=!1,Jc=!1;function ay(e){rr===null?rr=[e]:rr.push(e)}function l1(e){dc=!0,ay(e)}function Gr(){if(!Jc&&rr!==null){Jc=!0;var e=0,t=Ee;try{var n=rr;for(Ee=1;e>=l,i-=l,sr=1<<32-An(t)+i|n<R?(D=N,N=null):D=N.sibling;var k=f(v,N,y[R],b);if(k===null){N===null&&(N=D);break}e&&N&&k.alternate===null&&t(v,N),_=s(k,_,R),S===null?C=k:S.sibling=k,S=k,N=D}if(R===y.length)return n(v,N),Fe&&ni(v,R),C;if(N===null){for(;RR?(D=N,N=null):D=N.sibling;var L=f(v,N,k.value,b);if(L===null){N===null&&(N=D);break}e&&N&&L.alternate===null&&t(v,N),_=s(L,_,R),S===null?C=L:S.sibling=L,S=L,N=D}if(k.done)return n(v,N),Fe&&ni(v,R),C;if(N===null){for(;!k.done;R++,k=y.next())k=d(v,k.value,b),k!==null&&(_=s(k,_,R),S===null?C=k:S.sibling=k,S=k);return Fe&&ni(v,R),C}for(N=r(v,N);!k.done;R++,k=y.next())k=p(N,v,R,k.value,b),k!==null&&(e&&k.alternate!==null&&N.delete(k.key===null?R:k.key),_=s(k,_,R),S===null?C=k:S.sibling=k,S=k);return e&&N.forEach(function(A){return t(v,A)}),Fe&&ni(v,R),C}function w(v,_,y,b){if(typeof y=="object"&&y!==null&&y.type===Ui&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case oa:e:{for(var C=y.key,S=_;S!==null;){if(S.key===C){if(C=y.type,C===Ui){if(S.tag===7){n(v,S.sibling),_=i(S,y.props.children),_.return=v,v=_;break e}}else if(S.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===Cr&&Cm(C)===S.type){n(v,S.sibling),_=i(S,y.props),_.ref=Rs(v,S,y),_.return=v,v=_;break e}n(v,S);break}else t(v,S);S=S.sibling}y.type===Ui?(_=fi(y.props.children,v.mode,b,y.key),_.return=v,v=_):(b=so(y.type,y.key,y.props,null,v.mode,b),b.ref=Rs(v,_,y),b.return=v,v=b)}return l(v);case Hi:e:{for(S=y.key;_!==null;){if(_.key===S)if(_.tag===4&&_.stateNode.containerInfo===y.containerInfo&&_.stateNode.implementation===y.implementation){n(v,_.sibling),_=i(_,y.children||[]),_.return=v,v=_;break e}else{n(v,_);break}else t(v,_);_=_.sibling}_=lu(y,v.mode,b),_.return=v,v=_}return l(v);case Cr:return S=y._init,w(v,_,S(y._payload),b)}if(tl(y))return m(v,_,y,b);if(Ps(y))return x(v,_,y,b);_a(v,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,_!==null&&_.tag===6?(n(v,_.sibling),_=i(_,y),_.return=v,v=_):(n(v,_),_=su(y,v.mode,b),_.return=v,v=_),l(v)):n(v,_)}return w}var hs=dy(!0),hy=dy(!1),Lo=Kr(null),Do=null,Ji=null,Cf=null;function jf(){Cf=Ji=Do=null}function Nf(e){var t=Lo.current;ze(Lo),e._currentValue=t}function Ld(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ls(e,t){Do=e,Cf=Ji=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Kt=!0),e.firstContext=null)}function wn(e){var t=e._currentValue;if(Cf!==e)if(e={context:e,memoizedValue:t,next:null},Ji===null){if(Do===null)throw Error(Q(308));Ji=e,Do.dependencies={lanes:0,firstContext:e}}else Ji=Ji.next=e;return t}var ci=null;function Ef(e){ci===null?ci=[e]:ci.push(e)}function fy(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Ef(t)):(n.next=i.next,i.next=n),t.interleaved=n,hr(e,r)}function hr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var jr=!1;function Pf(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function py(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function or(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function zr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,je&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,hr(e,n)}return i=r.interleaved,i===null?(t.next=t,Ef(r)):(t.next=i.next,i.next=t),r.interleaved=t,hr(e,n)}function Za(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pf(e,n)}}function jm(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=l:s=s.next=l,n=n.next}while(n!==null);s===null?i=s=t:s=s.next=t}else i=s=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ro(e,t,n,r){var i=e.updateQueue;jr=!1;var s=i.firstBaseUpdate,l=i.lastBaseUpdate,o=i.shared.pending;if(o!==null){i.shared.pending=null;var c=o,u=c.next;c.next=null,l===null?s=u:l.next=u,l=c;var h=e.alternate;h!==null&&(h=h.updateQueue,o=h.lastBaseUpdate,o!==l&&(o===null?h.firstBaseUpdate=u:o.next=u,h.lastBaseUpdate=c))}if(s!==null){var d=i.baseState;l=0,h=u=c=null,o=s;do{var f=o.lane,p=o.eventTime;if((r&f)===f){h!==null&&(h=h.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var m=e,x=o;switch(f=t,p=n,x.tag){case 1:if(m=x.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=x.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Ke({},d,f);break e;case 2:jr=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,f=i.effects,f===null?i.effects=[o]:f.push(o))}else p={eventTime:p,lane:f,tag:o.tag,payload:o.payload,callback:o.callback,next:null},h===null?(u=h=p,c=d):h=h.next=p,l|=f;if(o=o.next,o===null){if(o=i.shared.pending,o===null)break;f=o,o=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(h===null&&(c=d),i.baseState=c,i.firstBaseUpdate=u,i.lastBaseUpdate=h,t=i.shared.interleaved,t!==null){i=t;do l|=i.lane,i=i.next;while(i!==t)}else s===null&&(i.shared.lanes=0);yi|=l,e.lanes=l,e.memoizedState=d}}function Nm(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=eu.transition;eu.transition={};try{e(!1),t()}finally{Ee=n,eu.transition=r}}function Ty(){return Sn().memoizedState}function u1(e,t,n){var r=$r(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ly(e))Dy(t,n);else if(n=fy(e,t,n,r),n!==null){var i=Ot();Tn(n,e,r,i),Ry(n,t,r)}}function d1(e,t,n){var r=$r(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ly(e))Dy(t,i);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var l=t.lastRenderedState,o=s(l,n);if(i.hasEagerState=!0,i.eagerState=o,Rn(o,l)){var c=t.interleaved;c===null?(i.next=i,Ef(t)):(i.next=c.next,c.next=i),t.interleaved=i;return}}catch{}finally{}n=fy(e,t,i,r),n!==null&&(i=Ot(),Tn(n,e,r,i),Ry(n,t,r))}}function Ly(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function Dy(e,t){pl=Io=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ry(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pf(e,n)}}var Oo={readContext:wn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},h1={readContext:wn,useCallback:function(e,t){return Fn().memoizedState=[e,t===void 0?null:t],e},useContext:wn,useEffect:Pm,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,to(4194308,4,jy.bind(null,t,e),n)},useLayoutEffect:function(e,t){return to(4194308,4,e,t)},useInsertionEffect:function(e,t){return to(4,2,e,t)},useMemo:function(e,t){var n=Fn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=u1.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Fn();return e={current:e},t.memoizedState=e},useState:Em,useDebugValue:Of,useDeferredValue:function(e){return Fn().memoizedState=e},useTransition:function(){var e=Em(!1),t=e[0];return e=c1.bind(null,e[1]),Fn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,i=Fn();if(Fe){if(n===void 0)throw Error(Q(407));n=n()}else{if(n=t(),xt===null)throw Error(Q(349));_i&30||vy(r,t,n)}i.memoizedState=n;var s={value:n,getSnapshot:t};return i.queue=s,Pm(yy.bind(null,r,s,e),[e]),r.flags|=2048,Ol(9,_y.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=Fn(),t=xt.identifierPrefix;if(Fe){var n=lr,r=sr;n=(r&~(1<<32-An(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ml++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[Wn]=t,e[Ll]=r,Uy(e,t,!1,!1),t.stateNode=e;e:{switch(l=pd(n,r),n){case"dialog":Oe("cancel",e),Oe("close",e),i=r;break;case"iframe":case"object":case"embed":Oe("load",e),i=r;break;case"video":case"audio":for(i=0;ims&&(t.flags|=128,r=!0,Ms(s,!1),t.lanes=4194304)}else{if(!r)if(e=Mo(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ms(s,!0),s.tail===null&&s.tailMode==="hidden"&&!l.alternate&&!Fe)return Ct(t),null}else 2*et()-s.renderingStartTime>ms&&n!==1073741824&&(t.flags|=128,r=!0,Ms(s,!1),t.lanes=4194304);s.isBackwards?(l.sibling=t.child,t.child=l):(n=s.last,n!==null?n.sibling=l:t.child=l,s.last=l)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=et(),t.sibling=null,n=Ue.current,Ie(Ue,r?n&1|2:n&1),t):(Ct(t),null);case 22:case 23:return Hf(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?rn&1073741824&&(Ct(t),t.subtreeFlags&6&&(t.flags|=8192)):Ct(t),null;case 24:return null;case 25:return null}throw Error(Q(156,t.tag))}function y1(e,t){switch(Sf(t),t.tag){case 1:return Yt(t.type)&&Eo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return fs(),ze(Gt),ze(Tt),Lf(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tf(t),null;case 13:if(ze(Ue),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Q(340));ds()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ze(Ue),null;case 4:return fs(),null;case 10:return Nf(t.type._context),null;case 22:case 23:return Hf(),null;case 24:return null;default:return null}}var ba=!1,Pt=!1,b1=typeof WeakSet=="function"?WeakSet:Set,ae=null;function Zi(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ye(e,t,r)}else n.current=null}function $d(e,t,n){try{n()}catch(r){Ye(e,t,r)}}var Fm=!1;function w1(e,t){if(kd=ko,e=Q_(),bf(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,u=0,h=0,d=e,f=null;t:for(;;){for(var p;d!==n||i!==0&&d.nodeType!==3||(o=l+i),d!==s||r!==0&&d.nodeType!==3||(c=l+r),d.nodeType===3&&(l+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===e)break t;if(f===n&&++u===i&&(o=l),f===s&&++h===r&&(c=l),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Cd={focusedElem:e,selectionRange:n},ko=!1,ae=t;ae!==null;)if(t=ae,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ae=e;else for(;ae!==null;){t=ae;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var x=m.memoizedProps,w=m.memoizedState,v=t.stateNode,_=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:Nn(t.type,x),w);v.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Q(163))}}catch(b){Ye(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,ae=e;break}ae=t.return}return m=Fm,Fm=!1,m}function ml(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,s!==void 0&&$d(t,n,s)}i=i.next}while(i!==r)}}function pc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Wd(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ky(e){var t=e.alternate;t!==null&&(e.alternate=null,Ky(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Wn],delete t[Ll],delete t[Ed],delete t[i1],delete t[s1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Gy(e){return e.tag===5||e.tag===3||e.tag===4}function $m(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Gy(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Hd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=No));else if(r!==4&&(e=e.child,e!==null))for(Hd(e,t,n),e=e.sibling;e!==null;)Hd(e,t,n),e=e.sibling}function Ud(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ud(e,t,n),e=e.sibling;e!==null;)Ud(e,t,n),e=e.sibling}var yt=null,En=!1;function _r(e,t,n){for(n=n.child;n!==null;)Yy(e,t,n),n=n.sibling}function Yy(e,t,n){if(qn&&typeof qn.onCommitFiberUnmount=="function")try{qn.onCommitFiberUnmount(lc,n)}catch{}switch(n.tag){case 5:Pt||Zi(n,t);case 6:var r=yt,i=En;yt=null,_r(e,t,n),yt=r,En=i,yt!==null&&(En?(e=yt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):yt.removeChild(n.stateNode));break;case 18:yt!==null&&(En?(e=yt,n=n.stateNode,e.nodeType===8?Qc(e.parentNode,n):e.nodeType===1&&Qc(e,n),Nl(e)):Qc(yt,n.stateNode));break;case 4:r=yt,i=En,yt=n.stateNode.containerInfo,En=!0,_r(e,t,n),yt=r,En=i;break;case 0:case 11:case 14:case 15:if(!Pt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,l=s.destroy;s=s.tag,l!==void 0&&(s&2||s&4)&&$d(n,t,l),i=i.next}while(i!==r)}_r(e,t,n);break;case 1:if(!Pt&&(Zi(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Ye(n,t,o)}_r(e,t,n);break;case 21:_r(e,t,n);break;case 22:n.mode&1?(Pt=(r=Pt)||n.memoizedState!==null,_r(e,t,n),Pt=r):_r(e,t,n);break;default:_r(e,t,n)}}function Wm(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new b1),t.forEach(function(r){var i=T1.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function jn(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=l),r&=~s}if(r=i,r=et()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*k1(r/1960))-r,10e?16:e,Dr===null)var r=!1;else{if(e=Dr,Dr=null,Fo=0,je&6)throw Error(Q(331));var i=je;for(je|=4,ae=e.current;ae!==null;){var s=ae,l=s.child;if(ae.flags&16){var o=s.deletions;if(o!==null){for(var c=0;cet()-$f?hi(e,0):Ff|=n),Xt(e,t)}function rb(e,t){t===0&&(e.mode&1?(t=ha,ha<<=1,!(ha&130023424)&&(ha=4194304)):t=1);var n=Ot();e=hr(e,t),e!==null&&(Vl(e,t,n),Xt(e,n))}function A1(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),rb(e,n)}function T1(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Q(314))}r!==null&&r.delete(t),rb(e,n)}var ib;ib=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Gt.current)Kt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Kt=!1,v1(e,t,n);Kt=!!(e.flags&131072)}else Kt=!1,Fe&&t.flags&1048576&&oy(t,To,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;no(e,t),e=t.pendingProps;var i=us(t,Tt.current);ls(t,n),i=Rf(null,t,r,e,i,n);var s=Mf();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Yt(r)?(s=!0,Po(t)):s=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Pf(t),i.updater=fc,t.stateNode=i,i._reactInternals=t,Rd(t,r,e,n),t=Od(null,t,r,!0,s,n)):(t.tag=0,Fe&&s&&wf(t),Mt(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(no(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=D1(r),e=Nn(r,e),i){case 0:t=Id(null,t,r,e,n);break e;case 1:t=Om(null,t,r,e,n);break e;case 11:t=Mm(null,t,r,e,n);break e;case 14:t=Im(null,t,r,Nn(r.type,e),n);break e}throw Error(Q(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),Id(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),Om(e,t,r,i,n);case 3:e:{if($y(t),e===null)throw Error(Q(387));r=t.pendingProps,s=t.memoizedState,i=s.element,py(e,t),Ro(t,r,null,n);var l=t.memoizedState;if(r=l.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){i=ps(Error(Q(423)),t),t=Bm(e,t,r,n,i);break e}else if(r!==i){i=ps(Error(Q(424)),t),t=Bm(e,t,r,n,i);break e}else for(sn=Br(t.stateNode.containerInfo.firstChild),ln=t,Fe=!0,Pn=null,n=hy(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ds(),r===i){t=fr(e,t,n);break e}Mt(e,t,r,n)}t=t.child}return t;case 5:return my(t),e===null&&Td(t),r=t.type,i=t.pendingProps,s=e!==null?e.memoizedProps:null,l=i.children,jd(r,i)?l=null:s!==null&&jd(r,s)&&(t.flags|=32),Fy(e,t),Mt(e,t,l,n),t.child;case 6:return e===null&&Td(t),null;case 13:return Wy(e,t,n);case 4:return Af(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=hs(t,null,r,n):Mt(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),Mm(e,t,r,i,n);case 7:return Mt(e,t,t.pendingProps,n),t.child;case 8:return Mt(e,t,t.pendingProps.children,n),t.child;case 12:return Mt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,s=t.memoizedProps,l=i.value,Ie(Lo,r._currentValue),r._currentValue=l,s!==null)if(Rn(s.value,l)){if(s.children===i.children&&!Gt.current){t=fr(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var o=s.dependencies;if(o!==null){l=s.child;for(var c=o.firstContext;c!==null;){if(c.context===r){if(s.tag===1){c=or(-1,n&-n),c.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var h=u.pending;h===null?c.next=c:(c.next=h.next,h.next=c),u.pending=c}}s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),Ld(s.return,n,t),o.lanes|=n;break}c=c.next}}else if(s.tag===10)l=s.type===t.type?null:s.child;else if(s.tag===18){if(l=s.return,l===null)throw Error(Q(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),Ld(l,n,t),l=s.sibling}else l=s.child;if(l!==null)l.return=s;else for(l=s;l!==null;){if(l===t){l=null;break}if(s=l.sibling,s!==null){s.return=l.return,l=s;break}l=l.return}s=l}Mt(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,ls(t,n),i=wn(i),r=r(i),t.flags|=1,Mt(e,t,r,n),t.child;case 14:return r=t.type,i=Nn(r,t.pendingProps),i=Nn(r.type,i),Im(e,t,r,i,n);case 15:return By(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Nn(r,i),no(e,t),t.tag=1,Yt(r)?(e=!0,Po(t)):e=!1,ls(t,n),My(t,r,i),Rd(t,r,i,n),Od(null,t,r,!0,e,n);case 19:return Hy(e,t,n);case 22:return zy(e,t,n)}throw Error(Q(156,t.tag))};function sb(e,t){return L_(e,t)}function L1(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function _n(e,t,n,r){return new L1(e,t,n,r)}function qf(e){return e=e.prototype,!(!e||!e.isReactComponent)}function D1(e){if(typeof e=="function")return qf(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uf)return 11;if(e===df)return 14}return 2}function Wr(e,t){var n=e.alternate;return n===null?(n=_n(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function so(e,t,n,r,i,s){var l=2;if(r=e,typeof e=="function")qf(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case Ui:return fi(n.children,i,s,t);case cf:l=8,i|=8;break;case id:return e=_n(12,n,t,i|2),e.elementType=id,e.lanes=s,e;case sd:return e=_n(13,n,t,i),e.elementType=sd,e.lanes=s,e;case ld:return e=_n(19,n,t,i),e.elementType=ld,e.lanes=s,e;case m_:return gc(n,i,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case f_:l=10;break e;case p_:l=9;break e;case uf:l=11;break e;case df:l=14;break e;case Cr:l=16,r=null;break e}throw Error(Q(130,e==null?e:typeof e,""))}return t=_n(l,n,t,i),t.elementType=e,t.type=r,t.lanes=s,t}function fi(e,t,n,r){return e=_n(7,e,r,t),e.lanes=n,e}function gc(e,t,n,r){return e=_n(22,e,r,t),e.elementType=m_,e.lanes=n,e.stateNode={isHidden:!1},e}function su(e,t,n){return e=_n(6,e,null,t),e.lanes=n,e}function lu(e,t,n){return t=_n(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function R1(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Fc(0),this.expirationTimes=Fc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Fc(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Vf(e,t,n,r,i,s,l,o,c){return e=new R1(e,t,n,o,c),t===1?(t=1,s===!0&&(t|=8)):t=0,s=_n(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Pf(s),e}function M1(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(cb)}catch(e){console.error(e)}}cb(),c_.exports=cn;var F1=c_.exports,Xm=F1;nd.createRoot=Xm.createRoot,nd.hydrateRoot=Xm.hydrateRoot;/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var ub=Object.defineProperty,$1=Object.getOwnPropertyDescriptor,W1=(e,t)=>{for(var n in t)ub(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,r)=>{for(var i=r>1?void 0:r?$1(t,n):t,s=e.length-1,l;s>=0;s--)(l=e[s])&&(i=(r?l(t,n,i):l(i))||i);return r&&i&&ub(t,n,i),i},se=(e,t)=>(n,r)=>t(n,r,e),Qm="Terminal input",Yd={get:()=>Qm,set:e=>Qm=e},Jm="Too much output to announce, navigate to rows manually to read",Xd={get:()=>Jm,set:e=>Jm=e};function H1(e){return e.replace(/\r?\n/g,"\r")}function U1(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function q1(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function V1(e,t,n,r){if(e.stopPropagation(),e.clipboardData){let i=e.clipboardData.getData("text/plain");db(i,t,n,r)}}function db(e,t,n,r){e=H1(e),e=U1(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function hb(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,s=e.clientY-r.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${i}px`,t.style.top=`${s}px`,t.style.zIndex="1000",t.focus()}function Zm(e,t,n,r,i){hb(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Nr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function bc(e,t=0,n=e.length){let r="";for(let i=t;i65535?(s-=65536,r+=String.fromCharCode((s>>10)+55296)+String.fromCharCode(s%1024+56320)):r+=String.fromCharCode(s)}return r}var K1=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let s=e.charCodeAt(i++);56320<=s&&s<=57343?t[r++]=(this._interim-55296)*1024+s-56320+65536:(t[r++]=this._interim,t[r++]=s),this._interim=0}for(let s=i;s=n)return this._interim=l,r;let o=e.charCodeAt(s);56320<=o&&o<=57343?t[r++]=(l-55296)*1024+o-56320+65536:(t[r++]=l,t[r++]=o);continue}l!==65279&&(t[r++]=l)}return r}},G1=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,s,l,o,c=0,u=0;if(this.interim[0]){let f=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,x;for(;(x=this.interim[++m]&63)&&m<4;)p<<=6,p|=x;let w=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,v=w-m;for(;u=n)return 0;if(x=e[u++],(x&192)!==128){u--,f=!0;break}else this.interim[m++]=x,p<<=6,p|=x&63}f||(w===2?p<128?u--:t[r++]=p:w===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let h=n-4,d=u;for(;d=n)return this.interim[0]=i,r;if(s=e[d++],(s&192)!==128){d--;continue}if(c=(i&31)<<6|s&63,c<128){d--;continue}t[r++]=c}else if((i&240)===224){if(d>=n)return this.interim[0]=i,r;if(s=e[d++],(s&192)!==128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=s,r;if(l=e[d++],(l&192)!==128){d--;continue}if(c=(i&15)<<12|(s&63)<<6|l&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)===240){if(d>=n)return this.interim[0]=i,r;if(s=e[d++],(s&192)!==128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=s,r;if(l=e[d++],(l&192)!==128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=s,this.interim[2]=l,r;if(o=e[d++],(o&192)!==128){d--;continue}if(c=(i&7)<<18|(s&63)<<12|(l&63)<<6|o&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},fb="",Rr=" ",Xl=class pb{constructor(){this.fg=0,this.bg=0,this.extended=new Ho}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new pb;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Ho=class mb{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new mb(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},bn=class gb extends Xl{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Ho,this.combinedData=""}static fromCharData(t){let n=new gb;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Nr(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let r=t[1].charCodeAt(0);if(55296<=r&&r<=56319){let i=t[1].charCodeAt(1);56320<=i&&i<=57343?this.content=(r-55296)*1024+i-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},eg="di$target",Qd="di$dependencies",au=new Map;function Y1(e){return e[Qd]||[]}function vt(e){if(au.has(e))return au.get(e);let t=function(n,r,i){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");X1(t,n,i)};return t._id=e,au.set(e,t),t}function X1(e,t,n){t[eg]===t?t[Qd].push({id:e,index:n}):(t[Qd]=[{id:e,index:n}],t[eg]=t)}var Ft=vt("BufferService"),xb=vt("CoreMouseService"),Ni=vt("CoreService"),Q1=vt("CharsetService"),Xf=vt("InstantiationService"),vb=vt("LogService"),$t=vt("OptionsService"),_b=vt("OscLinkService"),J1=vt("UnicodeService"),Ql=vt("DecorationService"),Jd=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,s=new bn,l=n.getTrimmedLength(),o=-1,c=-1,u=!1;for(let h=0;hi?i.activate(m,x,f):Z1(m,x),hover:(m,x)=>i?.hover?.(m,x,f),leave:(m,x)=>i?.leave?.(m,x,f)})}u=!1,s.hasExtendedAttrs()&&s.extended.urlId?(c=h,o=s.extended.urlId):(c=-1,o=-1)}}t(r)}};Jd=Qe([se(0,Ft),se(1,$t),se(2,_b)],Jd);function Z1(e,t){if(confirm(`Do you want to navigate to ${t}? - -WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var wc=vt("CharSizeService"),mr=vt("CoreBrowserService"),Qf=vt("MouseService"),gr=vt("RenderService"),eC=vt("SelectionService"),yb=vt("CharacterJoinerService"),ws=vt("ThemeService"),bb=vt("LinkProviderService"),tC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?tg.isErrorNoTelemetry(e)?new tg(e.message+` - -`+e.stack):new Error(e.message+` - -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},nC=new tC;function lo(e){rC(e)||nC.onUnexpectedError(e)}var Zd="Canceled";function rC(e){return e instanceof iC?!0:e instanceof Error&&e.name===Zd&&e.message===Zd}var iC=class extends Error{constructor(){super(Zd),this.name=this.message}};function sC(e){return new Error(`Illegal argument: ${e}`)}var tg=class eh extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof eh)return t;let n=new eh;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},th=class wb extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,wb.prototype)}};function Zt(e,t=0){return e[e.length-(1+t)]}var lC;(e=>{function t(s){return s<0}e.isLessThan=t;function n(s){return s<=0}e.isLessThanOrEqual=n;function r(s){return s>0}e.isGreaterThan=r;function i(s){return s===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(lC||={});function aC(e,t){let n=this,r=!1,i;return function(){return r||(r=!0,t||(i=e.apply(n,arguments))),i}}var Sb;(e=>{function t(b){return b&&typeof b=="object"&&typeof b[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(b){yield b}e.single=i;function s(b){return t(b)?b:i(b)}e.wrap=s;function l(b){return b||n}e.from=l;function*o(b){for(let C=b.length-1;C>=0;C--)yield b[C]}e.reverse=o;function c(b){return!b||b[Symbol.iterator]().next().done===!0}e.isEmpty=c;function u(b){return b[Symbol.iterator]().next().value}e.first=u;function h(b,C){let S=0;for(let N of b)if(C(N,S++))return!0;return!1}e.some=h;function d(b,C){for(let S of b)if(C(S))return S}e.find=d;function*f(b,C){for(let S of b)C(S)&&(yield S)}e.filter=f;function*p(b,C){let S=0;for(let N of b)yield C(N,S++)}e.map=p;function*m(b,C){let S=0;for(let N of b)yield*C(N,S++)}e.flatMap=m;function*x(...b){for(let C of b)yield*C}e.concat=x;function w(b,C,S){let N=S;for(let R of b)N=C(N,R);return N}e.reduce=w;function*v(b,C,S=b.length){for(C<0&&(C+=b.length),S<0?S+=b.length:S>b.length&&(S=b.length);C1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function oC(...e){return $e(()=>wi(e))}function $e(e){return{dispose:aC(()=>{e()})}}var kb=class Cb{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{wi(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Cb.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};kb.DISABLE_DISPOSED_WARNING=!1;var Hr=kb,_e=class{constructor(){this._store=new Hr,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};_e.None=Object.freeze({dispose(){}});var gs=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},ar=typeof window=="object"?window:globalThis,nh=class rh{constructor(t){this.element=t,this.next=rh.Undefined,this.prev=rh.Undefined}};nh.Undefined=new nh(void 0);var We=nh,ng=class{constructor(){this._first=We.Undefined,this._last=We.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===We.Undefined}clear(){let e=this._first;for(;e!==We.Undefined;){let t=e.next;e.prev=We.Undefined,e.next=We.Undefined,e=t}this._first=We.Undefined,this._last=We.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new We(e);if(this._first===We.Undefined)this._first=n,this._last=n;else if(t){let i=this._last;this._last=n,n.prev=i,i.next=n}else{let i=this._first;this._first=n,n.next=i,i.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==We.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==We.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==We.Undefined&&e.next!==We.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===We.Undefined&&e.next===We.Undefined?(this._first=We.Undefined,this._last=We.Undefined):e.next===We.Undefined?(this._last=this._last.prev,this._last.next=We.Undefined):e.prev===We.Undefined&&(this._first=this._first.next,this._first.prev=We.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==We.Undefined;)yield e.element,e=e.next}},cC=globalThis.performance&&typeof globalThis.performance.now=="function",uC=class jb{static create(t){return new jb(t)}constructor(t){this._now=cC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},bt;(e=>{e.None=()=>_e.None;function t(A,P){return d(A,()=>{},0,void 0,!0,void 0,P)}e.defer=t;function n(A){return(P,I=null,O)=>{let U=!1,K;return K=A(E=>{if(!U)return K?K.dispose():U=!0,P.call(I,E)},null,O),U&&K.dispose(),K}}e.once=n;function r(A,P,I){return u((O,U=null,K)=>A(E=>O.call(U,P(E)),null,K),I)}e.map=r;function i(A,P,I){return u((O,U=null,K)=>A(E=>{P(E),O.call(U,E)},null,K),I)}e.forEach=i;function s(A,P,I){return u((O,U=null,K)=>A(E=>P(E)&&O.call(U,E),null,K),I)}e.filter=s;function l(A){return A}e.signal=l;function o(...A){return(P,I=null,O)=>{let U=oC(...A.map(K=>K(E=>P.call(I,E))));return h(U,O)}}e.any=o;function c(A,P,I,O){let U=I;return r(A,K=>(U=P(U,K),U),O)}e.reduce=c;function u(A,P){let I,O={onWillAddFirstListener(){I=A(U.fire,U)},onDidRemoveLastListener(){I?.dispose()}},U=new ne(O);return P?.add(U),U.event}function h(A,P){return P instanceof Array?P.push(A):P&&P.add(A),A}function d(A,P,I=100,O=!1,U=!1,K,E){let F,j,re,V=0,T,ie={leakWarningThreshold:K,onWillAddFirstListener(){F=A(J=>{V++,j=P(j,J),O&&!re&&(ee.fire(j),j=void 0),T=()=>{let W=j;j=void 0,re=void 0,(!O||V>1)&&ee.fire(W),V=0},typeof I=="number"?(clearTimeout(re),re=setTimeout(T,I)):re===void 0&&(re=0,queueMicrotask(T))})},onWillRemoveListener(){U&&V>0&&T?.()},onDidRemoveLastListener(){T=void 0,F.dispose()}},ee=new ne(ie);return E?.add(ee),ee.event}e.debounce=d;function f(A,P=0,I){return e.debounce(A,(O,U)=>O?(O.push(U),O):[U],P,void 0,!0,void 0,I)}e.accumulate=f;function p(A,P=(O,U)=>O===U,I){let O=!0,U;return s(A,K=>{let E=O||!P(K,U);return O=!1,U=K,E},I)}e.latch=p;function m(A,P,I){return[e.filter(A,P,I),e.filter(A,O=>!P(O),I)]}e.split=m;function x(A,P=!1,I=[],O){let U=I.slice(),K=A(j=>{U?U.push(j):F.fire(j)});O&&O.add(K);let E=()=>{U?.forEach(j=>F.fire(j)),U=null},F=new ne({onWillAddFirstListener(){K||(K=A(j=>F.fire(j)),O&&O.add(K))},onDidAddFirstListener(){U&&(P?setTimeout(E):E())},onDidRemoveLastListener(){K&&K.dispose(),K=null}});return O&&O.add(F),F.event}e.buffer=x;function w(A,P){return(I,O,U)=>{let K=P(new _);return A(function(E){let F=K.evaluate(E);F!==v&&I.call(O,F)},void 0,U)}}e.chain=w;let v=Symbol("HaltChainable");class _{constructor(){this.steps=[]}map(P){return this.steps.push(P),this}forEach(P){return this.steps.push(I=>(P(I),I)),this}filter(P){return this.steps.push(I=>P(I)?I:v),this}reduce(P,I){let O=I;return this.steps.push(U=>(O=P(O,U),O)),this}latch(P=(I,O)=>I===O){let I=!0,O;return this.steps.push(U=>{let K=I||!P(U,O);return I=!1,O=U,K?U:v}),this}evaluate(P){for(let I of this.steps)if(P=I(P),P===v)break;return P}}function y(A,P,I=O=>O){let O=(...F)=>E.fire(I(...F)),U=()=>A.on(P,O),K=()=>A.removeListener(P,O),E=new ne({onWillAddFirstListener:U,onDidRemoveLastListener:K});return E.event}e.fromNodeEventEmitter=y;function b(A,P,I=O=>O){let O=(...F)=>E.fire(I(...F)),U=()=>A.addEventListener(P,O),K=()=>A.removeEventListener(P,O),E=new ne({onWillAddFirstListener:U,onDidRemoveLastListener:K});return E.event}e.fromDOMEventEmitter=b;function C(A){return new Promise(P=>n(A)(P))}e.toPromise=C;function S(A){let P=new ne;return A.then(I=>{P.fire(I)},()=>{P.fire(void 0)}).finally(()=>{P.dispose()}),P.event}e.fromPromise=S;function N(A,P){return A(I=>P.fire(I))}e.forward=N;function R(A,P,I){return P(I),A(O=>P(O))}e.runAndSubscribe=R;class D{constructor(P,I){this._observable=P,this._counter=0,this._hasChanged=!1;let O={onWillAddFirstListener:()=>{P.addObserver(this)},onDidRemoveLastListener:()=>{P.removeObserver(this)}};this.emitter=new ne(O),I&&I.add(this.emitter)}beginUpdate(P){this._counter++}handlePossibleChange(P){}handleChange(P,I){this._hasChanged=!0}endUpdate(P){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function k(A,P){return new D(A,P).emitter.event}e.fromObservable=k;function L(A){return(P,I,O)=>{let U=0,K=!1,E={beginUpdate(){U++},endUpdate(){U--,U===0&&(A.reportChanges(),K&&(K=!1,P.call(I)))},handlePossibleChange(){},handleChange(){K=!0}};A.addObserver(E),A.reportChanges();let F={dispose(){A.removeObserver(E)}};return O instanceof Hr?O.add(F):Array.isArray(O)&&O.push(F),F}}e.fromObservableLight=L})(bt||={});var ih=class sh{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${sh._idPool++}`,sh.all.add(this)}start(t){this._stopWatch=new uC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};ih.all=new Set,ih._idPool=0;var dC=ih,hC=-1,Nb=class Eb{constructor(t,n,r=(Eb._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,n){let r=this.threshold;if(r<=0||n{let s=this._stacks.get(t.value)||0;this._stacks.set(t.value,s-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[r,i]of this._stacks)(!t||n{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let l=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(l);let o=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new gC(`${l}. HINT: Stack shows most frequent listener (${o[1]}-times)`,o[0]);return(this._options?.onListenerError||lo)(c),_e.None}if(this._disposed)return _e.None;t&&(e=e.bind(t));let r=new ou(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=pC.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ou?(this._deliveryQueue??=new yC,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let s=$e(()=>{i?.(),this._removeListener(r)});return n instanceof Hr?n.add(s):Array.isArray(n)&&n.push(s),s},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*vC<=t.length){let i=0;for(let s=0;s0}},yC=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},lh=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new ne,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new ne,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(r,t),this._onDidChangeZoomLevel.fire(r)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let r=this.getWindowId(n);this.mapWindowIdToFullScreen.set(r,t),this._onDidChangeFullscreen.fire(r)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};lh.INSTANCE=new lh;var Jf=lh;function bC(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}Jf.INSTANCE.onDidChangeZoomLevel;function wC(e){return Jf.INSTANCE.getZoomFactor(e)}Jf.INSTANCE.onDidChangeFullscreen;var Ss=typeof navigator=="object"?navigator.userAgent:"",ah=Ss.indexOf("Firefox")>=0,SC=Ss.indexOf("AppleWebKit")>=0,Zf=Ss.indexOf("Chrome")>=0,kC=!Zf&&Ss.indexOf("Safari")>=0;Ss.indexOf("Electron/")>=0;Ss.indexOf("Android")>=0;var cu=!1;if(typeof ar.matchMedia=="function"){let e=ar.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=ar.matchMedia("(display-mode: fullscreen)");cu=e.matches,bC(ar,e,({matches:n})=>{cu&&t.matches||(cu=n)})}var ts="en",oh=!1,ch=!1,ao=!1,Ab=!1,ka,oo=ts,rg=ts,CC,tr,pi=globalThis,nn;typeof pi.vscode<"u"&&typeof pi.vscode.process<"u"?nn=pi.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(nn=process);var jC=typeof nn?.versions?.electron=="string",NC=jC&&nn?.type==="renderer";if(typeof nn=="object"){oh=nn.platform==="win32",ch=nn.platform==="darwin",ao=nn.platform==="linux",ao&&nn.env.SNAP&&nn.env.SNAP_REVISION,nn.env.CI||nn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,ka=ts,oo=ts;let e=nn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);ka=t.userLocale,rg=t.osLocale,oo=t.resolvedLanguage||ts,CC=t.languagePack?.translationsConfigFile}catch{}Ab=!0}else typeof navigator=="object"&&!NC?(tr=navigator.userAgent,oh=tr.indexOf("Windows")>=0,ch=tr.indexOf("Macintosh")>=0,(tr.indexOf("Macintosh")>=0||tr.indexOf("iPad")>=0||tr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,ao=tr.indexOf("Linux")>=0,tr?.indexOf("Mobi")>=0,oo=globalThis._VSCODE_NLS_LANGUAGE||ts,ka=navigator.language.toLowerCase(),rg=ka):console.error("Unable to resolve platform.");var Tb=oh,Kn=ch,EC=ao,ig=Ab,Gn=tr,yr=oo,PC;(e=>{function t(){return yr}e.value=t;function n(){return yr.length===2?yr==="en":yr.length>=3?yr[0]==="e"&&yr[1]==="n"&&yr[2]==="-":!1}e.isDefaultVariant=n;function r(){return yr==="en"}e.isDefault=r})(PC||={});var AC=typeof pi.postMessage=="function"&&!pi.importScripts;(()=>{if(AC){let e=[];pi.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let r=0,i=e.length;r{let r=++t;e.push({id:r,callback:n}),pi.postMessage({vscodeScheduleAsyncWork:r},"*")}}return e=>setTimeout(e)})();var TC=!!(Gn&&Gn.indexOf("Chrome")>=0);Gn&&Gn.indexOf("Firefox")>=0;!TC&&Gn&&Gn.indexOf("Safari")>=0;Gn&&Gn.indexOf("Edg/")>=0;Gn&&Gn.indexOf("Android")>=0;var Ti=typeof navigator=="object"?navigator:{};ig||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ti&&Ti.clipboard&&Ti.clipboard.writeText,ig||Ti&&Ti.clipboard&&Ti.clipboard.readText;var ep=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},uu=new ep,sg=new ep,lg=new ep,LC=new Array(230),Lb;(e=>{function t(o){return uu.keyCodeToStr(o)}e.toString=t;function n(o){return uu.strToKeyCode(o)}e.fromString=n;function r(o){return sg.keyCodeToStr(o)}e.toUserSettingsUS=r;function i(o){return lg.keyCodeToStr(o)}e.toUserSettingsGeneral=i;function s(o){return sg.strToKeyCode(o)||lg.strToKeyCode(o)}e.fromUserSettings=s;function l(o){if(o>=98&&o<=113)return null;switch(o){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return uu.keyCodeToStr(o)}e.toElectronAccelerator=l})(Lb||={});var DC=class Db{constructor(t,n,r,i,s){this.ctrlKey=t,this.shiftKey=n,this.altKey=r,this.metaKey=i,this.keyCode=s}equals(t){return t instanceof Db&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",r=this.altKey?"1":"0",i=this.metaKey?"1":"0";return`K${t}${n}${r}${i}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new RC([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},RC=class{constructor(e){if(e.length===0)throw sC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t{function t(n){return n===e.None||n===e.Cancelled||n instanceof HC?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:bt.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Rb})})(WC||={});var HC=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Rb:(this._emitter||(this._emitter=new ne),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},tp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new th("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new th("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},UC=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new th("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=$e(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},qC;(e=>{async function t(r){let i,s=await Promise.all(r.map(l=>l.then(o=>o,o=>{i||(i=o)})));if(typeof i<"u")throw i;return s}e.settled=t;function n(r){return new Promise(async(i,s)=>{try{await r(i,s)}catch(l){s(l)}})}e.withAsyncBody=n})(qC||={});var ug=class pn{static fromArray(t){return new pn(n=>{n.emitMany(t)})}static fromPromise(t){return new pn(async n=>{n.emitMany(await t)})}static fromPromises(t){return new pn(async n=>{await Promise.all(t.map(async r=>n.emitOne(await r)))})}static merge(t){return new pn(async n=>{await Promise.all(t.map(async r=>{for await(let i of r)n.emitOne(i)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new ne,queueMicrotask(async()=>{let r={emitOne:i=>this.emitOne(i),emitMany:i=>this.emitMany(i),reject:i=>this.reject(i)};try{await Promise.resolve(t(r)),this.resolve()}catch(i){this.reject(i)}finally{r.emitOne=void 0,r.emitMany=void 0,r.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new pn(async r=>{for await(let i of t)r.emitOne(n(i))})}map(t){return pn.map(this,t)}static filter(t,n){return new pn(async r=>{for await(let i of t)n(i)&&r.emitOne(i)})}filter(t){return pn.filter(this,t)}static coalesce(t){return pn.filter(t,n=>!!n)}coalesce(){return pn.coalesce(this)}static async toPromise(t){let n=[];for await(let r of t)n.push(r);return n}toPromise(){return pn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};ug.EMPTY=ug.fromArray([]);var{getWindow:Un,getWindowId:VC,onDidRegisterWindow:KC}=function(){let e=new Map,t={window:ar,disposables:new Hr};e.set(ar.vscodeWindowId,t);let n=new ne,r=new ne,i=new ne;function s(l,o){return(typeof l=="number"?e.get(l):void 0)??(o?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(l){if(e.has(l.vscodeWindowId))return _e.None;let o=new Hr,c={window:l,disposables:o.add(new Hr)};return e.set(l.vscodeWindowId,c),o.add($e(()=>{e.delete(l.vscodeWindowId),r.fire(l)})),o.add(pe(l,ht.BEFORE_UNLOAD,()=>{i.fire(l)})),n.fire(c),o},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(l){return l.vscodeWindowId},hasWindow(l){return e.has(l)},getWindowById:s,getWindow(l){let o=l;if(o?.ownerDocument?.defaultView)return o.ownerDocument.defaultView.window;let c=l;return c?.view?c.view.window:ar},getDocument(l){return Un(l).document}}}(),GC=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function pe(e,t,n,r){return new GC(e,t,n,r)}var dg=function(e,t,n,r){return pe(e,t,n,r)},np,YC=class extends UC{constructor(e){super(),this.defaultTarget=e&&Un(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},hg=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){lo(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=s=>{n.set(s,!1);let l=e.get(s)??[];for(t.set(s,l),e.set(s,[]),r.set(s,!0);l.length>0;)l.sort(hg.sort),l.shift().execute();r.set(s,!1)};np=(s,l,o=0)=>{let c=VC(s),u=new hg(l,o),h=e.get(c);return h||(h=[],e.set(c,h)),h.push(u),n.get(c)||(n.set(c,!0),s.requestAnimationFrame(()=>i(c))),u}})();function XC(e){let t=e.getBoundingClientRect(),n=Un(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var ht={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},QC=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Wt(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Wt(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Wt(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Wt(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Wt(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Wt(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Wt(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Wt(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Wt(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Wt(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Wt(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Wt(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Wt(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Wt(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Wt(e){return typeof e=="number"?`${e}px`:e}function vl(e){return new QC(e)}var Mb=class{constructor(){this._hooks=new Hr,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let s=e;try{e.setPointerCapture(t),this._hooks.add($e(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{s=Un(e)}this._hooks.add(pe(s,ht.POINTER_MOVE,l=>{if(l.buttons!==n){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(pe(s,ht.POINTER_UP,l=>this.stopMonitoring(!0)))}};function JC(e,t,n){let r=null,i=null;if(typeof n.value=="function"?(r="value",i=n.value,i.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(r="get",i=n.get),!i)throw new Error("not supported");let s=`$memoize$${t}`;n[r]=function(...l){return this.hasOwnProperty(s)||Object.defineProperty(this,s,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,l)}),this[s]}}var zn;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(zn||={});var il=class Nt extends _e{constructor(){super(),this.dispatched=!1,this.targets=new ng,this.ignoreTargets=new ng,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(bt.runAndSubscribe(KC,({window:t,disposables:n})=>{n.add(pe(t.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),n.add(pe(t.document,"touchend",r=>this.onTouchEnd(t,r))),n.add(pe(t.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:ar,disposables:this._store}))}static addTarget(t){if(!Nt.isTouchDevice())return _e.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.targets.push(t);return $e(n)}static ignoreTarget(t){if(!Nt.isTouchDevice())return _e.None;Nt.INSTANCE||(Nt.INSTANCE=new Nt);let n=Nt.INSTANCE.ignoreTargets.push(t);return $e(n)}static isTouchDevice(){return"ontouchstart"in ar||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,i=t.targetTouches.length;r=Nt.HOLD_DELAY&&Math.abs(c.initialPageX-Zt(c.rollingPageX))<30&&Math.abs(c.initialPageY-Zt(c.rollingPageY))<30){let h=this.newGestureEvent(zn.Contextmenu,c.initialTarget);h.pageX=Zt(c.rollingPageX),h.pageY=Zt(c.rollingPageY),this.dispatchEvent(h)}else if(i===1){let h=Zt(c.rollingPageX),d=Zt(c.rollingPageY),f=Zt(c.rollingTimestamps)-c.rollingTimestamps[0],p=h-c.rollingPageX[0],m=d-c.rollingPageY[0],x=[...this.targets].filter(w=>c.initialTarget instanceof Node&&w.contains(c.initialTarget));this.inertia(t,x,r,Math.abs(p)/f,p>0?1:-1,h,Math.abs(m)/f,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(zn.End,c.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let r=document.createEvent("CustomEvent");return r.initEvent(t,!1,!0),r.initialTarget=n,r.tapCount=0,r}dispatchEvent(t){if(t.type===zn.Tap){let n=new Date().getTime(),r=0;n-this._lastSetTapCountTime>Nt.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===zn.Change||t.type===zn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(t.initialTarget))return;let n=[];for(let r of this.targets)if(r.contains(t.initialTarget)){let i=0,s=t.initialTarget;for(;s&&s!==r;)i++,s=s.parentElement;n.push([i,r])}n.sort((r,i)=>r[0]-i[0]);for(let[r,i]of n)i.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,s,l,o,c,u){this.handle=np(t,()=>{let h=Date.now(),d=h-r,f=0,p=0,m=!0;i+=Nt.SCROLL_FRICTION*d,o+=Nt.SCROLL_FRICTION*d,i>0&&(m=!1,f=s*i*d),o>0&&(m=!1,p=c*o*d);let x=this.newGestureEvent(zn.Change);x.translationX=f,x.translationY=p,n.forEach(w=>w.dispatchEvent(x)),m||this.inertia(t,n,h,i,s,l+f,o,c,u+p)})}onTouchMove(t){let n=Date.now();for(let r=0,i=t.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(s.pageX),l.rollingPageY.push(s.pageY),l.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};il.SCROLL_FRICTION=-.005,il.HOLD_DELAY=700,il.CLEAR_TAP_COUNT_TIME=400,Qe([JC],il,"isTouchDevice",1);var ZC=il,rp=class extends _e{onclick(e,t){this._register(pe(e,ht.CLICK,n=>t(new Ca(Un(e),n))))}onmousedown(e,t){this._register(pe(e,ht.MOUSE_DOWN,n=>t(new Ca(Un(e),n))))}onmouseover(e,t){this._register(pe(e,ht.MOUSE_OVER,n=>t(new Ca(Un(e),n))))}onmouseleave(e,t){this._register(pe(e,ht.MOUSE_LEAVE,n=>t(new Ca(Un(e),n))))}onkeydown(e,t){this._register(pe(e,ht.KEY_DOWN,n=>t(new ag(n))))}onkeyup(e,t){this._register(pe(e,ht.KEY_UP,n=>t(new ag(n))))}oninput(e,t){this._register(pe(e,ht.INPUT,t))}onblur(e,t){this._register(pe(e,ht.BLUR,t))}onfocus(e,t){this._register(pe(e,ht.FOCUS,t))}onchange(e,t){this._register(pe(e,ht.CHANGE,t))}ignoreGesture(e){return ZC.ignoreTarget(e)}},fg=11,ej=class extends rp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=fg+"px",this.domNode.style.height=fg+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Mb),this._register(dg(this.bgDomNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(dg(this.domNode,ht.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new YC),this._pointerdownScheduleRepeatTimer=this._register(new tp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Un(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},tj=class uh{constructor(t,n,r,i,s,l,o){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,r=r|0,i=i|0,s=s|0,l=l|0,o=o|0),this.rawScrollLeft=i,this.rawScrollTop=o,n<0&&(n=0),i+n>r&&(i=r-n),i<0&&(i=0),s<0&&(s=0),o+s>l&&(o=l-s),o<0&&(o=0),this.width=n,this.scrollWidth=r,this.scrollLeft=i,this.height=s,this.scrollHeight=l,this.scrollTop=o}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new uh(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new uh(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let r=this.width!==t.width,i=this.scrollWidth!==t.scrollWidth,s=this.scrollLeft!==t.scrollLeft,l=this.height!==t.height,o=this.scrollHeight!==t.scrollHeight,c=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:r,scrollWidthChanged:i,scrollLeftChanged:s,heightChanged:l,scrollHeightChanged:o,scrollTopChanged:c}}},nj=class extends _e{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new tj(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;t?r=new mg(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):r=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=mg.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},pg=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function du(e,t){let n=t-e;return function(r){return e+n*sj(r)}}function rj(e,t,n){return function(r){return r2.5*r){let i,s;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},aj=140,Ib=class extends rp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new lj(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Mb),this._shouldRender=!0,this.domNode=vl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(pe(this.domNode.domNode,ht.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new ej(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=vl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof n=="number"&&this.slider.setWidth(n),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(pe(this.slider.domNode,ht.POINTER_DOWN,i=>{i.button===0&&(i.preventDefault(),this._sliderPointerDown(i))})),this.onclick(this.slider.domNode,i=>{i.leftButton&&i.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,n=e.offsetY;else{let i=XC(this.domNode.domNode);t=e.pageX-i.left,n=e.pageY-i.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{let s=this._sliderOrthogonalPointerPosition(i),l=Math.abs(s-n);if(Tb&&l>aj){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(i)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Ob=class hh{constructor(t,n,r,i,s,l){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(r),this._arrowSize=Math.round(t),this._visibleSize=i,this._scrollSize=s,this._scrollPosition=l,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new hh(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,r,i,s){let l=Math.max(0,r-t),o=Math.max(0,l-2*n),c=i>0&&i>r;if(!c)return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(r*o/i))),h=(o-u)/(i-r),d=s*h;return{computedAvailableSize:Math.round(l),computedIsNeeded:c,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let t=hh._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,r=this._scrollPosition;return n0&&Math.abs(t.deltaY)>0)return 1;let r=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(r+=.25),n){let i=Math.abs(t.deltaX),s=Math.abs(t.deltaY),l=Math.abs(n.deltaX),o=Math.abs(n.deltaY),c=Math.max(Math.min(i,l),1),u=Math.max(Math.min(s,o),1),h=Math.max(i,l),d=Math.max(s,o);h%c===0&&d%u===0&&(r-=.5)}return Math.min(Math.max(r,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};fh.INSTANCE=new fh;var hj=fh,fj=class extends rp{constructor(e,t,n){super(),this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new ne),this.onWillScroll=this._onWillScroll.event,this._options=mj(t),this._scrollable=n,this._register(this._scrollable.onScroll(i=>{this._onWillScroll.fire(i),this._onDidScroll(i),this._onScroll.fire(i)}));let r={onMouseWheel:i=>this._onMouseWheel(i),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new cj(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new oj(this._scrollable,this._options,r)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=vl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=vl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=vl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,i=>this._onMouseOver(i)),this.onmouseleave(this._listenOnDomNode,i=>this._onMouseLeave(i)),this._hideTimeout=this._register(new tp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=wi(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Kn&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new cg(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=wi(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new cg(n))};this._mouseWheelToDispose.push(pe(this._listenOnDomNode,ht.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=hj.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let i=e.deltaY*this._options.mouseWheelScrollSensitivity,s=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&s+i===0?s=i=0:Math.abs(i)>=Math.abs(s)?s=0:i=0),this._options.flipAxes&&([i,s]=[s,i]);let l=!Kn&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||l)&&!s&&(s=i,i=0),e.browserEvent&&e.browserEvent.altKey&&(s=s*this._options.fastScrollSensitivity,i=i*this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),c={};if(i){let u=gg*i,h=o.scrollTop-(u<0?Math.floor(u):Math.ceil(u));this._verticalScrollbar.writeScrollPosition(c,h)}if(s){let u=gg*s,h=o.scrollLeft-(u<0?Math.floor(u):Math.ceil(u));this._horizontalScrollbar.writeScrollPosition(c,h)}c=this._scrollable.validateScrollPosition(c),(o.scrollLeft!==c.scrollLeft||o.scrollTop!==c.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(c):this._scrollable.setScrollPositionNow(c),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?" left":"",i=t?" top":"",s=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${s}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),uj)}},pj=class extends fj{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function mj(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Kn&&(t.className+=" mac"),t}var ph=class extends _e{constructor(e,t,n,r,i,s,l,o){super(),this._bufferService=n,this._optionsService=l,this._renderService=o,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new nj({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:u=>np(r.window,u)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new pj(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(u=>{this._scrollableElement.updateOptions({handleMouseWheel:!(u&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(bt.runAndSubscribe(s.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=s.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register($e(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register($e(()=>this._styleElement.remove())),this._register(bt.runAndSubscribe(s.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${s.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${s.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${s.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(u=>this._handleScroll(u)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};ph=Qe([se(2,Ft),se(3,mr),se(4,xb),se(5,ws),se(6,$t),se(7,gr)],ph);var mh=class extends _e{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(s=>this._removeDecoration(s))),this._register($e(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};mh=Qe([se(1,Ft),se(2,mr),se(3,Ql),se(4,gr)],mh);var gj=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||"full"]&&t<=e.endBufferLine+this._linePadding[n||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},In={full:0,left:0,center:0,right:0},br={full:0,left:0,center:0,right:0},Os={full:0,left:0,center:0,right:0},Uo=class extends _e{constructor(e,t,n,r,i,s,l,o){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=s,this._themeService=l,this._coreBrowserService=o,this._colorZoneStore=new gj,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register($e(()=>this._canvas?.remove()));let c=this._canvas.getContext("2d");if(c)this._ctx=c;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);br.full=this._canvas.width,br.left=e,br.center=t,br.right=e,this._refreshDrawHeightConstants(),Os.full=1,Os.left=1,Os.center=1+br.left,Os.right=1+br.left+br.center}_refreshDrawHeightConstants(){In.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);In.left=t,In.center=t,In.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*In.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Os[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-In[e.position||"full"]/2),br[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+In[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Uo=Qe([se(2,Ft),se(3,Ql),se(4,gr),se(5,$t),se(6,ws),se(7,mr)],Uo);var G;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(G||={});var co;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(co||={});var Bb;(e=>e.ST=`${G.ESC}\\`)(Bb||={});var gh=class{constructor(e,t,n,r,i,s){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=s,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let n;t.start+=this._dataAlreadySent.length,this._isComposing?n=this._textarea.value.substring(t.start,this._compositionPosition.start):n=this._textarea.value.substring(t.start),n.length>0&&this._coreService.triggerDataEvent(n,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,"");this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};gh=Qe([se(2,Ft),se(3,$t),se(4,Ni),se(5,gr)],gh);var pt=0,mt=0,gt=0,Ge=0,xg={css:"#00000000",rgba:0},rt;(e=>{function t(i,s,l,o){return o!==void 0?`#${Jr(i)}${Jr(s)}${Jr(l)}${Jr(o)}`:`#${Jr(i)}${Jr(s)}${Jr(l)}`}e.toCss=t;function n(i,s,l,o=255){return(i<<24|s<<16|l<<8|o)>>>0}e.toRgba=n;function r(i,s,l,o){return{css:e.toCss(i,s,l,o),rgba:e.toRgba(i,s,l,o)}}e.toColor=r})(rt||={});var Be;(e=>{function t(c,u){if(Ge=(u.rgba&255)/255,Ge===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,d=u.rgba>>16&255,f=u.rgba>>8&255,p=c.rgba>>24&255,m=c.rgba>>16&255,x=c.rgba>>8&255;pt=p+Math.round((h-p)*Ge),mt=m+Math.round((d-m)*Ge),gt=x+Math.round((f-x)*Ge);let w=rt.toCss(pt,mt,gt),v=rt.toRgba(pt,mt,gt);return{css:w,rgba:v}}e.blend=t;function n(c){return(c.rgba&255)===255}e.isOpaque=n;function r(c,u,h){let d=uo.ensureContrastRatio(c.rgba,u.rgba,h);if(d)return rt.toColor(d>>24&255,d>>16&255,d>>8&255)}e.ensureContrastRatio=r;function i(c){let u=(c.rgba|255)>>>0;return[pt,mt,gt]=uo.toChannels(u),{css:rt.toCss(pt,mt,gt),rgba:u}}e.opaque=i;function s(c,u){return Ge=Math.round(u*255),[pt,mt,gt]=uo.toChannels(c.rgba),{css:rt.toCss(pt,mt,gt,Ge),rgba:rt.toRgba(pt,mt,gt,Ge)}}e.opacity=s;function l(c,u){return Ge=c.rgba&255,s(c,Ge*u/255)}e.multiplyOpacity=l;function o(c){return[c.rgba>>24&255,c.rgba>>16&255,c.rgba>>8&255]}e.toColorRGB=o})(Be||={});var He;(e=>{let t,n;try{let i=document.createElement("canvas");i.width=1,i.height=1;let s=i.getContext("2d",{willReadFrequently:!0});s&&(t=s,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function r(i){if(i.match(/#[\da-f]{3,8}/i))switch(i.length){case 4:return pt=parseInt(i.slice(1,2).repeat(2),16),mt=parseInt(i.slice(2,3).repeat(2),16),gt=parseInt(i.slice(3,4).repeat(2),16),rt.toColor(pt,mt,gt);case 5:return pt=parseInt(i.slice(1,2).repeat(2),16),mt=parseInt(i.slice(2,3).repeat(2),16),gt=parseInt(i.slice(3,4).repeat(2),16),Ge=parseInt(i.slice(4,5).repeat(2),16),rt.toColor(pt,mt,gt,Ge);case 7:return{css:i,rgba:(parseInt(i.slice(1),16)<<8|255)>>>0};case 9:return{css:i,rgba:parseInt(i.slice(1),16)>>>0}}let s=i.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(s)return pt=parseInt(s[1]),mt=parseInt(s[2]),gt=parseInt(s[3]),Ge=Math.round((s[5]===void 0?1:parseFloat(s[5]))*255),rt.toColor(pt,mt,gt,Ge);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=i,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[pt,mt,gt,Ge]=t.getImageData(0,0,1,1).data,Ge!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rt.toRgba(pt,mt,gt,Ge),css:i}}e.toColor=r})(He||={});var Rt;(e=>{function t(r){return n(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=t;function n(r,i,s){let l=r/255,o=i/255,c=s/255,u=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),h=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),d=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4);return u*.2126+h*.7152+d*.0722}e.relativeLuminance2=n})(Rt||={});var uo;(e=>{function t(l,o){if(Ge=(o&255)/255,Ge===1)return o;let c=o>>24&255,u=o>>16&255,h=o>>8&255,d=l>>24&255,f=l>>16&255,p=l>>8&255;return pt=d+Math.round((c-d)*Ge),mt=f+Math.round((u-f)*Ge),gt=p+Math.round((h-p)*Ge),rt.toRgba(pt,mt,gt)}e.blend=t;function n(l,o,c){let u=Rt.relativeLuminance(l>>8),h=Rt.relativeLuminance(o>>8);if(Zn(u,h)>8));if(m>8));return m>w?p:x}return p}let d=i(l,o,c),f=Zn(u,Rt.relativeLuminance(d>>8));if(f>8));return f>m?d:p}return d}}e.ensureContrastRatio=n;function r(l,o,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=o>>24&255,p=o>>16&255,m=o>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x0||p>0||m>0);)f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),m-=Math.max(0,Math.ceil(m*.1)),x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));return(f<<24|p<<16|m<<8|255)>>>0}e.reduceLuminance=r;function i(l,o,c){let u=l>>24&255,h=l>>16&255,d=l>>8&255,f=o>>24&255,p=o>>16&255,m=o>>8&255,x=Zn(Rt.relativeLuminance2(f,p,m),Rt.relativeLuminance2(u,h,d));for(;x>>0}e.increaseLuminance=i;function s(l){return[l>>24&255,l>>16&255,l>>8&255,l&255]}e.toChannels=s})(uo||={});function Jr(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Zn(e,t){return e1){let h=this._getJoinedRanges(r,l,s,t,i);for(let d=0;d1){let u=this._getJoinedRanges(r,l,s,t,i);for(let h=0;h=k,K=P,E=this._workCell;if(f.length>0&&P===f[0][0]&&U){let B=f.shift(),de=this._isCellInSelection(B[0],t);for(_=B[0]+1;_=B[1],U?(O=!0,E=new xj(this._workCell,e.translateToString(!0,B[0],B[1]),B[1]-B[0]),K=B[1]-1,I=E.getWidth()):k=B[1]}let F=this._isCellInSelection(P,t),j=n&&P===s,re=A&&P>=u&&P<=h,V=!1;this._decorationService.forEachDecorationAtCell(P,t,void 0,B=>{V=!0});let T=E.getChars()||Rr;if(T===" "&&(E.isUnderline()||E.isOverline())&&(T=" "),D=I*o-c.get(T,E.isBold(),E.isItalic()),!x)x=this._document.createElement("span");else if(w&&(F&&R||!F&&!R&&E.bg===y)&&(F&&R&&p.selectionForeground||E.fg===b)&&E.extended.ext===C&&re===S&&D===N&&!j&&!O&&!V&&U){E.isInvisible()?v+=Rr:v+=T,w++;continue}else w&&(x.textContent=v),x=this._document.createElement("span"),w=0,v="";if(y=E.bg,b=E.fg,C=E.extended.ext,S=re,N=D,R=F,O&&s>=P&&s<=K&&(s=P),!this._coreService.isCursorHidden&&j&&this._coreService.isCursorInitialized){if(L.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&L.push("xterm-cursor-blink"),L.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(i)switch(i){case"outline":L.push("xterm-cursor-outline");break;case"block":L.push("xterm-cursor-block");break;case"bar":L.push("xterm-cursor-bar");break;case"underline":L.push("xterm-cursor-underline");break}}if(E.isBold()&&L.push("xterm-bold"),E.isItalic()&&L.push("xterm-italic"),E.isDim()&&L.push("xterm-dim"),E.isInvisible()?v=Rr:v=E.getChars()||Rr,E.isUnderline()&&(L.push(`xterm-underline-${E.extended.underlineStyle}`),v===" "&&(v=" "),!E.isUnderlineColorDefault()))if(E.isUnderlineColorRGB())x.style.textDecorationColor=`rgb(${Xl.toColorRGB(E.getUnderlineColor()).join(",")})`;else{let B=E.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&E.isBold()&&B<8&&(B+=8),x.style.textDecorationColor=p.ansi[B].css}E.isOverline()&&(L.push("xterm-overline"),v===" "&&(v=" ")),E.isStrikethrough()&&L.push("xterm-strikethrough"),re&&(x.style.textDecoration="underline");let ie=E.getFgColor(),ee=E.getFgColorMode(),J=E.getBgColor(),W=E.getBgColorMode(),Y=!!E.isInverse();if(Y){let B=ie;ie=J,J=B;let de=ee;ee=W,W=de}let z,ce,we=!1;this._decorationService.forEachDecorationAtCell(P,t,void 0,B=>{B.options.layer!=="top"&&we||(B.backgroundColorRGB&&(W=50331648,J=B.backgroundColorRGB.rgba>>8&16777215,z=B.backgroundColorRGB),B.foregroundColorRGB&&(ee=50331648,ie=B.foregroundColorRGB.rgba>>8&16777215,ce=B.foregroundColorRGB),we=B.options.layer==="top")}),!we&&F&&(z=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,J=z.rgba>>8&16777215,W=50331648,we=!0,p.selectionForeground&&(ee=50331648,ie=p.selectionForeground.rgba>>8&16777215,ce=p.selectionForeground)),we&&L.push("xterm-decoration-top");let Pe;switch(W){case 16777216:case 33554432:Pe=p.ansi[J],L.push(`xterm-bg-${J}`);break;case 50331648:Pe=rt.toColor(J>>16,J>>8&255,J&255),this._addStyle(x,`background-color:#${vg((J>>>0).toString(16),"0",6)}`);break;case 0:default:Y?(Pe=p.foreground,L.push("xterm-bg-257")):Pe=p.background}switch(z||E.isDim()&&(z=Be.multiplyOpacity(Pe,.5)),ee){case 16777216:case 33554432:E.isBold()&&ie<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ie+=8),this._applyMinimumContrast(x,Pe,p.ansi[ie],E,z,void 0)||L.push(`xterm-fg-${ie}`);break;case 50331648:let B=rt.toColor(ie>>16&255,ie>>8&255,ie&255);this._applyMinimumContrast(x,Pe,B,E,z,ce)||this._addStyle(x,`color:#${vg(ie.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(x,Pe,p.foreground,E,z,ce)||Y&&L.push("xterm-fg-257")}L.length&&(x.className=L.join(" "),L.length=0),!j&&!O&&!V&&U?w++:x.textContent=v,D!==this.defaultSpacing&&(x.style.letterSpacing=`${D}px`),d.push(x),P=K}return x&&w&&(x.textContent=v),d}_applyMinimumContrast(e,t,n,r,i,s){if(this._optionsService.rawOptions.minimumContrastRatio===1||yj(r.getCode()))return!1;let l=this._getContrastCache(r),o;if(!i&&!s&&(o=l.getColor(t.rgba,n.rgba)),o===void 0){let c=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);o=Be.ensureContrastRatio(i||t,s||n,c),l.setColor((i||t).rgba,(s||n).rgba,o??null)}return o?(this._addStyle(e,`color:${o.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};xh=Qe([se(1,yb),se(2,$t),se(3,mr),se(4,Ni),se(5,Ql),se(6,ws)],xh);function vg(e,t,n){for(;e.length0&&(this._flat[r]=l),l}let i=e;t&&(i+="B"),n&&(i+="I");let s=this._holey.get(i);if(s===void 0){let l=0;t&&(l|=1),n&&(l|=2),s=this._measure(e,l),s>0&&this._holey.set(i,s)}return s}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Sj=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,s=t[1]-i,l=n[1]-i,o=Math.max(s,0),c=Math.min(l,e.rows-1);if(o>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=s,this.viewportEndRow=l,this.viewportCappedStartRow=o,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function kj(){return new Sj}var hu="xterm-dom-renderer-owner-",hn="xterm-rows",Na="xterm-fg-",_g="xterm-bg-",Bs="xterm-focus",Ea="xterm-selection",Cj=1,vh=class extends _e{constructor(e,t,n,r,i,s,l,o,c,u,h,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=s,this._linkifier2=l,this._charSizeService=c,this._optionsService=u,this._bufferService=h,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Cj++,this._rowElements=[],this._selectionRenderModel=kj(),this.onRequestRedraw=this._register(new ne).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(hn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Ea),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=bj(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(m=>this._injectCss(m))),this._injectCss(this._themeService.colors),this._rowFactory=o.createInstance(xh,document),this._element.classList.add(hu+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(m=>this._handleLinkHover(m))),this._register(this._linkifier2.onHideLinkUnderline(m=>this._handleLinkLeave(m))),this._register($e(()=>{this._element.classList.remove(hu+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new wj(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let n of this._rowElements)n.style.width=`${this.dimensions.css.canvas.width}px`,n.style.height=`${this.dimensions.css.cell.height}px`,n.style.lineHeight=`${this.dimensions.css.cell.height}px`,n.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${hn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${hn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${hn} .xterm-dim { color: ${Be.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${hn}.${Bs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${hn}.${Bs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${hn}.${Bs} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${hn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Ea} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Ea} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Ea} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[s,l]of e.ansi.entries())t+=`${this._terminalSelector} .${Na}${s} { color: ${l.css}; }${this._terminalSelector} .${Na}${s}.xterm-dim { color: ${Be.multiplyOpacity(l,.5).css}; }${this._terminalSelector} .${_g}${s} { background-color: ${l.css}; }`;t+=`${this._terminalSelector} .${Na}257 { color: ${Be.opaque(e.background).css}; }${this._terminalSelector} .${Na}257.xterm-dim { color: ${Be.multiplyOpacity(Be.opaque(e.background),.5).css}; }${this._terminalSelector} .${_g}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let n=this._rowElements.length;n<=t;n++){let r=this._document.createElement("div");this._rowContainer.appendChild(r),this._rowElements.push(r)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Bs),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Bs),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,s=this._selectionRenderModel.viewportCappedStartRow,l=this._selectionRenderModel.viewportCappedEndRow,o=this._document.createDocumentFragment();if(n){let c=e[0]>t[0];o.appendChild(this._createSelectionElement(s,c?t[0]:e[0],c?e[0]:t[0],l-s+1))}else{let c=r===s?e[0]:0,u=s===i?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(s,c,u));let h=l-s-1;if(o.appendChild(this._createSelectionElement(s+1,0,this._bufferService.cols,h)),s!==l){let d=i===l?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(l,0,d))}}this._selectionContainer.appendChild(o)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement("div"),s=t*this.dimensions.css.cell.width,l=this.dimensions.css.cell.width*(n-t);return s+l>this.dimensions.css.canvas.width&&(l=this.dimensions.css.canvas.width-s),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${s}px`,i.style.width=`${l}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),s=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,l=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,o=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let u=c+n.ydisp,h=this._rowElements[c],d=n.lines.get(u);if(!h||!d)break;h.replaceChildren(...this._rowFactory.createRow(d,u,u===r,l,o,i,s,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${hu}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,s){n<0&&(e=0),r<0&&(t=0);let l=this._bufferService.rows-1;n=Math.max(Math.min(n,l),0),r=Math.max(Math.min(r,l),0),i=Math.min(i,this._bufferService.cols);let o=this._bufferService.buffer,c=o.ybase+o.y,u=Math.min(o.x,i-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=n;p<=r;++p){let m=p+o.ydisp,x=this._rowElements[p],w=o.lines.get(m);if(!x||!w)break;x.replaceChildren(...this._rowFactory.createRow(w,m,m===c,d,f,u,h,this.dimensions.css.cell.width,this._widthCache,s?p===n?e:0:-1,s?(p===r?t:i)-1:-1))}}};vh=Qe([se(7,Xf),se(8,wc),se(9,$t),se(10,Ft),se(11,Ni),se(12,mr),se(13,ws)],vh);var _h=class extends _e{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new ne),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Nj(this._optionsService))}catch{this._measureStrategy=this._register(new jj(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};_h=Qe([se(2,$t)],_h);var zb=class extends _e{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},jj=class extends zb{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Nj=class extends zb{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Ej=class extends _e{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Pj(this._window)),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new ne),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(r=>this._screenDprMonitor.setWindow(r))),this._register(bt.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(pe(this._textarea,"focus",()=>this._isFocused=!0)),this._register(pe(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Pj=class extends _e{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new gs),this._onDprChange=this._register(new ne),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register($e(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=pe(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Aj=class extends _e{constructor(){super(),this.linkProviders=[],this._register($e(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function ip(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),s=parseInt(i.getPropertyValue("padding-left")),l=parseInt(i.getPropertyValue("padding-top"));return[t.clientX-r.left-s,t.clientY-r.top-l]}function Tj(e,t,n,r,i,s,l,o,c){if(!s)return;let u=ip(e,t,n);if(u)return u[0]=Math.ceil((u[0]+(c?l/2:0))/l),u[1]=Math.ceil(u[1]/o),u[0]=Math.min(Math.max(u[0],1),r+(c?1:0)),u[1]=Math.min(Math.max(u[1],1),i),u}var yh=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return Tj(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=ip(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};yh=Qe([se(0,gr),se(1,wc)],yh);var Lj=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Fb={};W1(Fb,{getSafariVersion:()=>Rj,isChromeOS:()=>Ub,isFirefox:()=>$b,isIpad:()=>Mj,isIphone:()=>Ij,isLegacyEdge:()=>Dj,isLinux:()=>sp,isMac:()=>Vo,isNode:()=>Sc,isSafari:()=>Wb,isWindows:()=>Hb});var Sc=typeof process<"u"&&"title"in process,Jl=Sc?"node":navigator.userAgent,Zl=Sc?"node":navigator.platform,$b=Jl.includes("Firefox"),Dj=Jl.includes("Edge"),Wb=/^((?!chrome|android).)*safari/i.test(Jl);function Rj(){if(!Wb)return 0;let e=Jl.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Vo=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zl),Mj=Zl==="iPad",Ij=Zl==="iPhone",Hb=["Windows","Win16","Win32","WinCE"].includes(Zl),sp=Zl.indexOf("Linux")>=0,Ub=/\bCrOS\b/.test(Jl),qb=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Oj=class extends qb{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Bj=class extends qb{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ko=!Sc&&"requestIdleCallback"in window?Bj:Oj,zj=class{constructor(){this._queue=new Ko}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},bh=class extends _e{constructor(e,t,n,r,i,s,l,o,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=o,this._renderer=this._register(new gs),this._pausedResizeTask=new zj,this._observerDisposable=this._register(new gs),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new ne),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new ne),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new ne),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Lj((u,h)=>this._renderRows(u,h),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Fj(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register($e(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(l.onResize(()=>this._fullRefresh())),this._register(l.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(s.onDecorationRegistered(()=>this._fullRefresh())),this._register(s.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(l.cols,l.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(l.buffer.y,l.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(u=>this._registerIntersectionObserver(u,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let n=new e.IntersectionObserver(r=>this._handleIntersectionChange(r[r.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=$e(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};bh=Qe([se(2,$t),se(3,wc),se(4,Ni),se(5,Ql),se(6,Ft),se(7,mr),se(8,ws)],bh);var Fj=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function $j(e,t,n,r){let i=n.buffer.x,s=n.buffer.y;if(!n.buffer.hasScrollback)return Uj(i,s,e,t,n,r)+kc(s,t,n,r)+qj(i,s,e,t,n,r);let l;if(s===t)return l=i>e?"D":"C",Fl(Math.abs(i-e),zl(l,r));l=s>t?"D":"C";let o=Math.abs(s-t),c=Hj(s>t?e:i,n)+(o-1)*n.cols+1+Wj(s>t?i:e);return Fl(c,zl(l,r))}function Wj(e,t){return e-1}function Hj(e,t){return t.cols-e}function Uj(e,t,n,r,i,s){return kc(t,r,i,s).length===0?"":Fl(Kb(e,t,e,t-Si(t,i),!1,i).length,zl("D",s))}function kc(e,t,n,r){let i=e-Si(e,n),s=t-Si(t,n),l=Math.abs(i-s)-Vj(e,t,n);return Fl(l,zl(Vb(e,t),r))}function qj(e,t,n,r,i,s){let l;kc(t,r,i,s).length>0?l=r-Si(r,i):l=t;let o=r,c=Kj(e,t,n,r,i,s);return Fl(Kb(e,l,n,o,c==="C",i).length,zl(c,s))}function Vj(e,t,n){let r=0,i=e-Si(e,n),s=t-Si(t,n);for(let l=0;l=0&&e0?l=r-Si(r,i):l=t,e=n&&lt?"A":"B"}function Kb(e,t,n,r,i,s){let l=e,o=t,c="";for(;(l!==n||o!==r)&&o>=0&&os.cols-1?(c+=s.buffer.translateBufferLineToString(o,!1,e,l),l=0,e=0,o++):!i&&l<0&&(c+=s.buffer.translateBufferLineToString(o,!1,0,e+1),l=s.cols-1,e=l,o--);return c+s.buffer.translateBufferLineToString(o,!1,e,l)}function zl(e,t){let n=t?"O":"[";return G.ESC+n+e}function Fl(e,t){e=Math.floor(e);let n="";for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function yg(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var fu=50,Yj=15,Xj=50,Qj=500,Jj=" ",Zj=new RegExp(Jj,"g"),wh=class extends _e{constructor(e,t,n,r,i,s,l,o,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=s,this._optionsService=l,this._renderService=o,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new bn,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new ne),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new ne),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new ne),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=u=>this._handleMouseMove(u),this._mouseUpListener=u=>this._handleMouseUp(u),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(u=>this._handleTrim(u)),this._register(this._bufferService.buffers.onBufferActivate(u=>this._handleBufferActivate(u))),this.enable(),this._model=new Gj(this._bufferService),this._activeSelectionMode=0,this._register($e(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(u=>{u.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let i=e[0]i.replace(Zj," ")).join(Hb?`\r -`:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),sp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=yg(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=ip(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-fu),fu),t/=fu,t/Math.abs(t)+Math.round(t*(Yj-1)))}shouldForceSelection(e){return Vo?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Xj)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Vo&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,s=i.lines.get(e[1]);if(!s)return;let l=i.translateBufferLineToString(e[1],!1),o=this._convertViewportColToCharacterIndex(s,e[0]),c=o,u=e[0]-o,h=0,d=0,f=0,p=0;if(l.charAt(o)===" "){for(;o>0&&l.charAt(o-1)===" ";)o--;for(;c1&&(p+=_-1,c+=_-1);w>0&&o>0&&!this._isCharWordSeparator(s.loadCell(w-1,this._workCell));){s.loadCell(w-1,this._workCell);let y=this._workCell.getChars().length;this._workCell.getWidth()===0?(h++,w--):y>1&&(f+=y-1,o-=y-1),o--,w--}for(;v1&&(p+=y-1,c+=y-1),c++,v++}}c++;let m=o+u-h+f,x=Math.min(this._bufferService.cols,c-o+h+d-f-p);if(!(!t&&l.slice(o,c).trim()==="")){if(n&&m===0&&s.getCodePoint(0)!==32){let w=i.lines.get(e[1]-1);if(w&&s.isWrapped&&w.getCodePoint(this._bufferService.cols-1)!==32){let v=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(v){let _=this._bufferService.cols-v.start;m-=_,x+=_}}}if(r&&m+x===this._bufferService.cols&&s.getCodePoint(this._bufferService.cols-1)!==32){let w=i.lines.get(e[1]+1);if(w?.isWrapped&&w.getCodePoint(0)!==32){let v=this._getWordAt([0,e[1]+1],!1,!1,!0);v&&(x+=v.length)}}return{start:m,length:x}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=yg(n,this._bufferService.cols)}};wh=Qe([se(3,Ft),se(4,Ni),se(5,Qf),se(6,$t),se(7,gr),se(8,mr)],wh);var bg=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},wg=class{constructor(){this._color=new bg,this._css=new bg}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},st=Object.freeze((()=>{let e=[He.toColor("#2e3436"),He.toColor("#cc0000"),He.toColor("#4e9a06"),He.toColor("#c4a000"),He.toColor("#3465a4"),He.toColor("#75507b"),He.toColor("#06989a"),He.toColor("#d3d7cf"),He.toColor("#555753"),He.toColor("#ef2929"),He.toColor("#8ae234"),He.toColor("#fce94f"),He.toColor("#729fcf"),He.toColor("#ad7fa8"),He.toColor("#34e2e2"),He.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],s=t[n%6];e.push({css:rt.toCss(r,i,s),rgba:rt.toRgba(r,i,s)})}for(let n=0;n<24;n++){let r=8+n*10;e.push({css:rt.toCss(r,r,r),rgba:rt.toRgba(r,r,r)})}return e})()),ii=He.toColor("#ffffff"),sl=He.toColor("#000000"),Sg=He.toColor("#ffffff"),kg=sl,zs={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},eN=ii,Sh=class extends _e{constructor(e){super(),this._optionsService=e,this._contrastCache=new wg,this._halfContrastCache=new wg,this._onChangeColors=this._register(new ne),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:ii,background:sl,cursor:Sg,cursorAccent:kg,selectionForeground:void 0,selectionBackgroundTransparent:zs,selectionBackgroundOpaque:Be.blend(sl,zs),selectionInactiveBackgroundTransparent:zs,selectionInactiveBackgroundOpaque:Be.blend(sl,zs),scrollbarSliderBackground:Be.opacity(ii,.2),scrollbarSliderHoverBackground:Be.opacity(ii,.4),scrollbarSliderActiveBackground:Be.opacity(ii,.5),overviewRulerBorder:ii,ansi:st.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Ae(e.foreground,ii),t.background=Ae(e.background,sl),t.cursor=Be.blend(t.background,Ae(e.cursor,Sg)),t.cursorAccent=Be.blend(t.background,Ae(e.cursorAccent,kg)),t.selectionBackgroundTransparent=Ae(e.selectionBackground,zs),t.selectionBackgroundOpaque=Be.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Ae(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Be.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Ae(e.selectionForeground,xg):void 0,t.selectionForeground===xg&&(t.selectionForeground=void 0),Be.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Be.opacity(t.selectionBackgroundTransparent,.3)),Be.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Be.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Ae(e.scrollbarSliderBackground,Be.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Ae(e.scrollbarSliderHoverBackground,Be.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Ae(e.scrollbarSliderActiveBackground,Be.opacity(t.foreground,.5)),t.overviewRulerBorder=Ae(e.overviewRulerBorder,eN),t.ansi=st.slice(),t.ansi[0]=Ae(e.black,st[0]),t.ansi[1]=Ae(e.red,st[1]),t.ansi[2]=Ae(e.green,st[2]),t.ansi[3]=Ae(e.yellow,st[3]),t.ansi[4]=Ae(e.blue,st[4]),t.ansi[5]=Ae(e.magenta,st[5]),t.ansi[6]=Ae(e.cyan,st[6]),t.ansi[7]=Ae(e.white,st[7]),t.ansi[8]=Ae(e.brightBlack,st[8]),t.ansi[9]=Ae(e.brightRed,st[9]),t.ansi[10]=Ae(e.brightGreen,st[10]),t.ansi[11]=Ae(e.brightYellow,st[11]),t.ansi[12]=Ae(e.brightBlue,st[12]),t.ansi[13]=Ae(e.brightMagenta,st[13]),t.ansi[14]=Ae(e.brightCyan,st[14]),t.ansi[15]=Ae(e.brightWhite,st[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;rs.index-l.index),r=[];for(let s of n){let l=this._services.get(s.id);if(!l)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${s.id._id}.`);r.push(l)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},rN={trace:0,debug:1,info:2,warn:3,error:4,off:5},iN="xterm.js: ",kh=class extends _e{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=rN[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;r--)this._array[this._getCyclicIndex(r+n.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;rthis._maxLength){let r=this._length+n.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+n<0)throw new Error("Cannot shift elements in list beyond index 0");if(n>0){for(let i=t-1;i>=0;i--)this.set(e+i+n,this.get(e+i));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r]}set(t,n){this._data[t*ve+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*ve+0]=t|2097152|n[2]<<22):this._data[t*ve+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*ve+0]>>22}hasWidth(t){return this._data[t*ve+0]&12582912}getFg(t){return this._data[t*ve+1]}getBg(t){return this._data[t*ve+2]}hasContent(t){return this._data[t*ve+0]&4194303}getCodePoint(t){let n=this._data[t*ve+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*ve+0]&2097152}getString(t){let n=this._data[t*ve+0];return n&2097152?this._combined[t]:n&2097151?Nr(n&2097151):""}isProtected(t){return this._data[t*ve+2]&536870912}loadCell(t,n){return Pa=t*ve,n.content=this._data[Pa+0],n.fg=this._data[Pa+1],n.bg=this._data[Pa+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*ve+0]=n.content,this._data[t*ve+1]=n.fg,this._data[t*ve+2]=n.bg}setCellFromCodepoint(t,n,r,i){i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ve+0]=n|r<<22,this._data[t*ve+1]=i.fg,this._data[t*ve+2]=i.bg}addCodepointToCell(t,n,r){let i=this._data[t*ve+0];i&2097152?this._combined[t]+=Nr(n):i&2097151?(this._combined[t]=Nr(i&2097151)+Nr(n),i&=-2097152,i|=2097152):i=n|1<<22,r&&(i&=-12582913,i|=r<<22),this._data[t*ve+0]=i}insertCells(t,n,r){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,r),n=0;--s)this.setCell(t+n+s,this.loadCell(t+s,i));for(let s=0;sthis.length){if(this._data.buffer.byteLength>=r*4)this._data=new Uint32Array(this._data.buffer,0,r);else{let i=new Uint32Array(r);i.set(this._data),this._data=i}for(let i=this.length;i=t&&delete this._combined[o]}let s=Object.keys(this._extendedAttrs);for(let l=0;l=t&&delete this._extendedAttrs[o]}}return this.length=t,r*4*pu=0;--t)if(this._data[t*ve+0]&4194303)return t+(this._data[t*ve+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ve+0]&4194303||this._data[t*ve+2]&50331648)return t+(this._data[t*ve+0]>>22);return 0}copyCellsFrom(t,n,r,i,s){let l=t._data;if(s)for(let c=i-1;c>=0;c--){for(let u=0;u=n&&(this._combined[u-n+r]=t._combined[u])}}translateToString(t,n,r,i){n=n??0,r=r??this.length,t&&(r=Math.min(r,this.getTrimmedLength())),i&&(i.length=0);let s="";for(;n>22||1}return i&&i.push(n),s}};function sN(e,t,n,r,i,s){let l=[];for(let o=0;o=o&&r0&&(w>d||h[w].getTrimmedLength()===0);w--)x++;x>0&&(l.push(o+h.length-x),l.push(x)),o+=h.length-1}return l}function lN(e,t){let n=[],r=0,i=t[r],s=0;for(let l=0;l$l(e,u,t)).reduce((c,u)=>c+u),s=0,l=0,o=0;for(;oc&&(s-=c,l++);let u=e[l].getWidth(s-1)===2;u&&s--;let h=u?n-1:n;r.push(h),o+=h}return r}function $l(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var Yb=class Xb{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Xb._nextId++,this._onDispose=this.register(new ne),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),wi(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Yb._nextId=1;var cN=Yb,ut={},si=ut.B;ut[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ut.A={"#":"£"};ut.B=void 0;ut[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ut.C=ut[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ut.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ut.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ut.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ut.E=ut[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ut.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ut.H=ut[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ut["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var jg=4294967295,Ng=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=nt.clone(),this.savedCharset=si,this.markers=[],this._nullCell=bn.fromCharData([0,fb,1,0]),this._whitespaceCell=bn.fromCharData([0,Rr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ko,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Cg(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Ho),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Ho),this._whitespaceCell}getBlankLine(e,t){return new ll(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&ejg?jg:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=nt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Cg(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(nt),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+s+1?(this.ybase--,s++,this.ydisp>0&&this.ydisp--):this.lines.push(new ll(e,n)));else for(let l=this._rows;l>t;l--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),s&&(this.y+=s),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let s=0;s.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=sN(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(nt),n);if(r.length>0){let i=lN(this.lines,r);aN(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(nt),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let o=this.lines.get(l);if(!o||!o.isWrapped&&o.getTrimmedLength()<=e)continue;let c=[o];for(;o.isWrapped&&l>0;)o=this.lines.get(--l),c.unshift(o);if(!n){let y=this.ybase+this.y;if(y>=l&&y0&&(i.push({start:l+c.length+s,newLines:p}),s+=p.length),c.push(...p);let m=h.length-1,x=h[m];x===0&&(m--,x=h[m]);let w=c.length-d-1,v=u;for(;w>=0;){let y=Math.min(v,x);if(c[m]===void 0)break;if(c[m].copyCellsFrom(c[w],v-y,x-y,y,!0),x-=y,x===0&&(m--,x=h[m]),v-=y,v===0){w--;let b=Math.max(w,0);v=$l(c,b,this._cols)}}for(let y=0;y0;)this.ybase===0?this.y0){let l=[],o=[];for(let x=0;x=0;x--)if(d&&d.start>u+f){for(let w=d.newLines.length-1;w>=0;w--)this.lines.set(x--,d.newLines[w]);x++,l.push({index:u+1,amount:d.newLines.length}),f+=d.newLines.length,d=i[++h]}else this.lines.set(x,o[u--]);let p=0;for(let x=l.length-1;x>=0;x--)l[x].index+=p,this.lines.onInsertEmitter.fire(l[x]),p+=l[x].amount;let m=Math.max(0,c+s-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.linen.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},uN=class extends _e{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ne),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ng(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ng(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Qb=2,Jb=1,Ch=class extends _e{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Qb),this.rows=Math.max(e.rawOptions.rows||0,Jb),this.buffers=this._register(new uN(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,s=n.ybase+n.scrollBottom;if(n.scrollTop===0){let l=n.lines.isFull;s===n.lines.length-1?l?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(s+1,0,r.clone()),l?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let l=s-i+1;n.lines.shiftElements(i+1,l-1,-1),n.lines.set(s,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Ch=Qe([se(0,$t)],Ch);var Li={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Vo,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},dN=["normal","bold","100","200","300","400","500","600","700","800","900"],hN=class extends _e{constructor(e){super(),this._onOptionChange=this._register(new ne),this.onOptionChange=this._onOptionChange.event;let t={...Li};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(r){console.error(r)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register($e(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=n=>{if(!(n in Li))throw new Error(`No option with key "${n}"`);return this.rawOptions[n]},t=(n,r)=>{if(!(n in Li))throw new Error(`No option with key "${n}"`);r=this._sanitizeAndValidateOption(n,r),this.rawOptions[n]!==r&&(this.rawOptions[n]=r,this._onOptionChange.fire(n))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Li[e]),!fN(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Li[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=dN.includes(t)?t:Li[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function fN(e){return e==="block"||e==="underline"||e==="bar"}function al(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&al(e[r],t-1);return n}var Eg=Object.freeze({insertMode:!1}),Pg=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),jh=class extends _e{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new ne),this.onData=this._onData.event,this._onUserInput=this._register(new ne),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ne),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=al(Eg),this.decPrivateModes=al(Pg)}reset(){this.modes=al(Eg),this.decPrivateModes=al(Pg)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(r=>r.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};jh=Qe([se(0,Ft),se(1,vb),se(2,$t)],jh);var Ag={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function mu(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var gu=String.fromCharCode,Tg={DEFAULT:e=>{let t=[mu(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${gu(t[0])}${gu(t[1])}${gu(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${mu(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${mu(e,!0)};${e.x};${e.y}${t}`}},Nh=class extends _e{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new ne),this.onProtocolChange=this._onProtocolChange.event;for(let r of Object.keys(Ag))this.addProtocol(r,Ag[r]);for(let r of Object.keys(Tg))this.addEncoding(r,Tg[r]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Nh=Qe([se(0,Ft),se(1,Ni),se(2,$t)],Nh);var xu=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],pN=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],lt;function mN(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let i=di.extractWidth(t);i===0?r=!1:i>n&&(n=i)}return di.createPropertyValue(0,n,r)}},di=class ho{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ne,this.onChange=this._onChange.event;let t=new gN;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,r=!1){return(t&16777215)<<3|(n&3)<<1|(r?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let s=0;s=i)return n+this.wcwidth(l);let u=t.charCodeAt(s);56320<=u&&u<=57343?l=(l-55296)*1024+u-56320+65536:n+=this.wcwidth(u)}let o=this.charProperties(l,r),c=ho.extractWidth(o);ho.extractShouldJoin(o)&&(c-=ho.extractWidth(r)),n+=c,r=o}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},xN=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Lg(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Fs=2147483647,vN=256,Zb=class Eh{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>vN)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new Eh;if(!t.length)return n;for(let r=Array.isArray(t[0])?1:0;r>8,i=this._subParamsIdx[n]&255;i-r>0&&t.push(Array.prototype.slice.call(this._subParams,r,i))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Fs?Fs:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Fs?Fs:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;return r-n>0?this._subParams.subarray(n,r):null}getSubParamsAll(){let t={};for(let n=0;n>8,i=this._subParamsIdx[n]&255;i-r>0&&(t[n]=this._subParams.slice(r,i))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,i=r[n-1];r[n-1]=~i?Math.min(i*10+t,Fs):t}},$s=[],_N=class{constructor(){this._state=0,this._active=$s,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=$s}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=$s,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||$s,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,"PUT",bc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=$s,this._id=-1,this._state=0}}},en=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=bc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(n=>(this._data="",this._hitLimit=!1,n));return this._data="",this._hitLimit=!1,t}},Ws=[],yN=class{constructor(){this._handlers=Object.create(null),this._active=Ws,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Ws}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Ws,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Ws,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let n=this._active.length-1;n>=0;n--)this._active[n].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,"PUT",bc(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Ws,this._ident=0}},ol=new Zb;ol.addParam(0);var Dg=class{constructor(e){this._handler=e,this._data="",this._params=ol,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ol,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=bc(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=ol,this._data="",this._hitLimit=!1,n));return this._params=ol,this._data="",this._hitLimit=!1,t}},bN=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;ic),n=(o,c)=>t.slice(o,c),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let s=n(0,14),l;e.setDefault(1,0),e.addMany(r,0,2,0);for(l in s)e.addMany([24,26,153,154],l,3,0),e.addMany(n(128,144),l,3,0),e.addMany(n(144,152),l,3,0),e.add(156,l,0,0),e.add(27,l,11,1),e.add(157,l,4,8),e.addMany([152,158,159],l,0,7),e.add(155,l,11,3),e.add(144,l,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(mn,0,2,0),e.add(mn,8,5,8),e.add(mn,6,0,6),e.add(mn,11,0,11),e.add(mn,13,13,13),e}(),SN=class extends _e{constructor(e=wN){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Zb,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,n,r)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,n)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register($e(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new _N),this._dcsParser=this._register(new yN),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let i=0;is||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");n<<=8,n|=s}}if(e.final.length!==1)throw new Error("final must be a single byte");let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let i=r.indexOf(t);i!==-1&&r.splice(i,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let i=r.indexOf(t);i!==-1&&r.splice(i,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,s=0,l;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,s=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let o=this._parseStack.handlers,c=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&c>-1){for(;c>=0&&(l=o[c](this._params),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 4:if(n===!1&&c>-1){for(;c>=0&&(l=o[c](),l!==!0);c--)if(l instanceof Promise)return this._parseStack.handlerPos=c,l}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],l=this._dcsParser.unhook(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],l=this._oscParser.end(r!==24&&r!==26,n),l)return l;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,s=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let o=s;o>4){case 2:for(let f=o+1;;++f){if(f>=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=t||(r=e[f])<32||r>126&&r=0&&(l=c[u](this._params),l!==!0);u--)if(l instanceof Promise)return this._preserveStack(3,c,u,i,o),l;u<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++o47&&r<60);o--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let h=this._escHandlers[this._collect<<8|r],d=h?h.length-1:-1;for(;d>=0&&(l=h[d](),l!==!0);d--)if(l instanceof Promise)return this._preserveStack(4,h,d,i,o),l;d<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let f=o+1;;++f)if(f>=t||(r=e[f])===24||r===26||r===27||r>127&&r=t||(r=e[f])<32||r>127&&r>4:s>>8}return r}}function vu(e,t){let n=e.toString(16),r=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function jN(e,t=16){let[n,r,i]=e;return`rgb:${vu(n,t)}/${vu(r,t)}/${vu(i,t)}`}var NN={"(":0,")":1,"*":2,"+":3,"-":1,".":2},wr=131072,Mg=10;function Ig(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Og=5e3,Bg=0,EN=class extends _e{constructor(e,t,n,r,i,s,l,o,c=new SN){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=s,this._coreMouseService=l,this._unicodeService=o,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new K1,this._utf8Decoder=new G1,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone(),this._onRequestBell=this._register(new ne),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ne),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ne),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ne),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ne),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ne),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ne),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ne),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ne),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ne),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Ph(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,h)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:h.toArray()})}),this._parser.setEscHandlerFallback(u=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(u)})}),this._parser.setExecuteHandlerFallback(u=>{this._logService.debug("Unknown EXECUTE code: ",{code:u})}),this._parser.setOscHandlerFallback((u,h,d)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:h,data:d})}),this._parser.setDcsHandlerFallback((u,h,d)=>{h==="HOOK"&&(d=d.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:h,payload:d})}),this._parser.setPrintHandler((u,h,d)=>this.print(u,h,d)),this._parser.registerCsiHandler({final:"@"},u=>this.insertChars(u)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},u=>this.scrollLeft(u)),this._parser.registerCsiHandler({final:"A"},u=>this.cursorUp(u)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},u=>this.scrollRight(u)),this._parser.registerCsiHandler({final:"B"},u=>this.cursorDown(u)),this._parser.registerCsiHandler({final:"C"},u=>this.cursorForward(u)),this._parser.registerCsiHandler({final:"D"},u=>this.cursorBackward(u)),this._parser.registerCsiHandler({final:"E"},u=>this.cursorNextLine(u)),this._parser.registerCsiHandler({final:"F"},u=>this.cursorPrecedingLine(u)),this._parser.registerCsiHandler({final:"G"},u=>this.cursorCharAbsolute(u)),this._parser.registerCsiHandler({final:"H"},u=>this.cursorPosition(u)),this._parser.registerCsiHandler({final:"I"},u=>this.cursorForwardTab(u)),this._parser.registerCsiHandler({final:"J"},u=>this.eraseInDisplay(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},u=>this.eraseInDisplay(u,!0)),this._parser.registerCsiHandler({final:"K"},u=>this.eraseInLine(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},u=>this.eraseInLine(u,!0)),this._parser.registerCsiHandler({final:"L"},u=>this.insertLines(u)),this._parser.registerCsiHandler({final:"M"},u=>this.deleteLines(u)),this._parser.registerCsiHandler({final:"P"},u=>this.deleteChars(u)),this._parser.registerCsiHandler({final:"S"},u=>this.scrollUp(u)),this._parser.registerCsiHandler({final:"T"},u=>this.scrollDown(u)),this._parser.registerCsiHandler({final:"X"},u=>this.eraseChars(u)),this._parser.registerCsiHandler({final:"Z"},u=>this.cursorBackwardTab(u)),this._parser.registerCsiHandler({final:"`"},u=>this.charPosAbsolute(u)),this._parser.registerCsiHandler({final:"a"},u=>this.hPositionRelative(u)),this._parser.registerCsiHandler({final:"b"},u=>this.repeatPrecedingCharacter(u)),this._parser.registerCsiHandler({final:"c"},u=>this.sendDeviceAttributesPrimary(u)),this._parser.registerCsiHandler({prefix:">",final:"c"},u=>this.sendDeviceAttributesSecondary(u)),this._parser.registerCsiHandler({final:"d"},u=>this.linePosAbsolute(u)),this._parser.registerCsiHandler({final:"e"},u=>this.vPositionRelative(u)),this._parser.registerCsiHandler({final:"f"},u=>this.hVPosition(u)),this._parser.registerCsiHandler({final:"g"},u=>this.tabClear(u)),this._parser.registerCsiHandler({final:"h"},u=>this.setMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"h"},u=>this.setModePrivate(u)),this._parser.registerCsiHandler({final:"l"},u=>this.resetMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"l"},u=>this.resetModePrivate(u)),this._parser.registerCsiHandler({final:"m"},u=>this.charAttributes(u)),this._parser.registerCsiHandler({final:"n"},u=>this.deviceStatus(u)),this._parser.registerCsiHandler({prefix:"?",final:"n"},u=>this.deviceStatusPrivate(u)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},u=>this.softReset(u)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},u=>this.setCursorStyle(u)),this._parser.registerCsiHandler({final:"r"},u=>this.setScrollRegion(u)),this._parser.registerCsiHandler({final:"s"},u=>this.saveCursor(u)),this._parser.registerCsiHandler({final:"t"},u=>this.windowOptions(u)),this._parser.registerCsiHandler({final:"u"},u=>this.restoreCursor(u)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},u=>this.insertColumns(u)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},u=>this.deleteColumns(u)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},u=>this.selectProtected(u)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},u=>this.requestMode(u,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},u=>this.requestMode(u,!1)),this._parser.setExecuteHandler(G.BEL,()=>this.bell()),this._parser.setExecuteHandler(G.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(G.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(G.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(G.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(G.BS,()=>this.backspace()),this._parser.setExecuteHandler(G.HT,()=>this.tab()),this._parser.setExecuteHandler(G.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(G.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(co.IND,()=>this.index()),this._parser.setExecuteHandler(co.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(co.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new en(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new en(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new en(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new en(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new en(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new en(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new en(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new en(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new en(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new en(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new en(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new en(u=>this.restoreCursorColor(u))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let u in ut)this._parser.registerEscHandler({intermediates:"(",final:u},()=>this.selectCharset("("+u)),this._parser.registerEscHandler({intermediates:")",final:u},()=>this.selectCharset(")"+u)),this._parser.registerEscHandler({intermediates:"*",final:u},()=>this.selectCharset("*"+u)),this._parser.registerEscHandler({intermediates:"+",final:u},()=>this.selectCharset("+"+u)),this._parser.registerEscHandler({intermediates:"-",final:u},()=>this.selectCharset("-"+u)),this._parser.registerEscHandler({intermediates:".",final:u},()=>this.selectCharset("."+u)),this._parser.registerEscHandler({intermediates:"/",final:u},()=>this.selectCharset("/"+u));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(u=>(this._logService.error("Parsing error: ",u),u)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Dg((u,h)=>this.requestStatusString(u,h)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),Og))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Og} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,s=0,l=this._parseStack.paused;if(l){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>wr&&(s=this._parseStack.position+wr)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,u=>String.fromCharCode(u)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(u=>u.charCodeAt(0)):e),this._parseBuffer.lengthwr)for(let u=s;u0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let f=this._parser.precedingJoinState;for(let p=t;po){if(c){let v=d,_=this._activeBuffer.x-w;for(this._activeBuffer.x=w,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),w>0&&d instanceof ll&&d.copyCellsFrom(v,_,0,w,!1);_=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(u&&(d.insertCells(this._activeBuffer.x,i-w,this._activeBuffer.getNullCell(h)),d.getWidth(o-1)===2&&d.setCellFromCodepoint(o-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,h),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>Ig(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Dg(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new en(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(s.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let r=this._activeBuffer.lines.length-this._bufferService.rows;r>0&&(this._activeBuffer.lines.trimStart(r),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-r,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-r,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=o;for(let u=1;u0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(G.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(G.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(G.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(G.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(G.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(x[x.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",x[x.SET=1]="SET",x[x.RESET=2]="RESET",x[x.PERMANENTLY_SET=3]="PERMANENTLY_SET",x[x.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:s}=this._coreMouseService,l=this._coreService,{buffers:o,cols:c}=this._bufferService,{active:u,alt:h}=o,d=this._optionsService.rawOptions,f=(x,w)=>(l.triggerDataEvent(`${G.ESC}[${t?"":"?"}${x};${w}$y`),!0),p=x=>x?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(l.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:c===132?1:0:0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i==="X10")):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!l.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i==="VT200")):m===1002?f(m,p(i==="DRAG")):m===1003?f(m,p(i==="ANY")):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(s==="SGR")):m===1015?f(m,4):m===1016?f(m,p(s==="SGR_PIXELS")):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(u===h)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Xl.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,s=0;do{if(r[s+i]=e.params[t+s],e.hasSubParams(t+s)){let l=e.getSubParams(t+s),o=0;do r[1]===5&&(i=1),r[s+o+1+i]=l[o];while(++o=2||r[1]===2&&s+i>=5)break;r[1]&&(i=1)}while(++s+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=nt.fg,e.bg=nt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777216|n-90|8):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777216|n-100|8):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=nt.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=nt.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=nt.fg&16777215,r.bg&=-67108864,r.bg|=nt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${G.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${G.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${G.ESC}[?${t};${n}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=nt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ig(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${G.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Mg&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Mg&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let r=n.shift(),i=n.shift();if(/^\d+$/.exec(r)){let s=parseInt(r);if(zg(s))if(i==="?")t.push({type:0,index:s});else{let l=Rg(i);l&&t.push({type:1,index:s,color:l})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),r,i=n.findIndex(s=>s.startsWith("id="));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let r=0;r=this._specialColors.length);++r,++t)if(n[r]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let i=Rg(n[r]);i&&this._onColor.fire([{type:1,index:this._specialColors[t],color:i}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let r=0;r=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=nt.clone(),this._eraseAttrDataInternal=nt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new bn;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${G.ESC}${l}${G.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-(i.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Ph=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Bg=e,e=t,t=Bg),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Ph=Qe([se(0,Ft)],Ph);function zg(e){return 0<=e&&e<256}var PN=5e7,Fg=12,AN=50,TN=class extends _e{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>PN)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let r=this._writeBuffer[this._bufferOffset],i=this._action(r,t);if(i){let l=o=>performance.now()-n>=Fg?setTimeout(()=>this._innerWrite(0,o)):this._innerWrite(n,o);i.catch(o=>(queueMicrotask(()=>{throw o}),Promise.resolve(!1))).then(l);return}let s=this._callbacks[this._bufferOffset];if(s&&s(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-n>=Fg)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>AN&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Ah=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let o=t.addMarker(t.ybase+t.y),c={data:e,id:this._nextId++,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._dataByLinkId.set(c.id,c),c.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let s=t.addMarker(t.ybase+t.y),l={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(l,s)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(r=>r.line!==t)){let r=this._bufferService.buffer.addMarker(t);n.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(n,r))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Ah=Qe([se(0,Ft)],Ah);var $g=!1,LN=class extends _e{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new gs),this._onBinary=this._register(new ne),this.onBinary=this._onBinary.event,this._onData=this._register(new ne),this.onData=this._onData.event,this._onLineFeed=this._register(new ne),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ne),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ne),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ne),this._instantiationService=new nN,this.optionsService=this._register(new hN(e)),this._instantiationService.setService($t,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Ch)),this._instantiationService.setService(Ft,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(kh)),this._instantiationService.setService(vb,this._logService),this.coreService=this._register(this._instantiationService.createInstance(jh)),this._instantiationService.setService(Ni,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Nh)),this._instantiationService.setService(xb,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(di)),this._instantiationService.setService(J1,this.unicodeService),this._charsetService=this._instantiationService.createInstance(xN),this._instantiationService.setService(Q1,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Ah),this._instantiationService.setService(_b,this._oscLinkService),this._inputHandler=this._register(new EN(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(bt.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(bt.forward(this._bufferService.onResize,this._onResize)),this._register(bt.forward(this.coreService.onData,this._onData)),this._register(bt.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new TN((t,n)=>this._inputHandler.parse(t,n))),this._register(bt.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ne),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!$g&&(this._logService.warn("writeSync is unreliable and will be removed soon."),$g=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Qb),t=Math.max(t,Jb),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Lg.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Lg(this._bufferService),!1))),this._windowsWrappingHeuristics.value=$e(()=>{for(let t of e)t.dispose()})}}},DN={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function RN(e,t,n,r){let i={type:0,cancel:!1,key:void 0},s=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?i.key=G.ESC+"OA":i.key=G.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?i.key=G.ESC+"OD":i.key=G.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?i.key=G.ESC+"OC":i.key=G.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?i.key=G.ESC+"OB":i.key=G.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":G.DEL,e.altKey&&(i.key=G.ESC+i.key);break;case 9:if(e.shiftKey){i.key=G.ESC+"[Z";break}i.key=G.HT,i.cancel=!0;break;case 13:i.key=e.altKey?G.ESC+G.CR:G.CR,i.cancel=!0;break;case 27:i.key=G.ESC,e.altKey&&(i.key=G.ESC+G.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;s?i.key=G.ESC+"[1;"+(s+1)+"D":t?i.key=G.ESC+"OD":i.key=G.ESC+"[D";break;case 39:if(e.metaKey)break;s?i.key=G.ESC+"[1;"+(s+1)+"C":t?i.key=G.ESC+"OC":i.key=G.ESC+"[C";break;case 38:if(e.metaKey)break;s?i.key=G.ESC+"[1;"+(s+1)+"A":t?i.key=G.ESC+"OA":i.key=G.ESC+"[A";break;case 40:if(e.metaKey)break;s?i.key=G.ESC+"[1;"+(s+1)+"B":t?i.key=G.ESC+"OB":i.key=G.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=G.ESC+"[2~");break;case 46:s?i.key=G.ESC+"[3;"+(s+1)+"~":i.key=G.ESC+"[3~";break;case 36:s?i.key=G.ESC+"[1;"+(s+1)+"H":t?i.key=G.ESC+"OH":i.key=G.ESC+"[H";break;case 35:s?i.key=G.ESC+"[1;"+(s+1)+"F":t?i.key=G.ESC+"OF":i.key=G.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=G.ESC+"[5;"+(s+1)+"~":i.key=G.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=G.ESC+"[6;"+(s+1)+"~":i.key=G.ESC+"[6~";break;case 112:s?i.key=G.ESC+"[1;"+(s+1)+"P":i.key=G.ESC+"OP";break;case 113:s?i.key=G.ESC+"[1;"+(s+1)+"Q":i.key=G.ESC+"OQ";break;case 114:s?i.key=G.ESC+"[1;"+(s+1)+"R":i.key=G.ESC+"OR";break;case 115:s?i.key=G.ESC+"[1;"+(s+1)+"S":i.key=G.ESC+"OS";break;case 116:s?i.key=G.ESC+"[15;"+(s+1)+"~":i.key=G.ESC+"[15~";break;case 117:s?i.key=G.ESC+"[17;"+(s+1)+"~":i.key=G.ESC+"[17~";break;case 118:s?i.key=G.ESC+"[18;"+(s+1)+"~":i.key=G.ESC+"[18~";break;case 119:s?i.key=G.ESC+"[19;"+(s+1)+"~":i.key=G.ESC+"[19~";break;case 120:s?i.key=G.ESC+"[20;"+(s+1)+"~":i.key=G.ESC+"[20~";break;case 121:s?i.key=G.ESC+"[21;"+(s+1)+"~":i.key=G.ESC+"[21~";break;case 122:s?i.key=G.ESC+"[23;"+(s+1)+"~":i.key=G.ESC+"[23~";break;case 123:s?i.key=G.ESC+"[24;"+(s+1)+"~":i.key=G.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=G.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=G.DEL:e.keyCode===219?i.key=G.ESC:e.keyCode===220?i.key=G.FS:e.keyCode===221&&(i.key=G.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let l=DN[e.keyCode]?.[e.shiftKey?1:0];if(l)i.key=G.ESC+l;else if(e.keyCode>=65&&e.keyCode<=90){let o=e.ctrlKey?e.keyCode-64:e.keyCode+32,c=String.fromCharCode(o);e.shiftKey&&(c=c.toUpperCase()),i.key=G.ESC+c}else if(e.keyCode===32)i.key=G.ESC+(e.ctrlKey?G.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let o=e.code.slice(3,4);e.shiftKey||(o=o.toLowerCase()),i.key=G.ESC+o,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(i.key=G.US),e.key==="@"&&(i.key=G.NUL));break}return i}var Je=0,MN=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ko,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ko,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((i,s)=>this._getKey(i)-this._getKey(s)),t=0,n=0,r=new Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Je=this._search(t),Je===-1)||this._getKey(this._array[Je])!==t)return!1;do if(this._array[Je]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Je),!0;while(++Jei-s),t=0,n=new Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Je=this._search(e),!(Je<0||Je>=this._array.length)&&this._getKey(this._array[Je])===e))do yield this._array[Je];while(++Je=this._array.length)&&this._getKey(this._array[Je])===e))do t(this._array[Je]);while(++Je=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},_u=0,Wg=0,IN=class extends _e{constructor(){super(),this._decorations=new MN(e=>e?.marker.line),this._onDecorationRegistered=this._register(new ne),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ne),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register($e(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new ON(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),r=t.onDispose(()=>{r.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let s of this._decorations.getKeyIterator(t))r=s.options.x??0,i=r+(s.options.width??1),e>=r&&e{_u=i.options.x??0,Wg=_u+(i.options.width??1),e>=_u&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let i=r-this._lastRefreshMs,s=this._debounceThresholdMS-i;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},s)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Hg=20,Go=class extends _e{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=i.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let s=0;sthis._handleBoundaryFocus(s,0),this._bottomBoundaryFocusListener=s=>this._handleBoundaryFocus(s,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new zN(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(s=>this._handleResize(s.rows))),this._register(this._terminal.onRender(s=>this._refreshRows(s.start,s.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(s=>this._handleChar(s))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(s=>this._handleTab(s))),this._register(this._terminal.onKey(s=>this._handleKey(s.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(pe(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register($e(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Hg+1&&(this._liveRegion.textContent+=Xd.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let s=n.lines.get(n.ydisp+i),l=[],o=s?.translateToString(!0,void 0,void 0,l)||"",c=(n.ydisp+i+1).toString(),u=this._rowElements[i];u&&(o.length===0?(u.textContent=" ",this._rowColumns.set(u,[0,1])):(u.textContent=o,this._rowColumns.set(u,l)),u.setAttribute("aria-posinset",c),u.setAttribute("aria-setsize",r),this._alignRowWidth(u))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],i=n.getAttribute("aria-posinset"),s=t===0?"1":`${this._terminal.buffer.lines.length}`;if(i===s||e.relatedTarget!==r)return;let l,o;if(t===0?(l=n,o=this._rowElements.pop(),this._rowContainer.removeChild(o)):(l=this._rowElements.shift(),o=n,this._rowContainer.removeChild(l)),l.removeEventListener("focus",this._topBoundaryFocusListener),o.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let c=this._createAccessibilityTreeNode();this._rowElements.unshift(c),this._rowContainer.insertAdjacentElement("afterbegin",c)}else{let c=this._createAccessibilityTreeNode();this._rowElements.push(c),this._rowContainer.appendChild(c)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:o,offset:c})=>{let u=o instanceof Text?o.parentNode:o,h=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(h))return console.warn("row is invalid. Race condition?"),null;let d=this._rowColumns.get(u);if(!d)return console.warn("columns is null. Race condition?"),null;let f=c=this._terminal.cols&&(++h,f=0),{row:h,column:f}},s=i(t),l=i(n);if(!(!s||!l)){if(s.row>l.row||s.row===l.row&&s.column>=l.column)throw new Error("invalid range");this._terminal.select(s.column,s.row,(l.row-s.row)*this._terminal.cols-s.column+l.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{wi(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(pe(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(pe(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(pe(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(pe(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let r=0;r{r?.forEach(i=>{i.link.dispose&&i.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,s=>{if(this._isMouseOut)return;let l=s?.map(o=>({link:o}));this._activeProviderReplies?.set(r,l),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:l.link.range.end.x;for(let u=o;u<=c;u++){if(n.has(u)){i.splice(s--,1);break}n.add(u)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let s=0;sthis._linkAtPosition(l.link,t));s&&(n=!0,this._handleNewLink(s))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let s=0;sthis._linkAtPosition(o.link,t));if(l){n=!0,this._handleNewLink(l);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&FN(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,wi(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let r=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=r&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(r,i),this._lastMouseEvent)){let s=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);s&&this._askForLink(s,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Th=Qe([se(1,Qf),se(2,gr),se(3,Ft),se(4,bb)],Th);function FN(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var $N=class extends LN{constructor(e={}){super(e),this._linkifier=this._register(new gs),this.browser=Fb,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new gs),this._onCursorMove=this._register(new ne),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ne),this.onKey=this._onKey.event,this._onRender=this._register(new ne),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ne),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ne),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ne),this.onBell=this._onBell.event,this._onFocus=this._register(new ne),this._onBlur=this._register(new ne),this._onA11yCharEmitter=this._register(new ne),this._onA11yTabEmitter=this._register(new ne),this._onWillOpen=this._register(new ne),this._setup(),this._decorationService=this._instantiationService.createInstance(IN),this._instantiationService.setService(Ql,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Aj),this._instantiationService.setService(bb,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Jd)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(bt.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(bt.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(bt.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(bt.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register($e(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let n,r="";switch(t.index){case 256:n="foreground",r="10";break;case 257:n="background",r="11";break;case 258:n="cursor",r="12";break;default:n="ansi",r="4;"+t.index}switch(t.type){case 0:let i=Be.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${G.ESC}]${r};${jN(i)}${Bb.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(s=>s.ansi[t.index]=rt.toColor(...t.color));else{let s=n;this._themeService.modifyColors(l=>l[s]=rt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Go,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),s=this._renderService.dimensions.css.cell.width*i,l=this.buffer.y*this._renderService.dimensions.css.cell.height,o=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=o+"px",this.textarea.style.top=l+"px",this.textarea.style.width=s+"px",this.textarea.style.height=r+"px",this.textarea.style.lineHeight=r+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(pe(this.element,"copy",t=>{this.hasSelection()&&q1(t,this._selectionService)}));let e=t=>V1(t,this.textarea,this.coreService,this.optionsService);this._register(pe(this.textarea,"paste",e)),this._register(pe(this.element,"paste",e)),$b?this._register(pe(this.element,"mousedown",t=>{t.button===2&&Zm(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(pe(this.element,"contextmenu",t=>{Zm(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),sp&&this._register(pe(this.element,"auxclick",t=>{t.button===1&&hb(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(pe(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(pe(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(pe(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(pe(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(pe(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(pe(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(pe(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(pe(this.screenElement,"mousemove",i=>this.updateCursorStyle(i))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Yd.get()),Ub||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Ej,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(mr,this._coreBrowserService),this._register(pe(this.textarea,"focus",i=>this._handleTextAreaFocus(i))),this._register(pe(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(_h,this._document,this._helperContainer),this._instantiationService.setService(wc,this._charSizeService),this._themeService=this._instantiationService.createInstance(Sh),this._instantiationService.setService(ws,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(qo),this._instantiationService.setService(yb,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(bh,this.rows,this.screenElement)),this._instantiationService.setService(gr,this._renderService),this._register(this._renderService.onRenderedViewportChange(i=>this._onRender.fire(i))),this.onResize(i=>this._renderService.resize(i.cols,i.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(gh,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(yh),this._instantiationService.setService(Qf,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Th,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ph,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(i=>{super.scrollLines(i,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(wh,this.element,this.screenElement,r)),this._instantiationService.setService(eC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(i=>this.scrollLines(i.amount,i.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(i=>this._renderService.handleSelectionChanged(i.start,i.end,i.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(i=>{this.textarea.value=i,this.textarea.focus(),this.textarea.select()})),this._register(bt.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(mh,this.screenElement)),this._register(pe(this.element,"mousedown",i=>this._selectionService.handleMouseDown(i))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Go,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",i=>this._handleScreenReaderModeOptionChange(i))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Uo,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",i=>{!this._overviewRulerRenderer&&i&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Uo,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(vh,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(s){let l=e._mouseService.getMouseReportCoords(s,e.screenElement);if(!l)return!1;let o,c;switch(s.overrideType||s.type){case"mousemove":c=32,s.buttons===void 0?(o=3,s.button!==void 0&&(o=s.button<3?s.button:3)):o=s.buttons&1?0:s.buttons&4?1:s.buttons&2?2:3;break;case"mouseup":c=0,o=s.button<3?s.button:3;break;case"mousedown":c=1,o=s.button<3?s.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(s)===!1)return!1;let u=s.deltaY;if(u===0||e.coreMouseService.consumeWheelEvent(s,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;c=u<0?0:1,o=4;break;default:return!1}return c===void 0||o===void 0||o>4?!1:e.coreMouseService.triggerMouseEvent({col:l.col,row:l.row,x:l.x,y:l.y,button:o,action:c,ctrl:s.ctrlKey,alt:s.altKey,shift:s.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:s=>(n(s),s.buttons||(this._document.removeEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.removeEventListener("mousemove",r.mousedrag)),this.cancel(s)),wheel:s=>(n(s),this.cancel(s,!0)),mousedrag:s=>{s.buttons&&n(s)},mousemove:s=>{s.buttons||n(s)}};this._register(this.coreMouseService.onProtocolChange(s=>{s?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(s)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),s&8?r.mousemove||(t.addEventListener("mousemove",i.mousemove),r.mousemove=i.mousemove):(t.removeEventListener("mousemove",r.mousemove),r.mousemove=null),s&16?r.wheel||(t.addEventListener("wheel",i.wheel,{passive:!1}),r.wheel=i.wheel):(t.removeEventListener("wheel",r.wheel),r.wheel=null),s&2?r.mouseup||(r.mouseup=i.mouseup):(this._document.removeEventListener("mouseup",r.mouseup),r.mouseup=null),s&4?r.mousedrag||(r.mousedrag=i.mousedrag):(this._document.removeEventListener("mousemove",r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(pe(t,"mousedown",s=>{if(s.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(s)))return n(s),r.mouseup&&this._document.addEventListener("mouseup",r.mouseup),r.mousedrag&&this._document.addEventListener("mousemove",r.mousedrag),this.cancel(s)})),this._register(pe(t,"wheel",s=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(s)===!1)return!1;if(!this.buffer.hasScrollback){if(s.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(s,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(s,!0);let l=G.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(s.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(l,!0),this.cancel(s,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){db(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=RN(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let r=this.rows-1;return this.scrollLines(n.type===2?-r:r),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===G.ETX||n.key===G.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(WN(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new bn)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Ug=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new UN(t)}getNullCell(){return new bn}},qN=class extends _e{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ne),this.onBufferChange=this._onBufferChange.event,this._normal=new Ug(this._core.buffers.normal,"normal"),this._alternate=new Ug(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},VN=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,r)=>t(n,r.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},KN=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},GN=["cols","rows"],On=0,YN=class extends _e{constructor(e){super(),this._core=this._register(new $N(e)),this._addonManager=this._register(new HN),this._publicOptions={...this._core.options};let t=r=>this._core.options[r],n=(r,i)=>{this._checkReadonlyOptions(r),this._core.options[r]=i};for(let r in this._core.options){let i={get:t.bind(this,r),set:n.bind(this,r)};Object.defineProperty(this._publicOptions,r,i)}}_checkReadonlyOptions(e){if(GN.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new VN(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new KN(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new qN(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Yd.get()},set promptLabel(e){Yd.set(e)},get tooMuchOutput(){return Xd.get()},set tooMuchOutput(e){Xd.set(e)}}}_verifyIntegers(...e){for(On of e)if(On===1/0||isNaN(On)||On%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(On of e)if(On&&(On===1/0||isNaN(On)||On%1!==0||On<0))throw new Error("This API only accepts positive integers")}};/** - * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. - * @license MIT - * - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * @license MIT - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - */var XN=2,QN=1,JN=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),i=Math.max(0,parseInt(n.getPropertyValue("width"))),s=window.getComputedStyle(this._terminal.element),l={top:parseInt(s.getPropertyValue("padding-top")),bottom:parseInt(s.getPropertyValue("padding-bottom")),right:parseInt(s.getPropertyValue("padding-right")),left:parseInt(s.getPropertyValue("padding-left"))},o=l.top+l.bottom,c=l.right+l.left,u=r-o,h=i-c-t;return{cols:Math.max(XN,Math.floor(h/e.css.cell.width)),rows:Math.max(QN,Math.floor(u/e.css.cell.height))}}};function jt(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}function Hs(e,t,n,r,i){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Zr,fn,Di,Aa;const qg="__TAURI_TO_IPC_KEY__";function ew(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}class Wl{constructor(t){Zr.set(this,void 0),fn.set(this,0),Di.set(this,[]),Aa.set(this,void 0),Hs(this,Zr,t||(()=>{})),this.id=ew(n=>{const r=n.index;if("end"in n){r==jt(this,fn,"f")?this.cleanupCallback():Hs(this,Aa,r);return}const i=n.message;if(r==jt(this,fn,"f")){for(jt(this,Zr,"f").call(this,i),Hs(this,fn,jt(this,fn,"f")+1);jt(this,fn,"f")in jt(this,Di,"f");){const s=jt(this,Di,"f")[jt(this,fn,"f")];jt(this,Zr,"f").call(this,s),delete jt(this,Di,"f")[jt(this,fn,"f")],Hs(this,fn,jt(this,fn,"f")+1)}jt(this,fn,"f")===jt(this,Aa,"f")&&this.cleanupCallback()}else jt(this,Di,"f")[r]=i})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(t){Hs(this,Zr,t)}get onmessage(){return jt(this,Zr,"f")}[(Zr=new WeakMap,fn=new WeakMap,Di=new WeakMap,Aa=new WeakMap,qg)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[qg]()}}async function $(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}var Vg;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_SUSPENDED="tauri://suspended",e.WINDOW_RESUMED="tauri://resumed",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"})(Vg||(Vg={}));async function ZN(e,t){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,t),await $("plugin:event|unlisten",{event:e,eventId:t})}async function Yo(e,t,n){var r;const i=(r=void 0)!==null&&r!==void 0?r:{kind:"Any"};return $("plugin:event|listen",{event:e,target:i,handler:ew(t)}).then(s=>async()=>ZN(e,s))}async function Kg(e={}){return typeof e=="object"&&Object.freeze(e),await $("plugin:dialog|open",{options:e})}const eE="domain://event",tE="app-exit-work-guard";class nE{async health(t){return $("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await Yo(eE,r=>{t(r.payload)})}async pickFolder(){const t=await Kg({directory:!0,multiple:!1});return t==null?null:typeof t=="string"?t:null}async pickArchiveFile(){const t=await Kg({directory:!1,multiple:!1,filters:[{name:"Plugin archive",extensions:["ideaplug","zip","vsix"]}]});return typeof t=="string"?t:null}async onAppExitWorkGuard(t){return await Yo(tE,r=>{t(r.payload)})}async confirmAppExit(){await $("confirm_app_exit")}}function Xo(e,t){let n=Promise.resolve();return{sessionId:e,write(r){const i=n.then(async()=>{Gg("start",e,r),await $("write_terminal",{request:{sessionId:e,data:Array.from(r)}}),Gg("ok",e,r)});return n=i.catch(()=>{}),i},async resize(r,i){await $("resize_terminal",{request:{sessionId:e,rows:r,cols:i}})},detach(){t.onmessage=()=>{}},async close(){await $("close_terminal",{sessionId:e})}}}function Gg(e,t,n){n.length===1&&n[0]>=32&&n[0]!==127||console.info("[terminal-write]",e,{sessionId:t,bytes:n.length,control:rE(n)})}function rE(e){return e.length===0?"":e.length>16?"":Array.from(e).map(t=>{switch(t){case 13:return"\\r";case 10:return"\\n";case 127:return"\\x7f";default:return t<32?`\\x${t.toString(16).padStart(2,"0")}`:String.fromCharCode(t)}}).join("")}class iE{async openTerminal(t,n){const r=new Wl;r.onmessage=s=>n(Uint8Array.from(s));const i=await $("open_terminal",{request:{cwd:t.cwd,rows:t.rows,cols:t.cols},onOutput:r});return Xo(i.sessionId,r)}async reattach(t,n){const r=new Wl;r.onmessage=s=>n(Uint8Array.from(s));const i=await $("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Xo(i.sessionId,r),scrollback:Uint8Array.from(i.scrollback)}}async closeTerminal(t){await $("close_terminal",{sessionId:t})}}class sE{listAgents(t){return $("list_agents",{projectId:t})}listLiveAgents(t){return $("list_live_agents",{projectId:t})}listResumableAgents(t){return $("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return $("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return $("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return $("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,i,s){return $("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:i,cols:s}})}readContext(t,n){return $("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await $("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await $("delete_agent",{projectId:t,agentId:n})}async launchAgent(t,n,r,i){const s=new Wl;s.onmessage=c=>i(Uint8Array.from(c));const l=await $("launch_agent",{request:{projectId:t,agentId:n,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,nodeId:r.nodeId??null},onOutput:s});return{...Xo(l.sessionId,s),...l.assignedConversationId?{assignedConversationId:l.assignedConversationId}:{}}}async reattach(t,n){const r=new Wl;r.onmessage=s=>n(Uint8Array.from(s));const i=await $("reattach_terminal",{sessionId:t,onOutput:r});return{handle:Xo(i.sessionId,r),scrollback:Uint8Array.from(i.scrollback)}}inspectConversation(t,n,r){return $("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}}class lE{async interrupt(t,n){await $("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){console.info("[input-gateway] delegationDelivered:start",{projectId:t,agentId:n,ticket:r}),await $("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}}),console.info("[input-gateway] delegationDelivered:ok",{projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){console.info("[input-gateway] setFrontAttached:start",{agentId:t,attached:n}),await $("set_front_attached",{request:{agentId:t,attached:n}}),console.info("[input-gateway] setFrontAttached:ok",{agentId:t,attached:n})}async cancelResume(t){return $("cancel_resume",{agentId:t})}async setResumeAt(t,n){await $("set_resume_at",{agentId:t,resetsAtMs:n})}}class aE{listProjects(){return $("list_projects")}createProject(t,n){return $("create_project",{request:{name:t,root:n}})}openProject(t){return $("open_project",{projectId:t})}async closeProject(t){await $("close_project",{projectId:t})}readProjectContext(t){return $("read_project_context",{projectId:t})}async updateProjectContext(t,n){await $("update_project_context",{request:{projectId:t,content:n}})}}class oE{loadLayout(t,n){return $("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return $("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return $("list_layouts",{projectId:t})}createLayout(t,n,r){return $("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return $("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return $("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return $("set_active_layout",{request:{projectId:t,layoutId:n}})}}class cE{firstRunState(){return $("first_run_state")}referenceProfiles(){return $("reference_profiles")}detectProfiles(t){return $("detect_profiles",{request:{candidates:t}})}listProfiles(){return $("list_profiles")}saveProfile(t){return $("save_profile",{request:{profile:t}})}async deleteProfile(t){await $("delete_profile",{profileId:t})}configureProfiles(t){return $("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return $("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return $("list_opencode_providers")}saveOpenCodeProviderProfile(t){return $("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class uE{listModelServers(){return $("list_model_servers")}saveModelServer(t){return $("save_model_server",{request:{config:t}})}async deleteModelServer(t){await $("delete_model_server",{serverId:t})}previewModelServerCommand(t){return $("preview_model_server_command",{config:t})}}const dE=2e3;class hE{constructor(t=dE){this.pollMs=t}getExposureSettings(){return $("get_server_exposure_settings")}async saveExposureSettings(t){await $("save_server_exposure_settings",{settings:t})}previewExposure(t){return $("preview_server_exposure_settings",{settings:t})}status(){return $("embedded_server_status")}start(){return $("embedded_server_start")}stop(){return $("embedded_server_stop")}async onStatusChanged(t){let n=!1;const r=setInterval(()=>{this.status().then(i=>{n||t(i)},()=>{})},this.pollMs);return()=>{n=!0,clearInterval(r)}}}class fE{listTemplates(){return $("list_templates")}createTemplate(t){return $("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return $("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await $("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return $("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return $("detect_agent_drift",{projectId:t})}syncAgent(t,n){return $("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class pE{listSkills(t,n){return $("list_skills",{projectId:t,scope:n})}createSkill(t){return $("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,i){return $("update_skill",{request:{projectId:t,scope:n,skillId:r,content:i}})}async deleteSkill(t,n,r){await $("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,i){await $("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:i}})}async unassignSkill(t,n,r){await $("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class mE{listMemories(t){return $("list_memories",{projectId:t})}getMemory(t,n){return $("get_memory",{projectId:t,slug:n})}createMemory(t){return $("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,i,s){return $("update_memory",{request:{projectId:t,slug:n,description:r,type:i,content:s}})}async deleteMemory(t,n){await $("delete_memory",{projectId:t,slug:n})}readIndex(t){return $("read_memory_index",{projectId:t})}resolveLinks(t,n){return $("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return $("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class gE{listEmbedderProfiles(){return $("list_embedder_profiles")}saveEmbedderProfile(t){return $("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await $("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return $("describe_embedder_engines")}}class xE{async listDevices(){return(await $("list_devices")).devices}createPairingCode(){return $("create_pairing_code")}renameDevice(t,n){return $("rename_device",{request:{deviceId:t,name:n}})}revokeDevice(t){return $("revoke_device",{request:{deviceId:t}})}revokeAllDevices(){return $("revoke_all_devices")}}class vE{status(t){return $("git_status",{projectId:t})}async stage(t,n){await $("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await $("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return $("git_commit",{request:{projectId:t,message:n}})}branches(t){return $("git_branches",{projectId:t})}async checkout(t,n){await $("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return $("git_log",{projectId:t,limit:n})}async init(t){await $("git_init",{projectId:t})}graph(t,n){return $("git_graph",{projectId:t,limit:n})}}class _E{getProjectPermissions(t){return $("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return $("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return $("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return $("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return $("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return $("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return $("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}function Ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xe(e,t=""){return typeof e=="string"?e:t}function Yn(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function yE(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function mi(e){return Array.isArray(e)?e:[]}function Yg(e){return typeof e=="string"?e:void 0}function os(e){return typeof e=="string"?e:null}function tw(e){return Ln(e)?e.kind==="agent"?{kind:"agent",agentId:Xe(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function bE(e){return e==="inProgress"?"inProgress":"queued"}function wE(e){return Ln(e)&&e.state==="busy"?{state:"busy",ticket:Xe(e.ticket,"unknown"),sinceMs:Yn(e.sinceMs,0)}:{state:"idle"}}function SE(e,t){const n=Ln(e)?e:{},r=Xe(n.taskPreview);return{ticketId:Xe(n.ticketId,`legacy-ticket-${t}`),conversationId:Xe(n.conversationId),position:Yn(n.position,t),status:bE(n.status),source:tw(n.source),requesterLabel:Xe(n.requesterLabel),taskPreview:r,taskLen:Yn(n.taskLen,r.length)}}function kE(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="completed"||t==="success"||t==="succeeded"?"completed":t==="failed"||t==="failure"?"failed":t==="cancelled"||t==="canceled"||t==="expired"?"cancelled":t==="running"||t==="started"?"running":t==="delivered"?"delivered":"pending"}function CE(e,t,n){const r=Ln(e)?e:{};return{taskId:Xe(r.taskId,`legacy-task-${t}`),ownerAgentId:Xe(r.ownerAgentId,n),projectId:Xe(r.projectId),kind:Xe(r.kind,"background"),status:kE(r.status??r.state),exitCode:yE(r.exitCode),summary:os(r.summary),stdoutTail:os(r.stdoutTail),stderrTail:os(r.stderrTail),updatedAtMs:Yn(r.updatedAtMs)}}function nw(e,t,n){const r=Ln(e)?e:{};return{id:Xe(r.id,`legacy-inbox-${t}`),agentId:Xe(r.agentId??r.agent_id,n),source:Xe(r.source,"unknown"),kind:Xe(r.kind,"message"),body:Xe(r.body),createdAtMs:Yn(r.createdAtMs??r.created_at_ms,0),...Yg(r.correlationId??r.correlation_id)?{correlationId:Yg(r.correlationId??r.correlation_id)}:{},priority:Yn(r.priority,0)}}function jE(e,t){const n=Ln(e)?e:{},r=Ln(n.live)&&n.live.kind==="structured"?"structured":"pty",i=Ln(n.live)?{nodeId:Xe(n.live.nodeId),sessionId:Xe(n.live.sessionId),kind:r}:void 0,s=Xe(n.agentId,`legacy-agent-${t}`),l=mi(n.inbox).map((c,u)=>nw(c,u,s)),o=mi(n.backgroundTasks??n.backgroundCompletions).map((c,u)=>CE(c,u,s));return{agentId:s,name:Xe(n.name,"Unnamed agent"),profileId:Xe(n.profileId,"unknown"),...i?{live:i}:{},busy:wE(n.busy),tickets:mi(n.tickets).map(SE),inboxDepth:Yn(n.inboxDepth,l.length),inbox:l,backgroundTasks:o}}function NE(e){return e==="ready"||e==="partial"||e==="unavailable"||e==="missing"?e:"missing"}function EE(e,t){const n=Ln(e)?e:{},r=Xe(n.textPreview);return{role:n.role==="response"||n.role==="toolActivity"?n.role:"prompt",source:tw(n.source),atMs:Yn(n.atMs,t),textPreview:r,textLen:Yn(n.textLen,r.length)}}function PE(e,t){const n=Ln(e)?e:{};return{conversationId:Xe(n.conversationId,`legacy-conversation-${t}`),status:NE(n.status),objectivePreview:os(n.objectivePreview),summaryPreview:os(n.summaryPreview),summaryLen:Yn(n.summaryLen,0),upTo:os(n.upTo),recentTurns:mi(n.recentTurns).map(EE)}}function lp(e){const t=Ln(e)?e:{},n=mi(t.agents).map(jE),r=mi(t.inboxItems).map((i,s)=>nw(i,s,""));for(const i of r){const s=n.find(l=>l.agentId===i.agentId);s&&(s.inbox??=[],s.inboxDepth??=0,s.inbox.some(l=>l.id===i.id)||(s.inbox.push(i),s.inboxDepth=Math.max(s.inboxDepth,s.inbox.length)))}return{agents:n,conversations:mi(t.conversations).map(PE)}}class AE{async getProjectWorkState(t){const n=await $("get_project_work_state",{projectId:t});return lp(n)}async cancelBackgroundTask(t){await $("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await $("retry_background_task",{taskId:t})}}function ap(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lh(e,t=""){return typeof e=="string"?e:t}function Xg(e,t=0){return typeof e=="number"&&Number.isFinite(e)?e:t}function TE(e){return Array.isArray(e)?e:[]}function LE(e){return ap(e)?e.kind==="agent"?{kind:"agent",agentId:Lh(e.agentId,"unknown")}:{kind:"human"}:{kind:"human"}}function DE(e){return e==="response"||e==="toolActivity"?e:"prompt"}function RE(e,t){const n=ap(e)?e:{},r=Lh(n.text);return{id:Lh(n.id,`turn-${t}`),atMs:Xg(n.atMs,t),role:DE(n.role),source:LE(n.source),text:r,textLen:Xg(n.textLen,r.length)}}function rw(e){const t=ap(e)?e:{},n=t.nextAnchor;return{turns:TE(t.turns).map(RE),hasMore:t.hasMore===!0,...typeof n=="string"?{nextAnchor:n}:{}}}class ME{async readPage(t,n,r){const i=await $("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return rw(i)}}class IE{async create(t,n){return $("ticket_create",{request:{projectId:t,...n}})}async read(t,n,r=!1){return $("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}async list(t,n){const{statuses:r,priorities:i,...s}=n??{};return $("ticket_list",{request:{projectId:t,statuses:r??[],priorities:i??[],...s}})}async update(t,n,r){return $("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await $("ticket_delete",{request:{projectId:t,ref:n}})}async readCarnet(t,n){return $("ticket_read_carnet",{request:{projectId:t,ref:n}})}async updateCarnet(t,n,r,i){return $("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:i}})}async link(t,n,r,i,s){return $("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:i,expectedVersion:s}})}async unlink(t,n,r,i,s){return $("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:i,kind:s}})}async assign(t,n,r,i,s){return $("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:i,expectedVersion:s}})}async listSprints(t){return(await $("sprint_list",{request:{projectId:t}})).items}async setTicketSprint(t,n,r,i){return r===null?$("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:i}}):$("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:i}})}async createSprint(t,n){return $("sprint_create",{request:{projectId:t,name:n}})}async renameSprint(t,n,r,i){return $("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:i}})}async reorderSprints(t,n){return(await $("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await $("sprint_delete",{request:{projectId:t,sprintId:n}})}async openTicketChat(t,n,r){return $("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await $("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const i=new Wl;i.onmessage=s=>r(s),await $("agent_send",{sessionId:t,prompt:n,onReply:i})}}const OE="view-window://lifecycle";class BE{async openViewWindow(t){await $("open_view_window",{panel:t})}async closeViewWindow(t){await $("close_view_window",{panel:t})}async listOpenViewWindows(){return $("list_open_view_windows")}async onViewWindowClosed(t){return await Yo(OE,r=>{r.payload.kind==="closed"&&t({panel:r.payload.panel})})}}const zE="focused-project://changed";class FE{async setFocusedProject(t){await $("set_focused_project",{project:t})}async getFocusedProject(){return await $("get_focused_project")??null}async onFocusedProjectChanged(t){return await Yo(zE,r=>t(r.payload.project??null))}}function yu(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}class iw{read(t){const n=yu();if(!n)return null;let r;try{r=n.getItem(t)}catch{return null}if(r===null)return null;try{return JSON.parse(r)}catch{try{n.removeItem(t)}catch{}return null}}write(t,n){const r=yu();if(r)try{r.setItem(t,JSON.stringify(n))}catch{}}remove(t){const n=yu();if(n)try{n.removeItem(t)}catch{}}}class $E{listPlugins(){return $("plugin_list_plugins")}reviewPackage(t){return $("plugin_review_package",{request:{sourceKind:t.sourceKind,path:t.path}})}installFromArchive(t){return $("plugin_install_from_archive",{path:t})}installFromDirectory(t){return $("plugin_install_from_directory",{path:t})}setEnabled(t,n){return $("plugin_set_enabled",{pluginId:t,enabled:n})}uninstall(t){return $("plugin_uninstall",{pluginId:t})}listRuntimeContributions(){return $("plugin_list_runtime_contributions")}async openPluginsFolder(t){await $("plugin_open_plugins_folder",{pluginId:t??null})}}function WE(e){throw{code:"NOT_IMPLEMENTED",message:`${e} is not implemented yet (pending its lot).`}}class HE{connect(){return WE("RemoteGateway.connect")}}function UE(){return{system:new nE,agent:new sE,input:new lE,terminal:new iE,project:new aE,layout:new oE,git:new vE,remote:new HE,profile:new cE,modelServer:new uE,desktopServer:new hE,template:new fE,skill:new pE,memory:new mE,embedder:new gE,device:new xE,permission:new _E,workState:new AE,conversation:new ME,ticket:new IE,window:new BE,focusedProject:new FE,uiPreferences:new iw,plugin:new $E}}function Dh(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Ta(e=Dh()){return{root:{type:"leaf",node:{id:e,session:null}}}}function Rh(e){if(e.length===0)return[];const t=1e-6,n=e.map(i=>Number.isFinite(i)&&i>0?i:t),r=n.reduce((i,s)=>i+s,0);if(r<=0){const i=100/n.length;return n.map(()=>i)}return n.map(i=>i/r*100)}function Qg(e,t,n){const r=[...e];if(t<0||t+1>=r.length)return r;const i=r.reduce((u,h)=>u+h,0),s=n*i,l=i*.05,o=r[t]+s,c=r[t+1]-s;return o({node:Ut(r.node,t),weight:r.weight}))}};break;case"grid":n={type:"grid",node:{...e.node,cells:e.node.cells.map(r=>({...r,node:Ut(r.node,t)}))}};break}return t(n)}function Jg(e,t){let n;return Ut(e,r=>(r.type==="leaf"&&r.node.id===t&&(n=r.node.session??null),r)),n}function qE(e,t){switch(t.type){case"split":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const s={id:t.newLeaf,session:null};return{type:"split",node:{id:t.container,direction:t.direction,children:[{node:i,weight:1},{node:{type:"leaf",node:s},weight:1}]}}}return i});if(!n)throw er(t.target);return{root:r}}case"merge":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="split"&&i.node.id===t.container){const s=i.node.children[t.keepIndex];if(!s)throw La(`merge keepIndex ${t.keepIndex} out of range`);return n=!0,s.node}return i});if(!n)throw er(t.container);return{root:r}}case"resize":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="split"&&i.node.id===t.container){if(i.node.children.length!==t.weights.length)throw La("resize weight count mismatch");n=!0;const s=i.node.children.map((l,o)=>({node:l.node,weight:t.weights[o]}));return{type:"split",node:{...i.node,children:s}}}return i});if(!n)throw er(t.container);return{root:r}}case"move":{const n=Jg(e.root,t.from);if(n===void 0)throw er(t.from);if(n===null)throw La("source cell has no session");const r=Jg(e.root,t.to);if(r===void 0)throw er(t.to);if(r!==null)throw La("target cell is occupied");return{root:Ut(e.root,s=>s.type==="leaf"&&s.node.id===t.from?{type:"leaf",node:{...s.node,session:null}}:s.type==="leaf"&&s.node.id===t.to?{type:"leaf",node:{...s.node,session:n}}:s)}}case"setSession":{let n=!1;const r=Ut(e.root,i=>i.type==="leaf"&&i.node.id===t.target?(n=!0,{type:"leaf",node:{...i.node,session:t.session??null}}):i);if(!n)throw er(t.target);return{root:r}}case"setCellAgent":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const{agent:s,...l}=i.node;return{type:"leaf",node:t.agent!==null?{...l,agent:t.agent}:l}}return i});if(!n)throw er(t.target);return{root:r}}case"setCellConversation":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const{conversationId:s,...l}=i.node;return{type:"leaf",node:t.conversationId!==null?{...l,conversationId:t.conversationId}:l}}return i});if(!n)throw er(t.target);return{root:r}}case"setAgentRunning":{let n=!1;const r=Ut(e.root,i=>{if(i.type==="leaf"&&i.node.id===t.target){n=!0;const{agentWasRunning:s,...l}=i.node;return{type:"leaf",node:t.running?{...l,agentWasRunning:!0}:l}}return i});if(!n)throw er(t.target);return{root:r}}}}function Qo(e){const t=[];return Ut(e.root,n=>(n.type==="leaf"&&t.push(n.node),n)),t}function VE(e,t,n){return{root:Ut(e.root,r=>r.type==="customPluginLayout"&&r.node.id===t?{type:"customPluginLayout",node:{...r.node,state:n}}:r)}}function KE(e,t){return{root:Ut(e.root,n=>n.type==="customPluginLayout"&&n.node.id===t?{type:"leaf",node:{id:t}}:n)}}function GE(e,t){return{type:"split",target:e,direction:t,newLeaf:Dh(),container:Dh()}}function er(e){return{code:"NOT_FOUND",message:`layout node ${e} not found`}}function La(e){return{code:"INVALID",message:e}}const Zg={low:0,medium:1,high:2,critical:3},ex={open:0,inProgress:1,QA:2,closed:3};function YE(e,t){return e.sort((n,r)=>{let i=0;return t.field==="number"?i=n.number-r.number:t.field==="priority"?i=Zg[n.priority]-Zg[r.priority]:t.field==="status"?i=ex[n.status]-ex[r.status]:i=n.title.localeCompare(r.title,void 0,{sensitivity:"base"})||n.title.localeCompare(r.title),(t.direction==="desc"?-i:i)||n.number-r.number})}class XE{constructor(){X(this,"listeners",new Set);X(this,"exitGuardListeners",new Set);X(this,"confirmAppExitCallCount",0)}async health(t){const n={version:"0.1.0-mock",alive:!0,timeMillis:Date.now(),correlationId:`mock-${Math.random().toString(36).slice(2,10)}`,note:t??null};return this.emit({type:"projectCreated",projectId:n.correlationId}),n}async onDomainEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(t){for(const n of this.listeners)n(t)}async pickFolder(){return"/home/user/mock-project"}async pickArchiveFile(){return"/home/user/mock-plugin.ideaplug"}async onAppExitWorkGuard(t){return this.exitGuardListeners.add(t),()=>{this.exitGuardListeners.delete(t)}}emitAppExitWorkGuard(t){for(const n of this.exitGuardListeners)n(t)}async confirmAppExit(){this.confirmAppExitCallCount+=1}}function op(e){let t="",n=!1;for(const r of e.trim())/[a-zA-Z0-9]/.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="-",n=!0);return t.replace(/^-+|-+$/g,"")}class Mh{constructor(t,n){X(this,"scrollback",[]);X(this,"sink",null);X(this,"closed",!1);this.sessionId=t,this.sink=n}emit(t){if(!this.closed){for(const n of t)this.scrollback.push(n);this.sink?.(t)}}detach(){this.sink=null}reattach(t){return this.sink=t,Uint8Array.from(this.scrollback)}}class QE{constructor(){X(this,"agents",new Map);X(this,"contexts",new Map);X(this,"sessionSeq",0);X(this,"sessions",new Map);X(this,"liveByAgent",new Map);X(this,"liveSessionByAgent",new Map);X(this,"resumable",new Map);X(this,"conversationDetails",new Map)}getAgents(t){return this.agents.has(t)||this.agents.set(t,[]),this.agents.get(t)}contextKey(t,n){return`${t}::${n}`}async listAgents(t){return structuredClone(this.getAgents(t))}async listLiveAgents(t){const n=new Set(this.getAgents(t).map(r=>r.id));return[...this.liveByAgent.entries()].filter(([r])=>n.has(r)).map(([r,i])=>({agentId:r,nodeId:i,sessionId:this.liveSessionByAgent.get(r),kind:"pty"}))}_setResumableAgents(t,n){this.resumable.set(t,n)}async listResumableAgents(t){return structuredClone(this.resumable.get(t)??[])}async attachLiveAgent(t,n,r){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const s=this.liveSessionByAgent.get(n);if(!s||!this.sessions.has(s))throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};return this.liveByAgent.set(n,r),{agentId:n,nodeId:r,sessionId:s,kind:"pty"}}async stopLiveAgent(t,n){if(!this.getAgents(t).some(l=>l.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const i=this.liveSessionByAgent.get(n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} has no live session`};const s=this.sessions.get(i);return s&&(s.closed=!0),this.sessions.delete(i),this.liveSessionByAgent.delete(n),this.liveByAgent.delete(n),{agentId:n,sessionId:i,kind:"pty"}}async createAgent(t,n){const r=this.getAgents(t),i=op(n.name)||"agent",s=new Set(r.map(u=>u.contextPath));let l=`agents/${i}.md`,o=2;for(;s.has(l);)l=`agents/${i}-${o}.md`,o+=1;const c={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:n.name,contextPath:l,profileId:n.profileId,origin:{type:"scratch"},synchronized:!1,skills:[]};return r.push(c),this.contexts.set(this.contextKey(t,c.id),n.initialContent??""),structuredClone(c)}async readContext(t,n){if(!this.getAgents(t).some(i=>i.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};return this.contexts.get(this.contextKey(t,n))??""}async updateContext(t,n,r){if(!this.getAgents(t).some(s=>s.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.contexts.set(this.contextKey(t,n),r)}async deleteAgent(t,n){const r=this.getAgents(t),i=r.findIndex(s=>s.id===n);if(i===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};r.splice(i,1),this.contexts.delete(this.contextKey(t,n))}async changeAgentProfile(t,n,r,i,s){const l=this.getAgents(t),o=l.findIndex(m=>m.id===n);if(o===-1)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};l[o]={...l[o],profileId:r};const c=structuredClone(l[o]),u=this.liveByAgent.get(n),h=this.liveSessionByAgent.get(n);if(!u||!h)return{agent:c};const d=this.sessions.get(h);d&&(d.closed=!0),this.sessions.delete(h),this.sessionSeq+=1;const f=`mock-agent-session-${this.sessionSeq}`,p=new Mh(f,()=>{});return p.detach(),this.sessions.set(f,p),this.liveSessionByAgent.set(n,f),this.liveByAgent.set(n,u),{agent:c,relaunchedSession:{sessionId:f,cwd:"/home/user/mock-project",rows:i,cols:s}}}_insertAgent(t,n,r){this.getAgents(t).push(n),this.contexts.set(this.contextKey(t,n.id),r)}_updateAgent(t,n,r,i){const s=this.getAgents(t),l=s.findIndex(o=>o.id===n);l!==-1&&(s[l]={...s[l],...r},i!==void 0&&this.contexts.set(this.contextKey(t,n),i))}_rawAgents(t){return this.getAgents(t)}_setSkills(t,n,r){const i=this.getAgents(t),s=i.findIndex(l=>l.id===n);s!==-1&&(i[s]={...i[s],skills:r})}async launchAgent(t,n,r,i){if(!this.getAgents(t).some(p=>p.id===n))throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};const l=this.liveByAgent.get(n);if(l!==void 0&&r.nodeId&&l!==r.nodeId)throw{code:"AGENT_ALREADY_RUNNING",message:`agent ${n} is already running in cell ${l}`};this.sessionSeq+=1;const o=`mock-agent-session-${this.sessionSeq}`,c=r.cwd;r.nodeId&&(this.liveByAgent.set(n,r.nodeId),this.liveSessionByAgent.set(n,o));const u=()=>{this.liveByAgent.get(n)===r.nodeId&&(this.liveByAgent.delete(n),this.liveSessionByAgent.delete(n))},h=new TextEncoder,d=new Mh(o,i);this.sessions.set(o,d),queueMicrotask(()=>d.emit(h.encode(`agent ${n} @ ${c}\r -`)));const f=Jo(d,()=>{this.sessions.delete(o),u()});return r.conversationId?f:{...f,assignedConversationId:`mock-conversation-${o}`}}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`agent session ${t} is not alive`};const i=r.reattach(n);return{handle:Jo(r,()=>{this.sessions.delete(t);for(const[s,l]of this.liveSessionByAgent)l===t&&(this.liveSessionByAgent.delete(s),this.liveByAgent.delete(s))}),scrollback:i}}_setConversationDetails(t,n){this.conversationDetails.set(t,n)}async inspectConversation(t,n,r){return structuredClone(this.conversationDetails.get(r)??{})}}function Jo(e,t){return{sessionId:e.sessionId,async write(n){if(e.closed)return;const r=[];for(const i of n)i===13?r.push(13,10):r.push(i);e.emit(Uint8Array.from(r))},async resize(){},detach(){e.detach()},async close(){e.closed=!0,t()}}}class JE{constructor(){X(this,"seq",0);X(this,"sessions",new Map)}async openTerminal(t,n){this.seq+=1;const r=`mock-session-${this.seq}`,i=new TextEncoder,s=new Mh(r,n);return this.sessions.set(r,s),queueMicrotask(()=>s.emit(i.encode(`mock terminal @ ${t.cwd}\r -`))),Jo(s,()=>this.sessions.delete(r))}async reattach(t,n){const r=this.sessions.get(t);if(!r||r.closed)throw{code:"NOT_FOUND",message:`terminal session ${t} is not alive`};const i=r.reattach(n);return{handle:Jo(r,()=>this.sessions.delete(t)),scrollback:i}}async closeTerminal(t){const n=this.sessions.get(t);n&&(n.closed=!0,this.sessions.delete(t))}}class ZE{constructor(){X(this,"projects",[]);X(this,"contexts",new Map)}async listProjects(){return[...this.projects]}async createProject(t,n){if(this.projects.some(i=>i.root===n))throw{code:"INVALID",message:`a project already exists at ${n} for this remote`};const r={id:`mock-project-${Math.random().toString(36).slice(2,10)}`,name:t,root:n,remote:{kind:"local"},createdAt:Date.now()};return this.projects.push(r),r}async openProject(t){const n=this.projects.find(r=>r.id===t);if(!n)throw{code:"NOT_FOUND",message:`project ${t} not found`};return n}async closeProject(){}async readProjectContext(t){if(!this.projects.some(n=>n.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};return this.contexts.get(t)??""}async updateProjectContext(t,n){if(!this.projects.some(r=>r.id===t))throw{code:"NOT_FOUND",message:`project ${t} not found`};this.contexts.set(t,n)}}class e2{constructor(){X(this,"store",new Map)}getProjectLayouts(t){if(!this.store.has(t)){const n=`layout-default-${Math.random().toString(36).slice(2,8)}`;this.store.set(t,{activeId:n,layouts:[{id:n,name:"Default",kind:"terminal",tree:Ta()}]})}return this.store.get(t)}getActiveTree(t){const n=this.getProjectLayouts(t),r=n.layouts.find(i=>i.id===n.activeId);return r?r.tree:Ta()}getTree(t,n){if(!n)return this.getActiveTree(t);const i=this.getProjectLayouts(t).layouts.find(s=>s.id===n);return i?i.tree:Ta()}setTree(t,n,r){const i=this.getProjectLayouts(t),s=r??i.activeId,l=i.layouts.find(o=>o.id===s);l&&(l.tree=n)}async loadLayout(t,n){const r=this.getTree(t,n);return structuredClone(r)}async mutateLayout(t,n,r){const i=this.getTree(t,r),s=qE(i,n);return this.setTree(t,s,r),structuredClone(s)}async listLayouts(t){const n=this.getProjectLayouts(t);return{layouts:n.layouts.map(i=>({id:i.id,name:i.name,kind:i.kind})),activeId:n.activeId}}async createLayout(t,n,r="terminal"){const i=this.getProjectLayouts(t),s=`layout-${Math.random().toString(36).slice(2,10)}`;return i.layouts.push({id:s,name:n,kind:r,tree:Ta()}),{layoutId:s}}async renameLayout(t,n,r){const s=this.getProjectLayouts(t).layouts.find(l=>l.id===n);s&&(s.name=r)}async deleteLayout(t,n){const r=this.getProjectLayouts(t),i=r.layouts.findIndex(s=>s.id===n);return i!==-1&&r.layouts.splice(i,1),r.activeId===n&&r.layouts.length>0&&(r.activeId=r.layouts[0].id),{activeId:r.activeId}}async setActiveLayout(t,n){const r=this.getProjectLayouts(t);return r.layouts.some(i=>i.id===n)&&(r.activeId=n),{activeId:r.activeId}}}const t2=[{hash:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",summary:"Merge feature into main",parents:["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","dddddddddddddddddddddddddddddddddddddddd"],refs:["main","HEAD"],author:"Alice",timestamp:17172e5},{hash:"dddddddddddddddddddddddddddddddddddddddd",summary:"Implement feature (step 2)",parents:["cccccccccccccccccccccccccccccccccccccccc"],refs:["feature"],author:"Bob",timestamp:17171e5},{hash:"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",summary:"Hotfix on main",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Alice",timestamp:171709e4},{hash:"cccccccccccccccccccccccccccccccccccccccc",summary:"Implement feature (step 1)",parents:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],refs:[],author:"Bob",timestamp:171708e4},{hash:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",summary:"Initial commit",parents:[],refs:["tag: v1.0"],author:"Alice",timestamp:1717e6}];class n2{constructor(){X(this,"projects",new Map)}getState(t){return this.projects.has(t)||this.projects.set(t,this._seedState()),this.projects.get(t)}_seedState(){const t=new Map;return t.set("src/main.rs",!1),t.set("README.md",!1),{files:t,branches:["main"],current:"main",log:[],commitSeq:0}}async init(t){this.projects.has(t)||this.projects.set(t,this._seedState())}async status(t){const n=this.getState(t);return Array.from(n.files.entries()).map(([r,i])=>({path:r,staged:i}))}async stage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!0)}async unstage(t,n){const r=this.getState(t);r.files.has(n)&&r.files.set(n,!1)}async commit(t,n){const r=this.getState(t);r.commitSeq+=1;const i={hash:`mock-${r.commitSeq}`,summary:n.split(` -`)[0]};for(const[s,l]of Array.from(r.files.entries()))l&&r.files.delete(s);return r.log.unshift(i),i}async branches(t){const n=this.getState(t);return{branches:[...n.branches],current:n.current}}async checkout(t,n){const r=this.getState(t);r.branches.includes(n)||r.branches.push(n),r.current=n}async log(t,n){return this.getState(t).log.slice(0,n)}async graph(t,n){return t2.slice(0,n)}}class r2{async connect(){}}class i2{constructor(){X(this,"open",new Set);X(this,"listeners",new Set)}async openViewWindow(t){this.open.add(t)}async closeViewWindow(t){this.open.delete(t)&&this.emit({panel:t})}async listOpenViewWindows(){return[...this.open].map(t=>({panel:t,label:t,visible:!0}))}async onViewWindowClosed(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}simulateOsClose(t){this.open.delete(t),this.emit({panel:t})}emit(t){for(const n of this.listeners)n(t)}}class s2{constructor(){X(this,"focused",null);X(this,"listeners",new Set)}async setFocusedProject(t){this.focused=t;for(const n of this.listeners)n(t)}async getFocusedProject(){return this.focused}async onFocusedProjectChanged(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}}const bu=[{id:"mock-claude",name:"Claude Code",command:"claude",args:[],contextInjection:{strategy:"conventionFile",target:"CLAUDE.md"},detect:"claude --version",cwdTemplate:"{projectRoot}"},{id:"mock-codex",name:"OpenAI Codex CLI",command:"codex",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"codex --version",cwdTemplate:"{projectRoot}"},{id:"mock-opencode",name:"OpenCode + llama.cpp",command:"opencode",args:[],contextInjection:{strategy:"conventionFile",target:"AGENTS.md"},detect:"opencode --version",cwdTemplate:"{projectRoot}",structuredAdapter:"openCode",opencode:{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}],l2=[{providerId:"anthropic",displayName:"Anthropic",models:["claude-sonnet-5","claude-opus-4-8","claude-haiku-4-5"]},{providerId:"openrouter",displayName:"OpenRouter",models:["openrouter/auto","qwen/qwen3-coder"]}];class a2{constructor(){X(this,"profiles",[]);X(this,"configured",!1);X(this,"cloneCounter",0)}async firstRunState(){return{isFirstRun:!this.configured,referenceProfiles:structuredClone(bu)}}async referenceProfiles(){return structuredClone(bu)}async detectProfiles(t){return t.map(n=>({profile:n,available:n.command==="claude"}))}async listProfiles(){return structuredClone(this.profiles)}async saveProfile(t){const n=this.profiles.findIndex(r=>r.id===t.id);return n>=0?this.profiles[n]=t:this.profiles.push(t),this.configured=!0,structuredClone(t)}async deleteProfile(t){this.profiles=this.profiles.filter(n=>n.id!==t)}async configureProfiles(t){return this.profiles=structuredClone(t),this.configured=!0,structuredClone(t)}async cloneOpenCodeProfileFromSeed(t={}){const n=bu.find(r=>r.structuredAdapter==="openCode");if(!n)throw new Error("no OpenCode seed profile");return this.cloneCounter+=1,structuredClone({...n,id:`mock-opencode-clone-${this.cloneCounter}`,name:t.name??`${n.name} (copy ${this.cloneCounter})`,opencode:t.opencode??n.opencode})}async listOpenCodeProviders(){return structuredClone(l2)}async saveOpenCodeProviderProfile(t){const n={...structuredClone(t.profile),opencode:void 0,opencodeProvider:{providerId:t.providerId,model:t.model,apiKeyRef:`mock-secret-${t.profile.id}`,custom:t.custom}},r=this.profiles.findIndex(i=>i.id===n.id);return r>=0?this.profiles[r]=n:this.profiles.push(n),this.configured=!0,structuredClone(n)}}class o2{constructor(){X(this,"servers",[]);X(this,"inUse",new Set)}async listModelServers(){return structuredClone(this.servers)}async saveModelServer(t){const n=this.servers.findIndex(r=>r.id===t.id);return n>=0?this.servers[n]=structuredClone(t):this.servers.push(structuredClone(t)),structuredClone(t)}async deleteModelServer(t){if(this.inUse.has(t))throw{code:"model_server_in_use",message:"A profile still references this server."};this.servers=this.servers.filter(n=>n.id!==t)}async previewModelServerCommand(t){if(!t.modelSource)throw{code:"INVALID",message:"model.source missing"};const n=t.binaryPath&&t.binaryPath.trim().length>0?t.binaryPath:"llama-server",r=[];t.modelSource.type==="localPath"?r.push("--model",t.modelSource.path):r.push("-hf",t.modelSource.repo),r.push("--port",String(t.port),"--host",t.host),t.gpuLayers!==void 0&&r.push("-ngl",String(t.gpuLayers)),t.contextSize!==void 0&&r.push("-c",String(t.contextSize)),t.jinja&&r.push("--jinja"),r.push(...t.args);const i=[n,...r].map(s=>/\s/.test(s)?`'${s}'`:s).join(" ");return{command:n,args:r,display:i}}markInUse(t){this.inUse.add(t)}}const c2={mode:"localOnly",autoStart:!1,port:17373,trustedProxies:[]},u2=["192.168.1.42","10.0.0.17"];function Ri(e){throw{code:"INVALID",message:e}}class d2{constructor(){X(this,"settings",structuredClone(c2));X(this,"current",{state:"stopped"});X(this,"handlers",new Set)}async getExposureSettings(){return structuredClone(this.settings)}async saveExposureSettings(t){this.validate(t),this.settings=structuredClone(t)}async previewExposure(t){this.validate(t);const n=[];t.mode==="remoteProxyOtherMachine"&&t.trustedProxies.length===0&&n.push({code:"missingTrustedProxy",message:"Add the IP address or CIDR of the reverse proxy that connects to this server."});const r=t.mode==="remoteProxyOtherMachine"?t.lanBindAddress:"127.0.0.1",i=t.mode!=="localOnly"&&r?`http://${r}:${t.port}`:void 0;return{candidateLanAddresses:[...u2],upstreamUrl:i,warnings:n}}async status(){return structuredClone(this.current)}async start(){this.validate(this.settings);const t=await this.previewExposure(this.settings);return this.emit({state:"running",localUrl:`http://127.0.0.1:${this.settings.port}`,publicUrl:this.settings.mode==="localOnly"?void 0:this.settings.publicOrigin,upstreamUrl:t.upstreamUrl}),structuredClone(this.current)}async stop(){return this.emit({state:"stopped"}),structuredClone(this.current)}async onStatusChanged(t){return this.handlers.add(t),()=>this.handlers.delete(t)}setStatus(t){this.emit(t)}emit(t){this.current=t;for(const n of this.handlers)n(structuredClone(t))}validate(t){if(t.mode!=="localOnly"){const n=t.publicOrigin;n||Ri("remote exposure requires publicOrigin"),n.startsWith("https://")||Ri("remote exposure requires publicOrigin to start with https://"),n.includes("*")&&Ri("publicOrigin must be exact, not a wildcard"),n.endsWith("/")&&Ri("publicOrigin must not end with '/'")}t.mode==="remoteProxyOtherMachine"&&(t.lanBindAddress||Ri("remoteProxyOtherMachine requires lanBindAddress"),t.trustedProxies.length===0&&Ri("remoteProxyOtherMachine requires at least one trustedProxies entry"))}}class h2{constructor(t){X(this,"templates",[]);X(this,"seq",0);this.agentGateway=t}async listTemplates(){return structuredClone(this.templates)}async createTemplate(t){this.seq+=1;const n={id:`mock-template-${this.seq}`,name:t.name,contentMd:t.content,version:1,defaultProfileId:t.defaultProfileId};return this.templates.push(n),structuredClone(n)}async updateTemplate(t,n){const r=this.templates.findIndex(i=>i.id===t);if(r===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};return this.templates[r]={...this.templates[r],contentMd:n,version:this.templates[r].version+1},structuredClone(this.templates[r])}async deleteTemplate(t){const n=this.templates.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`template ${t} not found`};this.templates.splice(n,1)}async createAgentFromTemplate(t,n,r){const i=this.templates.find(f=>f.id===n);if(!i)throw{code:"NOT_FOUND",message:`template ${n} not found`};const s=r?.synchronized??!0,l=r?.name??i.name,o=op(l)||"agent",c=new Set(this.agentGateway._rawAgents(t).map(f=>f.contextPath));let u=`agents/${o}.md`,h=2;for(;c.has(u);)u=`agents/${o}-${h}.md`,h+=1;const d={id:`mock-agent-${Math.random().toString(36).slice(2,10)}`,name:l,contextPath:u,profileId:i.defaultProfileId,origin:{type:"fromTemplate",templateId:n,syncedTemplateVersion:i.version},synchronized:s,skills:[]};return this.agentGateway._insertAgent(t,d,i.contentMd),structuredClone(d)}async detectDrift(t){const n=this.agentGateway._rawAgents(t),r=[];for(const i of n){if(!i.synchronized||i.origin.type!=="fromTemplate")continue;const{templateId:s,syncedTemplateVersion:l}=i.origin,o=this.templates.find(c=>c.id===s);o&&o.version>l&&r.push({agentId:i.id,from:l,to:o.version})}return r}async syncAgent(t,n){const i=this.agentGateway._rawAgents(t).find(o=>o.id===n);if(!i||!i.synchronized||i.origin.type!=="fromTemplate")return{synced:!1,version:null};const{templateId:s}=i.origin,l=this.templates.find(o=>o.id===s);return l?(this.agentGateway._updateAgent(t,n,{origin:{type:"fromTemplate",templateId:s,syncedTemplateVersion:l.version}},l.contentMd),{synced:!0,version:l.version}):{synced:!1,version:null}}}class f2{constructor(t){X(this,"global",[]);X(this,"byProject",new Map);X(this,"seq",0);this.agentGateway=t}bucket(t,n){if(n==="global")return this.global;let r=this.byProject.get(t);return r||(r=[],this.byProject.set(t,r)),r}async listSkills(t,n){return structuredClone(this.bucket(t,n))}async createSkill(t){this.seq+=1;const n={id:`mock-skill-${this.seq}`,name:t.name,contentMd:t.content,scope:t.scope};return this.bucket(t.projectId,t.scope).push(n),structuredClone(n)}async updateSkill(t,n,r,i){const s=this.bucket(t,n),l=s.findIndex(o=>o.id===r);if(l===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};return s[l]={...s[l],contentMd:i},structuredClone(s[l])}async deleteSkill(t,n,r){const i=this.bucket(t,n),s=i.findIndex(l=>l.id===r);if(s===-1)throw{code:"NOT_FOUND",message:`skill ${r} not found`};i.splice(s,1)}async assignSkill(t,n,r,i){const s=this.agentGateway._rawAgents(t).find(l=>l.id===n);if(!s)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};s.skills.some(l=>l.skillId===r)||this.agentGateway._setSkills(t,n,[...s.skills,{skillId:r,scope:i}])}async unassignSkill(t,n,r){const i=this.agentGateway._rawAgents(t).find(s=>s.id===n);if(!i)throw{code:"NOT_FOUND",message:`agent ${n} not found in project ${t}`};this.agentGateway._setSkills(t,n,i.skills.filter(s=>s.skillId!==r))}}class p2{constructor(){X(this,"byProject",new Map)}bucket(t){let n=this.byProject.get(t);return n||(n=new Map,this.byProject.set(t,n)),n}notFound(t,n){return{code:"NOT_FOUND",message:`memory ${t} not found in project ${n}`}}async listMemories(t){return structuredClone([...this.bucket(t).values()])}async getMemory(t,n){const r=this.bucket(t).get(n);if(!r)throw this.notFound(n,t);return structuredClone(r)}async createMemory(t){const n={name:t.name,description:t.description,type:t.type,content:t.content};return this.bucket(t.projectId).set(op(t.name),n),structuredClone(n)}async updateMemory(t,n,r,i,s){const l=this.bucket(t),o=l.get(n);if(!o)throw this.notFound(n,t);const c={...o,description:r,type:i,content:s};return l.set(n,c),structuredClone(c)}async deleteMemory(t,n){if(!this.bucket(t).delete(n))throw this.notFound(n,t)}async readIndex(t){return[...this.bucket(t).entries()].map(([n,r])=>({slug:n,title:r.name,hook:r.description,type:r.type}))}async resolveLinks(t,n){const r=this.bucket(t),i=r.get(n);if(!i)throw this.notFound(n,t);const s=new Set;for(const l of i.content.matchAll(/\[\[([^\]]+)\]\]/g)){const o=l[1].trim();o!==n&&r.has(o)&&s.add(o)}return[...s]}async recall(t,n,r){const i=await this.readIndex(t),s=Math.max(0,Math.floor(r/16));return i.slice(0,s)}}class m2{constructor(t,n=[]){X(this,"profiles",new Map);X(this,"engines");this.engines={recommendedOnnx:[{id:"e5-small",displayName:"E5 Small (multilingual)",dimension:384,approxSizeMb:120,recommended:!0},{id:"bge-small",displayName:"BGE Small",dimension:384,approxSizeMb:130,recommended:!1}],ollamaDetected:!1,onnxCachedModels:[],vectorHttpEnabled:!0,vectorOnnxEnabled:!0,...t};for(const r of n)this.profiles.set(r.id,r)}async listEmbedderProfiles(){return structuredClone([...this.profiles.values()])}async saveEmbedderProfile(t){if(!t.id.trim()||!t.name.trim())throw{code:"INVALID",message:"embedder profile id/name must not be empty"};if(t.dimension<=0)throw{code:"INVALID",message:"embedder profile dimension must be > 0"};return this.profiles.set(t.id,structuredClone(t)),structuredClone(t)}async deleteEmbedderProfile(t){this.profiles.delete(t)}async describeEmbedderEngines(){return structuredClone(this.engines)}}class g2{constructor(){X(this,"interrupts",[]);X(this,"delivered",[]);X(this,"frontAttached",[]);X(this,"cancelledResumes",[]);X(this,"resumeArmings",[]);X(this,"cancelResumeResult",!0)}async interrupt(t,n){this.interrupts.push({projectId:t,agentId:n})}async delegationDelivered(t,n,r){this.delivered.push({projectId:t,agentId:n,ticket:r})}async setFrontAttached(t,n){this.frontAttached.push({agentId:t,attached:n})}async cancelResume(t){return this.cancelledResumes.push(t),this.cancelResumeResult}async setResumeAt(t,n){this.resumeArmings.push({agentId:t,resetsAtMs:n})}}class x2{constructor(){X(this,"devices",[]);X(this,"issued",0);X(this,"_issuedCodes",[])}_setDevices(t){this.devices=structuredClone(t)}async listDevices(){return structuredClone(this.devices)}async createPairingCode(){const t=(268435456+this.issued++).toString(16).toUpperCase().slice(0,8);this._issuedCodes.push(t);const n=600;return{code:t,expiresAtMs:Date.now()+n*1e3,ttlSeconds:n}}async renameDevice(t,n){const r=this.devices.find(i=>i.deviceId===t);if(!r)throw{code:"NOT_FOUND",message:`unknown device ${t}`};r.name=n}async revokeDevice(t){this.devices=this.devices.filter(n=>n.deviceId!==t)}async revokeAllDevices(){this.devices=[]}}class v2{constructor(){X(this,"docs",new Map);X(this,"mcpCatalogue",{readOnlyTools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read","idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"],writeActionTools:["idea_ask_agent","idea_run_in_background","idea_launch_agent","idea_stop_agent","idea_update_context","idea_context_propose","idea_memory_write","idea_workstate_set","idea_create_skill","idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]});X(this,"mcpDocs",new Map)}doc(t){return this.docs.has(t)||this.docs.set(t,{version:1,agents:[]}),this.docs.get(t)}async getProjectPermissions(t){return structuredClone(this.doc(t))}async updateProjectPermissions(t,n){const r=this.doc(t);return n?r.projectDefaults=structuredClone(n):delete r.projectDefaults,structuredClone(r)}async updateAgentPermissions(t,n,r){const i=this.doc(t),s=(i.agents??[]).filter(l=>l.agentId!==n);return r&&s.push({agentId:n,permissions:structuredClone(r)}),i.agents=s,structuredClone(i)}async resolveAgentPermissions(t,n){const r=this.doc(t),i=r.projectDefaults,s=r.agents?.find(l=>l.agentId===n)?.permissions;return!i&&!s?null:{rules:[...i?.rules??[],...s?.rules??[]],fallback:S2(i?.fallback,s?.fallback)}}mcpDoc(t){return this.mcpDocs.has(t)||this.mcpDocs.set(t,{version:1,catalogue:this.mcpCatalogue,projectDefault:null,agents:[]}),this.mcpDocs.get(t)}async getMcpToolPermissions(t){return structuredClone(this.mcpDoc(t))}async updateProjectMcpToolPermissions(t,n){const r=this.mcpDoc(t);return r.projectDefault=n?structuredClone(n):null,structuredClone(r)}async updateAgentMcpToolPermissions(t,n,r){const i=this.mcpDoc(t);return i.agents=i.agents.filter(s=>s.agentId!==n),r&&i.agents.push({agentId:n,policy:structuredClone(r)}),structuredClone(i)}}class _2{constructor(){X(this,"states",new Map)}_setProjectWorkState(t,n){this.states.set(t,lp(n))}async getProjectWorkState(t){return structuredClone(this.states.get(t)??{agents:[],conversations:[]})}async cancelBackgroundTask(t){}async retryBackgroundTask(t){}}class y2{constructor(){X(this,"threads",new Map)}key(t,n){return`${t}::${n}`}_setTurns(t,n,r){this.threads.set(this.key(t,n),r.map(i=>structuredClone(i)))}async readPage(t,n,r){const i=this.threads.get(this.key(t,n))??[],s=i.length,l=r?.limit,o=Math.min(Math.max(l&&l>0?l:50,1),200),c=r?.direction??"backward",u=r?.anchor;let h,d,f;if(u===void 0)c==="forward"?(h=0,d=Math.min(o,s),f=d0);else{const x=i.findIndex(w=>w.id===u);x===-1?(h=0,d=0,f=!1):c==="forward"?(h=x+1,d=Math.min(h+o,s),f=d0)}const p=i.slice(h,d).map(x=>structuredClone(x)),m=p.at(-1);return{turns:p,hasMore:f,...m?{nextAnchor:m.id}:{}}}}class b2{constructor(t){X(this,"tickets",new Map);X(this,"carnets",new Map);X(this,"counters",new Map);X(this,"sprints",new Map);X(this,"sprintCounters",new Map);X(this,"chatSessions",new Map);X(this,"chatCounter",0);this.system=t}_seedTicket(t,n){const r=structuredClone(n);return r.sprintId===void 0&&(r.sprintId=null),this.projectTickets(t).set(r.ref,r),this.counters.set(t,Math.max(this.counters.get(t)??0,r.number)),structuredClone(r)}_seedSprint(t,n){const r={status:"planned",ticketCount:0,version:1,...n};return this.projectSprints(t).set(r.id,r),structuredClone(r)}projectSprints(t){let n=this.sprints.get(t);return n||(n=new Map,this.sprints.set(t,n)),n}recountSprints(t){const n=this.projectSprints(t),r=new Map;for(const i of this.projectTickets(t).values())i.sprintId&&r.set(i.sprintId,(r.get(i.sprintId)??0)+1);for(const i of n.values())i.ticketCount=r.get(i.id)??0}projectTickets(t){let n=this.tickets.get(t);return n||(n=new Map,this.tickets.set(t,n)),n}projectCarnets(t){let n=this.carnets.get(t);return n||(n=new Map,this.carnets.set(t,n)),n}require(t,n){const r=this.projectTickets(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`ticket ${n} not found`};return r}guard(t,n){if(t.version!==n)throw{code:"INVALID",message:`issue version conflict: expected ${n}, actual ${t.version}`}}async create(t,n){const r=(this.counters.get(t)??0)+1;this.counters.set(t,r);const i=Date.now(),s={id:`mock-ticket-${t}-${r}`,ref:`#${r}`,number:r,title:n.title,description:n.description??"",status:n.status??"open",priority:n.priority??"medium",sprintId:null,links:[],assignedAgentIds:[...n.assignedAgentIds??[]],createdBy:{kind:"user"},updatedBy:{kind:"user"},createdAt:i,updatedAt:i,version:1};return this.projectTickets(t).set(s.ref,s),this.system?.emit({type:"issueCreated",issueId:s.id,issueRef:s.ref}),structuredClone(s)}async read(t,n,r=!1){const i=structuredClone(this.require(t,n));return r&&(i.carnet=this.projectCarnets(t).get(n)??""),i}async list(t,n){const r=n??{},i=r.text?.trim().toLowerCase(),s=r.statuses??[],l=r.priorities??[];let o=[...this.projectTickets(t).values()].filter(d=>s.length===0||s.includes(d.status)).filter(d=>l.length===0||l.includes(d.priority)).filter(d=>!r.assignedAgentId||d.assignedAgentIds.includes(r.assignedAgentId)).filter(d=>!i||d.title.toLowerCase().includes(i)||d.description.toLowerCase().includes(i));o=r.sort?YE(o,r.sort):o.sort((d,f)=>f.number-d.number);const c=Number.parseInt(r.cursor??"0",10)||0,u=Math.min(Math.max(r.limit??100,1),500),h=Math.min(o.length,c+u);return{items:o.slice(c,h).map(d=>({ref:d.ref,path:`.ideai/tickets/${d.number}.md`,title:d.title,status:d.status,priority:d.priority,sprintId:d.sprintId??null,assignedAgentIds:[...d.assignedAgentIds],updatedAt:d.updatedAt})),...hc.targetRef===r&&c.kind===i)||l.links.push({targetRef:r,kind:i}),this.bump(l),this.system?.emit({type:"issueLinked",issueRef:n,target:r,kind:i,version:l.version}),structuredClone(l)}async unlink(t,n,r,i,s){const l=this.require(t,n);return this.guard(l,i),l.links=l.links.filter(o=>o.targetRef!==r||s!==void 0&&o.kind!==s),this.bump(l),this.system?.emit({type:"issueUnlinked",issueRef:n,target:r,kind:s??"relatesTo",version:l.version}),structuredClone(l)}async assign(t,n,r,i,s){const l=this.require(t,n);this.guard(l,s);const o=l.assignedAgentIds.includes(r);return i&&!o&&l.assignedAgentIds.push(r),!i&&o&&(l.assignedAgentIds=l.assignedAgentIds.filter(c=>c!==r)),this.bump(l),this.system?.emit({type:i?"issueAgentAssigned":"issueAgentUnassigned",issueRef:n,agentId:r,version:l.version}),structuredClone(l)}async listSprints(t){return this.recountSprints(t),[...this.projectSprints(t).values()].sort((n,r)=>n.order-r.order).map(n=>structuredClone(n))}async setTicketSprint(t,n,r,i){const s=this.require(t,n);if(this.guard(s,i),r!==null&&!this.projectSprints(t).has(r))throw{code:"NOT_FOUND",message:`sprint ${r} not found`};const l=s.sprintId??null;return s.sprintId=r,this.bump(s),this.recountSprints(t),this.system?.emit({type:"issueSprintChanged",issueRef:n,from:l,to:r,version:s.version}),structuredClone(s)}async createSprint(t,n){const r=this.projectSprints(t),i=(this.sprintCounters.get(t)??0)+1;this.sprintCounters.set(t,i);const s=r.size===0?1:Math.max(...[...r.values()].map(o=>o.order))+1,l={id:`mock-sprint-${t}-${i}`,order:s,name:n,status:"planned",ticketCount:0,version:1};return r.set(l.id,l),this.system?.emit({type:"sprintCreated",sprintId:l.id,order:l.order}),structuredClone(l)}async renameSprint(t,n,r,i){const s=this.requireSprint(t,n);return this.guardSprint(s,i),s.name=r,s.version+=1,this.system?.emit({type:"sprintRenamed",sprintId:n,name:r,version:s.version}),structuredClone(s)}async reorderSprints(t,n){const r=this.projectSprints(t);for(const s of n)this.requireSprint(t,s);const i=[...r.values()].filter(s=>!n.includes(s.id)).sort((s,l)=>s.order-l.order).map(s=>s.id);return[...n,...i].forEach((s,l)=>{const o=r.get(s);o&&(o.order=l+1,this.system?.emit({type:"sprintReordered",sprintId:s,order:o.order,version:o.version}))}),this.listSprints(t)}async deleteSprint(t,n){this.requireSprint(t,n);for(const r of this.projectTickets(t).values())r.sprintId===n&&(r.sprintId=null,this.bump(r),this.system?.emit({type:"issueSprintChanged",issueRef:r.ref,from:n,to:null,version:r.version}));this.projectSprints(t).delete(n),this.system?.emit({type:"sprintDeleted",sprintId:n})}async openTicketChat(t,n,r){this.require(t,n);const i=`mock-ticket-chat-${++this.chatCounter}`;return this.chatSessions.set(n,i),this.system?.emit({type:"ticketAssistantOpened",issueRef:n,profileId:r}),{sessionId:i,requester:"ticket-assistant",issueRef:n}}async closeTicketChat(t,n){this.chatSessions.delete(n)&&this.system?.emit({type:"ticketAssistantClosed",issueRef:n})}async sendTicketChat(t,n,r){if(![...this.chatSessions.values()].includes(t))throw{code:"NOT_FOUND",message:`chat session ${t} not found`};const i=`Assistant: reçu « ${n} ».`,s=[{kind:"textDelta",text:"Assistant: reçu "},{kind:"textDelta",text:`« ${n} ».`},{kind:"final",content:i}];for(const l of s)await Promise.resolve(),r(l)}requireSprint(t,n){const r=this.projectSprints(t).get(n);if(!r)throw{code:"NOT_FOUND",message:`sprint ${n} not found`};return r}guardSprint(t,n){if(t.version!==n)throw{code:"INVALID",message:`sprint version conflict: expected ${n}, actual ${t.version}`}}}class w2{constructor(){X(this,"store",new Map)}read(t){const n=this.store.get(t);if(n===void 0)return null;try{return JSON.parse(n)}catch{return this.store.delete(t),null}}write(t,n){try{this.store.set(t,JSON.stringify(n))}catch{}}remove(t){this.store.delete(t)}}function S2(e,t){const n={allow:0,ask:1,deny:2},r=e??t??"ask";return t&&n[t]>=n[r]?t:r}class k2{constructor(){X(this,"plugins",[]);X(this,"seq",0)}summaryFor(t){return{topLevelMenus:0,menuItems:0,layouts:0,mcpServers:0}}_seedPlugin(t){this.plugins.push(t)}async listPlugins(){return structuredClone(this.plugins)}async reviewPackage(t){this.seq+=1;const n=t.path.split("/").pop()??t.path;return{id:`mock.plugin.${this.seq}`,displayName:n.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",description:`Reviewed from ${t.sourceKind}: ${t.path}`,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`),issues:[],installable:!0}}async install(t,n){this.seq+=1;const r=n.split("/").pop()??n,i={id:`mock.plugin.${this.seq}`,displayName:r.replace(/\.(ideaplug|zip|vsix)$/i,""),publisher:"Mock Publisher",version:"0.1.0",sourceKind:t,sourceLabel:n,lifecycleState:"enabled",enabled:!0,pendingUninstall:!1,restartRequired:!0,trustLevel:"full",contributionSummary:this.summaryFor(`mock.plugin.${this.seq}`)};return this.plugins.push(i),{plugin:structuredClone(i),restartRequired:!0}}installFromArchive(t){return this.install("archive",t)}installFromDirectory(t){return this.install("directory",t)}async setEnabled(t,n){const r=this.plugins.find(s=>s.id===t);if(!r)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};const i=n?"enabled":"disabled";return r.enabled=n,r.lifecycleState=i,r.restartRequired=!0,structuredClone(r)}async uninstall(t){const n=this.plugins.findIndex(r=>r.id===t);if(n===-1)throw{code:"NOT_FOUND",message:`plugin ${t} not found`};return this.plugins.splice(n,1),{pluginId:t,restartRequired:!0}}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){}}function C2(){const e=new QE,t=new XE;return{system:t,agent:e,input:new g2,terminal:new JE,project:new ZE,layout:new e2,git:new n2,remote:new r2,profile:new a2,modelServer:new o2,desktopServer:new d2,template:new h2(e),skill:new f2(e),memory:new p2,embedder:new m2,device:new x2,permission:new v2,workState:new _2,conversation:new y2,ticket:new b2(t),window:new i2,focusedProject:new s2,uiPreferences:new w2,plugin:new k2}}function sw(){const e=globalThis.fetch;return typeof e=="function"?e.bind(globalThis):e}function j2(e,t){if(e&&typeof e=="object"){const n=e,r=typeof n.code=="string"?n.code:void 0,i=typeof n.message=="string"?n.message:void 0;if(r||i)return{code:r??"ERROR",message:i??t}}return{code:"TRANSPORT_ERROR",message:t}}class N2{constructor(t){X(this,"baseUrl");X(this,"token");X(this,"fetchImpl");X(this,"onUnauthorized");this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.onUnauthorized=t.onUnauthorized,this.fetchImpl=t.fetchImpl??sw()}invoke(t,n={}){return this.request("POST","/api/invoke",{command:t,args:n},`command '${t}'`)}async request(t,n,r,i=`${t} ${n}`){const s={"Content-Type":"application/json"};this.token&&(s.Authorization=`Bearer ${this.token}`);let l;try{l=await this.fetchImpl(`${this.baseUrl}${n}`,{method:t,headers:s,body:r===void 0?void 0:JSON.stringify(r),credentials:"same-origin"})}catch(c){throw{code:"TRANSPORT_ERROR",message:`HTTP request for ${i} failed: ${String(c)}`}}if(!l.ok){l.status===401&&this.onUnauthorized?.();let c;try{c=await l.json()}catch{c=void 0}throw j2(c,`${i} failed (HTTP ${l.status})`)}let o;try{o=await l.json()}catch{o=void 0}return o}}function E2(e){let t="";for(let n=0;nlw(s.bytesBase64)),n=t.reduce((s,l)=>s+l.length,0),r=new Uint8Array(n);let i=0;for(const s of t)r.set(s,i),i+=s.length;return r}class aw{constructor(t){X(this,"wsUrl");X(this,"token");X(this,"socketFactory");X(this,"reconnectBaseMs");X(this,"reconnectMaxMs");X(this,"setTimeoutImpl");X(this,"clearTimeoutImpl");X(this,"onReconnectFailed");X(this,"socket",null);X(this,"opening",null);X(this,"disposed",!1);X(this,"everConnected",!1);X(this,"connState","connecting");X(this,"reconnectAttempt",0);X(this,"reconnectHandle",null);X(this,"outputSinks",new Map);X(this,"terminals",new Map);X(this,"pending",new Map);X(this,"domainEventHandler",null);X(this,"connListeners",new Set);this.wsUrl=t.wsUrl.replace(/\/+$/,""),this.token=t.token,this.socketFactory=t.socketFactory??(n=>new WebSocket(n)),this.reconnectBaseMs=t.reconnectBaseMs??500,this.reconnectMaxMs=t.reconnectMaxMs??1e4,this.setTimeoutImpl=t.setTimeoutImpl??((n,r)=>setTimeout(n,r)),this.clearTimeoutImpl=t.clearTimeoutImpl??(n=>clearTimeout(n)),this.onReconnectFailed=t.onReconnectFailed}getConnectionState(){return this.connState}onConnectionStateChange(t){return this.connListeners.add(t),()=>this.connListeners.delete(t)}setConnState(t){if(this.connState!==t){this.connState=t;for(const n of this.connListeners)n(t)}}setDomainEventHandler(t){this.domainEventHandler=t}clearDomainEventHandler(){this.domainEventHandler=null}setOutputSink(t,n){this.outputSinks.set(t,n)}removeOutputSink(t){this.outputSinks.delete(t)}async ensureConnected(){if(!this.socket)return this.opening?this.opening:this.connect()}connect(){return this.setConnState(this.everConnected?"reconnecting":"connecting"),this.opening=new Promise((t,n)=>{const r=this.token?`${this.wsUrl}${tx}?token=${encodeURIComponent(this.token)}`:`${this.wsUrl}${tx}`,i=this.socketFactory(r);i.onopen=()=>{this.socket=i,this.opening=null,this.everConnected=!0,this.reconnectAttempt=0,this.setConnState("connected"),t()},i.onerror=s=>{this.opening=null,n(s)},i.onclose=()=>this.handleSocketClosed(),i.onmessage=s=>this.handleMessage(s.data)}),this.opening}handleSocketClosed(){if(this.socket=null,this.opening=null,this.rejectAllPending({code:"WS_CLOSED",message:"socket closed"}),this.disposed){this.setConnState("closed");return}if(this.setConnState("reconnecting"),this.terminals.size>0)for(const t of this.terminals.values())t.onData(wu("déconnecté — reconnexion…"));this.needsReconnect()&&this.scheduleReconnect()}needsReconnect(){return this.terminals.size>0||this.domainEventHandler!==null}scheduleReconnect(){if(this.disposed||this.reconnectHandle)return;const t=Math.min(this.reconnectMaxMs,this.reconnectBaseMs*2**this.reconnectAttempt);this.reconnectAttempt+=1,this.reconnectHandle=this.setTimeoutImpl(()=>{this.reconnectHandle=null,this.reconnectNow()},t)}async reconnectNow(){if(!this.disposed)try{await this.connect(),await this.reattachAll()}catch{this.onReconnectFailed?.(),this.needsReconnect()&&this.scheduleReconnect()}}async reattachAll(){for(const[t,n]of this.terminals)try{const i=(await this.send("terminal.attach",{sessionId:t,lastSeq:n.lastSeq})).payload;n.onData(wu("reconnecté"));const s=ix(i);s.length>0&&n.onData(s),typeof i.nextSeq=="number"&&(n.lastSeq=Math.max(0,i.nextSeq-1))}catch{}}openTerminal(t){return this.attachInternal("terminal.open",{cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}launchAgent(t){return this.attachInternal("agent.launch",{projectId:t.projectId,agentId:t.agentId,nodeId:t.nodeId??null,rows:t.rows,cols:t.cols,conversationId:t.conversationId??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:0})}attachTerminal(t){return this.attachInternal("terminal.attach",{sessionId:t.sessionId,rows:t.rows,cols:t.cols,lastSeq:t.lastSeq??null},{onData:t.onData,onStatus:t.onStatus,lastSeq:t.lastSeq??0},t.sessionId)}async attachInternal(t,n,r,i){const l=(await this.send(t,n)).payload,o=i??l.session.sessionId;return typeof l.nextSeq=="number"&&(r.lastSeq=Math.max(0,l.nextSeq-1)),this.terminals.set(o,r),this.setOutputSink(o,r.onData),{sessionId:o,scrollback:ix(l),assignedConversationId:l.assignedConversationId,status:l.status}}async detachTerminal(t){this.removeTerminal(t),await this.sendFireAndForget("terminal.detach",{sessionId:t})}async closeTerminalSession(t){this.removeTerminal(t),await this.send("terminal.close",{sessionId:t})}removeTerminal(t){this.terminals.delete(t),this.outputSinks.delete(t)}async send(t,n){await this.ensureConnected();const r=this.socket;if(!r)throw{code:"WS_CLOSED",message:"socket not connected"};const i=rx(),s={id:i,kind:t,payload:n},l=new Promise((o,c)=>{this.pending.set(i,{resolve:o,reject:c})});return r.send(JSON.stringify(s)),l}async sendFireAndForget(t,n){await this.ensureConnected();const i={id:rx(),kind:t,payload:n};this.socket?.send(JSON.stringify(i))}static encodeInput(t){return E2(t)}disconnect(){this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disconnected"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null;const t=this.socket;t&&(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close()),this.socket=null,this.opening=null,this.everConnected=!1,this.reconnectAttempt=0,this.setConnState("closed")}dispose(){this.disposed=!0,this.reconnectHandle&&(this.clearTimeoutImpl(this.reconnectHandle),this.reconnectHandle=null),this.rejectAllPending({code:"WS_CLOSED",message:"client disposed"}),this.outputSinks.clear(),this.terminals.clear(),this.domainEventHandler=null,this.socket?.close(),this.socket=null,this.opening=null,this.setConnState("closed")}rejectAllPending(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}switch(n.kind){case"terminal.output":{const r=n.payload,i=this.terminals.get(r.sessionId);i&&typeof r.seq=="number"&&(i.lastSeq=r.seq);const s=this.outputSinks.get(r.sessionId);s&&s(lw(r.bytesBase64));return}case"terminal.status":{const r=n.payload;this.handleStatus(r);return}case"event.domain":{this.domainEventHandler?.(n.payload);return}}if(n.replyTo){const r=this.pending.get(n.replyTo);r&&(this.pending.delete(n.replyTo),n.kind==="error"?r.reject(n.payload):r.resolve(n))}}handleStatus(t){const n=this.terminals.get(t.sessionId);if(n)if(t.status==="exited"||t.status==="closed"){const r=t.exitCode;n.onData(wu(r==null?"session terminée":`session terminée (code ${r})`)),n.onStatus?.(t.status,t.exitCode),this.removeTerminal(t.sessionId)}else n.onStatus?.(t.status,t.exitCode)}}const Su="idea.web.paired";function A2(){const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n),removeItem:t=>void e.delete(t)}}function T2(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return A2()}function L2(){return typeof window<"u"&&window.location?window.location.origin:"http://localhost"}const D2={invalidOrExpired:"Code invalide ou expiré.",invalidName:"Nom d'appareil invalide (1 à 40 caractères). Le code reste valable.",rateLimited:"Trop de tentatives. Réessayez dans quelques minutes avec un nouveau code.",pairingFailed:"Échec de l'appairage."};function R2(e,t){const n=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;let r;return n==="invalid_or_expired"?r="invalidOrExpired":n==="invalid_name"?r="invalidName":n==="rate_limited"||t===429?r="rateLimited":t===401||t===403?r="invalidOrExpired":r="pairingFailed",{code:r,message:D2[r]}}class M2{constructor(t={}){X(this,"baseUrl");X(this,"fetchImpl");X(this,"store");X(this,"unauthorizedHandlers",new Set);this.baseUrl=(t.baseUrl??L2()).replace(/\/+$/,""),this.fetchImpl=t.fetchImpl??sw(),this.store=t.store??T2()}isPaired(){return this.store.getItem(Su)==="1"}markPaired(){this.store.setItem(Su,"1")}forget(){this.store.removeItem(Su)}async logout(){try{await this.fetchImpl(`${this.baseUrl}/api/logout`,{method:"POST",credentials:"same-origin"})}catch{}finally{this.forget()}}async pair(t,n){let r;try{r=await this.fetchImpl(`${this.baseUrl}/api/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,name:n})})}catch(i){throw{code:"TRANSPORT_ERROR",message:`Impossible de joindre le serveur : ${String(i)}`}}if(!r.ok){let i;try{i=await r.json()}catch{i=void 0}throw R2(i,r.status)}this.markPaired()}notifyUnauthorized(){this.forget();for(const t of this.unauthorizedHandlers)t()}onUnauthorized(t){return this.unauthorizedHandlers.add(t),()=>this.unauthorizedHandlers.delete(t)}}let ku=null;function ow(){return ku||(ku=new M2),ku}let cp=null;function I2(e){cp=e}function Ih(){return cp}function sx(){cp?.disconnect()}class O2{constructor(t){this.http=t}async listDevices(){return(await this.http.request("GET","/api/devices")).devices}createPairingCode(){return this.http.request("POST","/api/pairing-code")}renameDevice(t,n){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/rename`,{name:n})}revokeDevice(t){return this.http.request("POST",`/api/devices/${encodeURIComponent(t)}/revoke`)}revokeAllDevices(){return this.http.request("POST","/api/devices/revoke-all")}}class B2{constructor(t){this.http=t}listProjects(){return this.http.invoke("list_projects")}createProject(t,n){return this.http.invoke("create_project",{request:{name:t,root:n}})}openProject(t){return this.http.invoke("open_project",{projectId:t})}async closeProject(t){await this.http.invoke("close_project",{projectId:t})}readProjectContext(t){return this.http.invoke("read_project_context",{projectId:t})}async updateProjectContext(t,n){await this.http.invoke("update_project_context",{request:{projectId:t,content:n}})}}class z2{constructor(t){this.http=t}loadLayout(t,n){return this.http.invoke("load_layout",{projectId:t,layoutId:n})}mutateLayout(t,n,r){return this.http.invoke("mutate_layout",{projectId:t,layoutId:r,operation:n})}listLayouts(t){return this.http.invoke("list_layouts",{projectId:t})}createLayout(t,n,r){return this.http.invoke("create_layout",{request:{projectId:t,name:n,kind:r}})}renameLayout(t,n,r){return this.http.invoke("rename_layout",{request:{projectId:t,layoutId:n,name:r}})}deleteLayout(t,n){return this.http.invoke("delete_layout",{request:{projectId:t,layoutId:n}})}setActiveLayout(t,n){return this.http.invoke("set_active_layout",{request:{projectId:t,layoutId:n}})}}class F2{constructor(t){this.http=t}status(t){return this.http.invoke("git_status",{projectId:t})}async stage(t,n){await this.http.invoke("git_stage",{request:{projectId:t,path:n}})}async unstage(t,n){await this.http.invoke("git_unstage",{request:{projectId:t,path:n}})}commit(t,n){return this.http.invoke("git_commit",{request:{projectId:t,message:n}})}branches(t){return this.http.invoke("git_branches",{projectId:t})}async checkout(t,n){await this.http.invoke("git_checkout",{request:{projectId:t,branch:n}})}log(t,n){return this.http.invoke("git_log",{projectId:t,limit:n})}async init(t){await this.http.invoke("git_init",{projectId:t})}graph(t,n){return this.http.invoke("git_graph",{projectId:t,limit:n})}}class $2{constructor(t){this.http=t}firstRunState(){return this.http.invoke("first_run_state")}referenceProfiles(){return this.http.invoke("reference_profiles")}detectProfiles(t){return this.http.invoke("detect_profiles",{request:{candidates:t}})}listProfiles(){return this.http.invoke("list_profiles")}saveProfile(t){return this.http.invoke("save_profile",{request:{profile:t}})}async deleteProfile(t){await this.http.invoke("delete_profile",{profileId:t})}configureProfiles(t){return this.http.invoke("configure_profiles",{request:{profiles:t}})}cloneOpenCodeProfileFromSeed(t={}){return this.http.invoke("clone_opencode_profile_from_seed",{request:{name:t.name,opencode:t.opencode}})}listOpenCodeProviders(){return this.http.invoke("list_opencode_providers")}saveOpenCodeProviderProfile(t){return this.http.invoke("save_opencode_provider_profile",{request:{profile:t.profile,providerId:t.providerId,model:t.model,apiKey:t.apiKey,custom:t.custom}})}}class W2{constructor(t){this.http=t}listModelServers(){return this.http.invoke("list_model_servers")}saveModelServer(t){return this.http.invoke("save_model_server",{request:{config:t}})}async deleteModelServer(t){await this.http.invoke("delete_model_server",{serverId:t})}previewModelServerCommand(t){return this.http.invoke("preview_model_server_command",{config:t})}}class H2{constructor(t){this.http=t}listTemplates(){return this.http.invoke("list_templates")}createTemplate(t){return this.http.invoke("create_template",{request:{name:t.name,content:t.content,defaultProfileId:t.defaultProfileId}})}updateTemplate(t,n){return this.http.invoke("update_template",{request:{templateId:t,content:n}})}async deleteTemplate(t){await this.http.invoke("delete_template",{templateId:t})}createAgentFromTemplate(t,n,r){return this.http.invoke("create_agent_from_template",{request:{projectId:t,templateId:n,name:r?.name??null,synchronized:r?.synchronized??!0}})}detectDrift(t){return this.http.invoke("detect_agent_drift",{projectId:t})}syncAgent(t,n){return this.http.invoke("sync_agent_with_template",{request:{projectId:t,agentId:n}})}}class U2{constructor(t){this.http=t}listSkills(t,n){return this.http.invoke("list_skills",{projectId:t,scope:n})}createSkill(t){return this.http.invoke("create_skill",{request:{projectId:t.projectId,name:t.name,content:t.content,scope:t.scope}})}updateSkill(t,n,r,i){return this.http.invoke("update_skill",{request:{projectId:t,scope:n,skillId:r,content:i}})}async deleteSkill(t,n,r){await this.http.invoke("delete_skill",{projectId:t,scope:n,skillId:r})}async assignSkill(t,n,r,i){await this.http.invoke("assign_skill_to_agent",{request:{projectId:t,agentId:n,skillId:r,scope:i}})}async unassignSkill(t,n,r){await this.http.invoke("unassign_skill_from_agent",{request:{projectId:t,agentId:n,skillId:r}})}}class q2{constructor(t){this.http=t}listMemories(t){return this.http.invoke("list_memories",{projectId:t})}getMemory(t,n){return this.http.invoke("get_memory",{projectId:t,slug:n})}createMemory(t){return this.http.invoke("create_memory",{request:{projectId:t.projectId,name:t.name,description:t.description,type:t.type,content:t.content}})}updateMemory(t,n,r,i,s){return this.http.invoke("update_memory",{request:{projectId:t,slug:n,description:r,type:i,content:s}})}async deleteMemory(t,n){await this.http.invoke("delete_memory",{projectId:t,slug:n})}readIndex(t){return this.http.invoke("read_memory_index",{projectId:t})}resolveLinks(t,n){return this.http.invoke("resolve_memory_links",{projectId:t,slug:n})}recall(t,n,r){return this.http.invoke("recall_memory",{request:{projectId:t,text:n,tokenBudget:r}})}}class V2{constructor(t){this.http=t}listEmbedderProfiles(){return this.http.invoke("list_embedder_profiles")}saveEmbedderProfile(t){return this.http.invoke("save_embedder_profile",{request:{profile:t}})}async deleteEmbedderProfile(t){await this.http.invoke("delete_embedder_profile",{embedderId:t})}describeEmbedderEngines(){return this.http.invoke("describe_embedder_engines")}}class K2{constructor(t){this.http=t}getProjectPermissions(t){return this.http.invoke("get_project_permissions",{projectId:t})}updateProjectPermissions(t,n){return this.http.invoke("update_project_permissions",{request:{projectId:t,permissions:n}})}updateAgentPermissions(t,n,r){return this.http.invoke("update_agent_permissions",{request:{projectId:t,agentId:n,permissions:r}})}resolveAgentPermissions(t,n){return this.http.invoke("resolve_agent_permissions",{request:{projectId:t,agentId:n}})}getMcpToolPermissions(t){return this.http.invoke("get_mcp_tool_permissions",{projectId:t})}updateProjectMcpToolPermissions(t,n){return this.http.invoke("update_project_mcp_tool_permissions",{request:{projectId:t,policy:n}})}updateAgentMcpToolPermissions(t,n,r){return this.http.invoke("update_agent_mcp_tool_permissions",{request:{projectId:t,agentId:n,policy:r}})}}class G2{constructor(t){this.http=t}async getProjectWorkState(t){const n=await this.http.invoke("get_project_work_state",{projectId:t});return lp(n)}async cancelBackgroundTask(t){await this.http.invoke("cancel_background_task",{taskId:t})}async retryBackgroundTask(t){await this.http.invoke("retry_background_task",{taskId:t})}}class Y2{constructor(t){this.http=t}async readPage(t,n,r){const i=await this.http.invoke("read_conversation_page",{request:{projectId:t,conversationId:n,anchor:r?.anchor,direction:r?.direction??"backward",limit:r?.limit}});return rw(i)}}class X2{constructor(t){this.http=t}async interrupt(t,n){await this.http.invoke("interrupt_agent",{request:{projectId:t,agentId:n}})}async delegationDelivered(t,n,r){await this.http.invoke("delegation_delivered",{request:{projectId:t,agentId:n,ticket:r}})}async setFrontAttached(t,n){await this.http.invoke("set_front_attached",{request:{agentId:t,attached:n}})}async cancelResume(t){return this.http.invoke("cancel_resume",{agentId:t})}async setResumeAt(t,n){await this.http.invoke("set_resume_at",{agentId:t,resetsAtMs:n})}}function ot(e){throw{code:"UNSUPPORTED_ON_WEB",message:`${e} is not available in the web client (desktop-only).`}}class Q2{openViewWindow(){return ot("Detaching a panel into an OS window")}closeViewWindow(){return ot("Closing a detached OS window")}listOpenViewWindows(){return Promise.resolve([])}onViewWindowClosed(t){return Promise.resolve(()=>{})}}class J2{setFocusedProject(t){return Promise.resolve()}getFocusedProject(){return Promise.resolve(null)}onFocusedProjectChanged(t){return Promise.resolve(()=>{})}}class Z2{connect(){return ot("Remote (SSH/WSL) connection")}}class eP{async getExposureSettings(){return ot("Embedded server settings")}async saveExposureSettings(t){return ot("Embedded server settings")}async previewExposure(t){return ot("Embedded server settings")}async status(){return ot("Embedded server status")}async start(){return ot("Starting the embedded server")}async stop(){return ot("Stopping the embedded server")}onStatusChanged(t){return Promise.resolve(()=>{})}}class tP{async listPlugins(){return ot("Plugin management")}async reviewPackage(t){return ot("Plugin management")}async installFromArchive(t){return ot("Plugin management")}async installFromDirectory(t){return ot("Plugin management")}async setEnabled(t,n){return ot("Plugin management")}async uninstall(t){return ot("Plugin management")}async listRuntimeContributions(){return{plugins:[]}}async openPluginsFolder(t){return ot("Plugin management")}}function Zo(e,t,n){return{sessionId:e,...n?{assignedConversationId:n}:{},async write(r){await t.sendFireAndForget("terminal.input",{sessionId:e,bytesBase64:aw.encodeInput(r)})},async resize(r,i){await t.sendFireAndForget("terminal.resize",{sessionId:e,rows:r,cols:i})},detach(){t.detachTerminal(e)},async close(){await t.closeTerminalSession(e)}}}class nP{constructor(t,n){this.http=t,this.ws=n}health(t){return this.http.invoke("health",{request:t===void 0?null:{note:t}})}async onDomainEvent(t){return await this.ws.ensureConnected(),this.ws.setDomainEventHandler(t),()=>this.ws.clearDomainEventHandler()}pickFolder(){return ot("Native folder picker")}pickArchiveFile(){return ot("Native file picker")}onAppExitWorkGuard(t){return Promise.resolve(()=>{})}confirmAppExit(){return ot("Confirming an app exit")}}class rP{constructor(t){this.ws=t}async openTerminal(t,n){const r=await this.ws.openTerminal({cwd:t.cwd,rows:t.rows,cols:t.cols,nodeId:t.nodeId??null,onData:n});return Zo(r.sessionId,this.ws)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:Zo(r.sessionId,this.ws),scrollback:r.scrollback}}async closeTerminal(t){await this.ws.closeTerminalSession(t)}}class iP{constructor(t,n){this.http=t,this.ws=n}listAgents(t){return this.http.invoke("list_agents",{projectId:t})}listLiveAgents(t){return this.http.invoke("list_live_agents",{projectId:t})}listResumableAgents(t){return this.http.invoke("list_resumable_agents",{projectId:t}).then(n=>n.resumable)}attachLiveAgent(t,n,r){return this.http.invoke("attach_live_agent",{request:{projectId:t,agentId:n,nodeId:r}})}stopLiveAgent(t,n){return this.http.invoke("stop_live_agent",{request:{projectId:t,agentId:n}})}createAgent(t,n){return this.http.invoke("create_agent",{request:{projectId:t,name:n.name,profileId:n.profileId,initialContent:n.initialContent??null}})}changeAgentProfile(t,n,r,i,s){return this.http.invoke("change_agent_profile",{request:{projectId:t,agentId:n,profileId:r,rows:i,cols:s}})}readContext(t,n){return this.http.invoke("read_agent_context",{projectId:t,agentId:n})}async updateContext(t,n,r){await this.http.invoke("update_agent_context",{request:{projectId:t,agentId:n,content:r}})}async deleteAgent(t,n){await this.http.invoke("delete_agent",{projectId:t,agentId:n})}inspectConversation(t,n,r){return this.http.invoke("inspect_conversation",{request:{projectId:t,agentId:n,conversationId:r}})}async launchAgent(t,n,r,i){const s=await this.ws.launchAgent({projectId:t,agentId:n,nodeId:r.nodeId??null,rows:r.rows,cols:r.cols,conversationId:r.conversationId??null,onData:i});return Zo(s.sessionId,this.ws,s.assignedConversationId)}async reattach(t,n){const r=await this.ws.attachTerminal({sessionId:t,onData:n});return{handle:Zo(r.sessionId,this.ws),scrollback:r.scrollback}}}class sP{constructor(t,n){this.http=t,this.ws=n}create(t,n){return this.http.invoke("ticket_create",{request:{projectId:t,...n}})}read(t,n,r=!1){return this.http.invoke("ticket_read",{request:{projectId:t,ref:n,includeCarnet:r}})}list(t,n){const{statuses:r,priorities:i,...s}=n??{};return this.http.invoke("ticket_list",{request:{projectId:t,statuses:r??[],priorities:i??[],...s}})}update(t,n,r){return this.http.invoke("ticket_update",{request:{projectId:t,ref:n,...r}})}async delete(t,n){await this.http.invoke("ticket_delete",{request:{projectId:t,ref:n}})}readCarnet(t,n){return this.http.invoke("ticket_read_carnet",{request:{projectId:t,ref:n}})}updateCarnet(t,n,r,i){return this.http.invoke("ticket_update_carnet",{request:{projectId:t,ref:n,carnet:r,expectedVersion:i}})}link(t,n,r,i,s){return this.http.invoke("ticket_link",{request:{projectId:t,ref:n,targetRef:r,kind:i,expectedVersion:s}})}unlink(t,n,r,i,s){return this.http.invoke("ticket_unlink",{request:{projectId:t,ref:n,targetRef:r,expectedVersion:i,kind:s}})}assign(t,n,r,i,s){return this.http.invoke("ticket_assign",{request:{projectId:t,ref:n,agentId:r,assigned:i,expectedVersion:s}})}async listSprints(t){return(await this.http.invoke("sprint_list",{request:{projectId:t}})).items}setTicketSprint(t,n,r,i){return r===null?this.http.invoke("ticket_unassign_sprint",{request:{projectId:t,ref:n,expectedVersion:i}}):this.http.invoke("ticket_assign_sprint",{request:{projectId:t,ref:n,sprintId:r,expectedVersion:i}})}createSprint(t,n){return this.http.invoke("sprint_create",{request:{projectId:t,name:n}})}renameSprint(t,n,r,i){return this.http.invoke("sprint_rename",{request:{projectId:t,sprintId:n,name:r,expectedVersion:i}})}async reorderSprints(t,n){return(await this.http.invoke("sprint_reorder",{request:{projectId:t,orderedIds:n}})).items}async deleteSprint(t,n){await this.http.invoke("sprint_delete",{request:{projectId:t,sprintId:n}})}openTicketChat(t,n,r){return this.http.invoke("open_ticket_chat",{request:{projectId:t,issueRef:n,profileId:r}})}async closeTicketChat(t,n){await this.http.invoke("close_ticket_chat",{request:{projectId:t,issueRef:n}})}async sendTicketChat(t,n,r){const s=(await this.ws.send("chat.send",{sessionId:t,prompt:n})).payload;s&&s.chunk&&r(s.chunk)}}function lP(e){const t=typeof window<"u"&&window.location?window.location.origin:"http://localhost",n=e.baseUrl??t,r=e.wsUrl??n.replace(/^http(s?):\/\//,(i,s)=>`ws${s}://`);return{baseUrl:n,wsUrl:r}}function aP(e={}){const{baseUrl:t,wsUrl:n}=lP(e),r=ow();let i;const s=new N2({baseUrl:t,token:e.token,onUnauthorized:()=>{r.notifyUnauthorized(),i?.disconnect()}});return i=new aw({wsUrl:n,token:e.token,onReconnectFailed:()=>{s.invoke("health",{request:null}).catch(()=>{})}}),I2(i),{system:new nP(s,i),agent:new iP(s,i),input:new X2(s),terminal:new rP(i),project:new B2(s),layout:new z2(s),git:new F2(s),remote:new Z2,profile:new $2(s),modelServer:new W2(s),desktopServer:new eP,template:new H2(s),skill:new U2(s),memory:new q2(s),embedder:new V2(s),device:new O2(s),permission:new K2(s),workState:new G2(s),conversation:new Y2(s),ticket:new sP(s,i),window:new Q2,focusedProject:new J2,uiPreferences:new iw,plugin:new tP}}function oP(e){return"http"}const cw=g.createContext(null);function uw(){return oP()}function cP(){switch(uw()){case"mock":return C2();case"http":return aP();case"tauri":return UE()}}function uP({children:e,gateways:t}){const n=g.useMemo(()=>t??cP(),[t]);return a.jsx(cw.Provider,{value:n,children:e})}function fe(){const e=g.useContext(cw);if(!e)throw new Error("useGateways must be used within a ");return e}function up({cwd:e,open:t,reattach:n,sessionId:r,onSessionId:i,agentMode:s=!1,portal:l,onReady:o,refitSignal:c}){const{terminal:u}=fe(),h=g.useRef(null),[d,f]=g.useState(null),[p,m]=g.useState(!1),x=g.useRef(t);x.current=t;const w=g.useRef(n);w.current=n;const v=g.useRef(r);v.current=r;const _=g.useRef(i);_.current=i;const y=g.useRef(u);y.current=u;const b=g.useRef(s);b.current=s;const C=g.useRef(l);C.current=l;const S=g.useRef(o);S.current=o;const N=g.useRef(null);return g.useEffect(()=>{const R=h.current,D=y.current,k=x.current??D?.openTerminal.bind(D),L=w.current??D?.reattach.bind(D);if(!R||!k)return;f(null),m(!1);const A=new YN({convertEol:!1,cursorBlink:!0,fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'}),P=new JN;A.loadAddon(P);try{A.open(R)}catch{A.dispose();return}let I=!1,O=null;const U=new TextEncoder;let K=0,E=A.rows,F=A.cols,j=!1,re="";const V=A.onData(B=>{const de=C.current;b.current&&de&&(de.onHumanData(B),de.isSuspended())||(O?O.write(U.encode(B)):re+=B)});S.current?.({send:B=>{I||A.input(B)},focus:()=>{I||A.focus()}});const T=B=>{I||A.write(B)},ie=()=>{O&&(A.rows<=0||A.cols<=0||O.resize(A.rows,A.cols))},ee=B=>{if(I){B.detach();return}O=B,b.current&&C.current?.bindHandle(B),re&&(B.write(U.encode(re)),re=""),j&&ie()},J=B=>{if(!I){if(dP(B)==="AGENT_ALREADY_RUNNING"){A.write(`\r -\x1B[2mCellule disponible — l'agent est en cours dans une autre cellule.\x1B[0m\r -`);return}f(`Échec du lancement de l'agent : ${lx(B)}`),A.write(`\r -\x1B[31mfailed to open terminal: ${lx(B)}\x1B[0m\r -`)}},W=v.current;W&&L?L(W,T).then(({handle:B,scrollback:de})=>{if(I){B.detach();return}de.length>0&&A.write(de),ee(B)}).catch(()=>{I||k({cwd:e,rows:A.rows,cols:A.cols},T).then(B=>{_.current?.(B.sessionId),ee(B)}).catch(J)}):k({cwd:e,rows:A.rows,cols:A.cols},T).then(B=>{_.current?.(B.sessionId),ee(B)}).catch(J);const Y=8;let z=0;const ce=()=>{if(K=0,I)return;if(R.clientWidth===0||R.clientHeight===0){z{K&&cancelAnimationFrame(K),K=requestAnimationFrame(ce)},Pe=new ResizeObserver(we);return Pe.observe(R),we(),N.current=we,()=>{I=!0,N.current=null,K&&cancelAnimationFrame(K),Pe.disconnect(),V.dispose(),C.current?.unbindHandle(),O&&O.detach(),A.dispose()}},[e]),g.useEffect(()=>{c!==void 0&&N.current?.()},[c]),a.jsxs("div",{"data-testid":"terminal-view",style:{position:"relative",width:"100%",height:"100%",minHeight:"16rem"},children:[a.jsx("div",{ref:h,"data-testid":"terminal-xterm-container","aria-hidden":!p,style:{width:"100%",height:"100%",visibility:p?"visible":"hidden"}}),!p&&!d&&a.jsx("div",{"data-testid":"terminal-boot-placeholder","aria-live":"polite",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"#101214",color:"#9ca3af",fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',zIndex:1},children:"Préparation du terminal…"}),d&&a.jsx("div",{role:"alert","data-testid":"terminal-error",style:{position:"absolute",top:0,left:0,right:0,padding:"0.5rem 0.75rem",background:"rgba(120, 20, 20, 0.92)",color:"#fff",fontSize:13,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",zIndex:3},children:d})]})}function lx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function dP(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function hP({agentWasRunning:e,details:t,onResume:n,onNewConversation:r}){const i=e?"en cours":"clot";return a.jsx("div",{"data-testid":"resume-conversation-popup",role:"dialog","aria-label":"Reprise de conversation",style:{position:"absolute",inset:0,zIndex:5,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)"},children:a.jsxs("div",{style:{minWidth:260,maxWidth:360,padding:"16px 18px",background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:6,boxShadow:"0 8px 24px rgba(0, 0, 0, 0.5)",fontSize:13},children:[a.jsx("p",{style:{margin:"0 0 8px",fontWeight:600},children:"Reprise de conversation"}),a.jsxs("p",{style:{margin:"0 0 6px"},children:["Statut :"," ",a.jsx("span",{"data-testid":"resume-status",children:i})]}),t?.lastTopic&&a.jsxs("p",{style:{margin:"0 0 6px"},"data-testid":"resume-last-topic",children:["Dernier sujet : ",t.lastTopic]}),t?.tokenCount!==void 0&&a.jsxs("p",{style:{margin:"0 0 10px"},"data-testid":"resume-token-count",children:["Tokens : ",t.tokenCount]}),a.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[a.jsx("button",{type:"button",onClick:n,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Reprendre la dernière conversation"}),a.jsx("button",{type:"button",onClick:r,style:{flex:1,padding:"6px 10px",cursor:"pointer"},children:"Nouvelle conversation"})]})]})})}const Cu="\r",ax=350,fP=2e3,pP=512,mP=8,gP="[write-portal]",Ar=new TextEncoder;function xP(e){if(e.length===0)return!1;for(const t of e){const n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function vP(e,t){const{system:n,input:r}=fe(),[i,s]=g.useState(!1),l=g.useRef(0),o=g.useRef([]),c=g.useRef(null),u=g.useRef(!1),h=g.useRef(!1),d=g.useRef(null),f=g.useRef(null),p=g.useRef(r);p.current=r;const m=g.useRef(t);m.current=t;const x=g.useRef(e);x.current=e;const w=g.useRef(()=>{});w.current=()=>{const y=c.current&&d.current?d.current:null,b=f.current;b!==y&&(b&&(Ze("front-attached:set",{agent:b,attached:!1}),p.current?.setFrontAttached(b,!1).catch(C=>{Ze("front-attached:set-failed",{agent:b,attached:!1,error:ju(C)})})),y&&(Ze("front-attached:set",{agent:y,attached:!0}),p.current?.setFrontAttached(y,!0).catch(C=>{Ze("front-attached:set-failed",{agent:y,attached:!0,error:ju(C)})})),f.current=y)};const v=g.useRef(()=>{});return v.current=()=>{if(h.current)return;const y=o.current[0];if(!y||l.current>0)return;const b=c.current;if(!b)return;const C=m.current,S=x.current;if(!C)return;h.current=!0;const N=Date.now();u.current=!0,s(!0),(async()=>{let R=!1;try{Ze("inject:start",{agent:C,ticket:y.ticket,textBytes:Ar.encode(y.text).byteLength,queue:o.current.length,submitSequence:fo(y.submitSequence),submitDelayMs:y.submitDelayMs??ax}),await Promise.resolve();const D=l.current;D>0&&(Ze("inject:erase-human-window",{agent:C,ticket:y.ticket,count:D}),await b.write(Ar.encode("".repeat(D))),l.current=0),await _P(b,y.text,y.ticket);const k=y.submitDelayMs??ax;Ze("inject:before-submit-delay",{agent:C,ticket:y.ticket,delay:k}),await Oh(k);const L=yP(y.submitSequence,y.ticket);Ze("inject:submit-write:start",{agent:C,ticket:y.ticket,submitSequence:fo(L),submitBytes:Ar.encode(L).byteLength}),await b.write(Ar.encode(L)),Ze("inject:submit-write:ok",{agent:C,ticket:y.ticket}),o.current.shift(),R=!0;try{Ze("inject:ack:start",{agent:C,ticket:y.ticket}),await p.current.delegationDelivered(S,C,y.ticket),Ze("inject:ack:ok",{agent:C,ticket:y.ticket})}catch{Ze("inject:ack:failed",{agent:C,ticket:y.ticket})}}catch(D){Ze("inject:failed",{agent:C,ticket:y.ticket,error:ju(D)})}finally{const D=Date.now()-N,k=fP-D;k>0&&await Oh(k),u.current=!1,s(!1),h.current=!1,o.current.length>0&&R&&v.current()}})()},g.useEffect(()=>{if(!n||!t){d.current=null,w.current();return}let y,b=!1;const C=t;return n.onDomainEvent(S=>{S.type==="delegationReady"&&S.agentId===C&&(o.current.push({ticket:S.ticket,text:S.text,submitSequence:S.submitSequence,submitDelayMs:S.submitDelayMs}),Ze("event:delegation-ready",{agent:C,ticket:S.ticket,textBytes:Ar.encode(S.text).byteLength,queue:o.current.length,submitSequence:fo(S.submitSequence),submitDelayMs:S.submitDelayMs}),v.current())}).then(S=>{b?S():(y=S,d.current=C,Ze("event:subscribed",{agent:C}),w.current())}),()=>{b=!0,y?.(),d.current===C&&(d.current=null,Ze("event:unsubscribed",{agent:C})),f.current===C?(p.current?.setFrontAttached(C,!1).catch(()=>{}),f.current=null):w.current()}},[n,t]),{portal:g.useMemo(()=>({onHumanData(y){if(y==="\r"||y===` -`||y===""){l.current=0,v.current();return}xP(y)&&(l.current+=1)},isSuspended(){return u.current},bindHandle(y){c.current=y,Ze("handle:bound",{agent:m.current,sessionId:y.sessionId}),w.current(),v.current()},unbindHandle(){Ze("handle:unbound",{agent:m.current,sessionId:c.current?.sessionId}),c.current=null,w.current()}}),[]),overlay:i}}function Oh(e){return new Promise(t=>setTimeout(t,e))}async function _P(e,t,n){const r=bP(t,pP);for(let i=0;i0?e:(Ze("inject:empty-submit-sequence-defaulted",{ticket:t,defaultSubmitSequence:fo(Cu)}),Cu)}function bP(e,t){if(e.length===0)return[""];const n=[];let r="",i=0;for(const s of e){const l=Ar.encode(s).byteLength;r.length>0&&i+l>t&&(n.push(r),r="",i=0),r+=s,i+=l}return r.length>0&&n.push(r),n}function fo(e){return e==null?"":e.length===0?"":[...e].map(t=>{switch(t){case"\r":return"\\r";case` -`:return"\\n";case"":return"\\x7f";default:{const n=t.codePointAt(0);return n<32?`\\x${n.toString(16).padStart(2,"0")}`:t}}}).join("")}function ju(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Ze(e,t){console.info(gP,e,t)}function wP(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function ea(e){const{workState:t,system:n}=fe(),[r,i]=g.useState(null),[s,l]=g.useState(null),[o,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{i(await t.getProjectWorkState(e))}catch(h){l(wP(h))}finally{c(!1)}},[e,t]);return g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let h,d=!1;return n.onDomainEvent(f=>{(f.type==="agentLaunched"||f.type==="agentExited"||f.type==="agentBusyChanged"||f.type==="delegationReady"||f.type==="orchestratorRequestProcessed"||f.type==="backgroundTaskChanged"||f.type==="agentInboxChanged"||f.type==="agentWakeChanged")&&u()}).then(f=>{d?f():h=f}),()=>{d=!0,h?.()}},[u,n]),{state:r,error:s,busy:o,refresh:u}}const SP=50;function dw(){return{byTarget:{},nextSeq:1}}function kP(e,t,n=SP){const{target:r,ticketId:i}=t,s={...t,seq:e.nextSeq},l=e.byTarget[r]??{},c=[...l[i]??[],s],u=c.length>n?c.slice(c.length-n):c;return{byTarget:{...e.byTarget,[r]:{...l,[i]:u}},nextSeq:e.nextSeq+1}}function CP(e,t){if(!(t in e.byTarget))return e;const{[t]:n,...r}=e.byTarget;return{byTarget:r,nextSeq:e.nextSeq}}function hw(e,t){return e.atMs-t.atMs||e.seq-t.seq}function jP(e,t){const n=e.byTarget[t];return n?Object.values(n).flat().sort(hw):[]}function NP(e,t,n){const r=[];for(const i of Object.values(e.byTarget))for(const[s,l]of Object.entries(i))if(!(n!==void 0&&s!==n))for(const o of l)o.requester===t&&r.push(o);return r.sort(hw)}const EP=()=>{},PP=dw(),AP={},TP={index:PP,busy:AP,seedBusy:EP},dp=g.createContext(null);function LP({children:e}){const{system:t}=fe(),[n,r]=g.useState(dw),[i,s]=g.useState({}),l=g.useCallback((c,u)=>{s(h=>c in h?h:{...h,[c]:u})},[]);g.useEffect(()=>{if(!t)return;let c,u=!1;return t.onDomainEvent(h=>{if(h.type==="agentAnnouncement")r(d=>kP(d,{requester:h.requester,target:h.target,ticketId:h.ticketId,text:h.text,atMs:h.atMs}));else if(h.type==="agentBusyChanged"){const{agentId:d,busy:f}=h;s(p=>({...p,[d]:f})),f||r(p=>CP(p,d))}}).then(h=>{u?h():c=h}).catch(()=>{}),()=>{u=!0,c?.()}},[t]);const o=g.useMemo(()=>({index:n,busy:i,seedBusy:l}),[n,i,l]);return a.jsx(dp.Provider,{value:o,children:e})}function hp(){return g.useContext(dp)??TP}function DP(){return g.useContext(dp)!==null}function fw(e){const{index:t,busy:n}=hp();return g.useMemo(()=>({announcements:jP(t,e),active:n[e]===!0}),[t,n,e])}function RP(e,t){const{workState:n}=fe(),{seedBusy:r}=hp(),i=DP();g.useEffect(()=>{if(!i||!n)return;let s=!1;return n.getProjectWorkState(e).then(l=>{if(s)return;const o=l.agents.find(c=>c.agentId===t);o&&r(t,o.busy.state==="busy")}).catch(()=>{}),()=>{s=!0}},[i,n,e,t,r])}function MP(e,t){const{index:n}=hp();return g.useMemo(()=>NP(n,e,t),[n,e,t])}function q(...e){return e.filter(Boolean).join(" ")}function Me({size:e=16,className:t,label:n="Loading"}){return a.jsx("span",{role:"status","aria-label":n,className:q("inline-block animate-spin rounded-full border-2 border-current border-t-transparent",t),style:{width:e,height:e}})}const IP="inline-flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors select-none disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none",OP={sm:"h-7 px-2.5 text-xs",md:"h-9 px-3.5 text-sm"},BP={primary:"bg-primary text-on-primary hover:bg-primary-hover",secondary:"bg-raised text-content border border-border hover:border-border-strong",ghost:"text-muted hover:text-content hover:bg-raised",danger:"bg-danger text-white hover:brightness-110"},M=g.forwardRef(function({variant:t="secondary",size:n="md",loading:r=!1,disabled:i,className:s,children:l,...o},c){return a.jsxs("button",{ref:c,type:o.type??"button",disabled:i||r,className:q(IP,OP[n],BP[t],s),...o,children:[r&&a.jsx(Me,{size:n==="sm"?12:14}),l]})}),zP={sm:"h-6 w-6 text-xs",md:"h-8 w-8 text-sm"},ir=g.forwardRef(function({size:t="md",className:n,children:r,...i},s){return a.jsx("button",{ref:s,type:i.type??"button",className:q("inline-flex items-center justify-center rounded-md text-muted transition-colors","hover:bg-raised hover:text-content focus-visible:outline-none","disabled:opacity-50 disabled:cursor-not-allowed",zP[t],n),...i,children:r})}),oe=g.forwardRef(function({invalid:t=!1,className:n,...r},i){return a.jsx("input",{ref:i,"aria-invalid":t||void 0,className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border placeholder:text-faint outline-none transition-colors",t?"border-danger":"border-border focus:border-primary","disabled:opacity-50 disabled:cursor-not-allowed",n),...r})});function qt({label:e,hint:t,error:n,hideLabel:r,className:i,children:s}){const l=g.useId(),o=`${l}-msg`,c=n??t;return a.jsxs("div",{className:q("flex flex-col gap-1",i),children:[a.jsx("label",{htmlFor:l,className:q("text-xs font-medium text-muted",r&&"sr-only"),children:e}),s({id:l,describedBy:c?o:void 0}),c&&a.jsx("p",{id:o,role:n?"alert":void 0,className:q("text-xs",n?"text-danger":"text-faint"),children:c})]})}function Se({title:e,actions:t,flush:n,className:r,children:i,...s}){const l=e!=null||t!=null;return a.jsxs("section",{className:q("rounded-lg border border-border bg-surface",r),...s,children:[l&&a.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-2.5",children:[typeof e=="string"?a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}):e,t]}),a.jsx("div",{className:q(!n&&"p-4"),children:i})]})}function FP({items:e,value:t,onSelect:n,onClose:r,className:i}){return a.jsx("div",{role:"tablist",className:q("flex flex-wrap items-stretch gap-1",i),children:e.map(s=>{const l=s.id===t;return a.jsxs("div",{className:q("group flex items-center gap-1 rounded-md border px-1 transition-colors",l?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[a.jsx("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>n(s.id),className:q("px-2 py-1 text-sm focus-visible:outline-none",l?"font-semibold text-content":"text-muted hover:text-content"),children:s.label}),r&&a.jsx(ir,{size:"sm","aria-label":`close ${s.label}`,onClick:()=>r(s.id),className:"opacity-60 group-hover:opacity-100",children:"×"})]},s.id)})})}const $P={start:"justify-start",between:"justify-between",end:"justify-end"};function pw({justify:e="start",className:t,children:n,...r}){return a.jsx("div",{role:"toolbar",className:q("flex items-center gap-2",$P[e],t),...r,children:n})}const kn={menuDropdown:40,floatingWindow:50,floatingWindowNested:60,toast:70},WP={sm:"max-w-sm",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"},ox='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',Us=[];function Bh({open:e,title:t,onClose:n,size:r="md",children:i}){return e?a.jsx(HP,{title:t,onClose:n,size:r,children:i}):null}function HP({title:e,onClose:t,size:n,children:r}){const i=g.useRef(null),s=g.useRef(t);return s.current=t,g.useEffect(()=>{const l=document.activeElement,o=i.current,c={};Us.push(c);const u=()=>Us[Us.length-1]===c;(o?.querySelector(ox)??o)?.focus();function d(f){if(!u())return;if(f.key==="Escape"){f.preventDefault(),s.current();return}if(f.key!=="Tab"||!o)return;const p=Array.from(o.querySelectorAll(ox));if(p.length===0){f.preventDefault(),o.focus();return}const m=p[0],x=p[p.length-1],w=document.activeElement;f.shiftKey&&w===m?(f.preventDefault(),x.focus()):!f.shiftKey&&w===x&&(f.preventDefault(),m.focus())}return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d);const f=Us.indexOf(c);f>=0&&Us.splice(f,1),l?.focus?.()}},[]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:kn.floatingWindow},onMouseDown:l=>{l.target===l.currentTarget&&t()},children:a.jsxs("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":e,tabIndex:-1,className:q("flex max-h-[80vh] w-full flex-col overflow-hidden rounded-lg","border border-border bg-surface shadow-xl outline-none",WP[n??"md"]),children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:e}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`close ${e}`,onClick:t,children:"Close"})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})})}function UP({menus:e,className:t}){const[n,r]=g.useState(null),[i,s]=g.useState(null),l=g.useRef(null);function o(){r(null),s(null)}return g.useEffect(()=>{if(n===null)return;function c(h){l.current?.contains(h.target)||o()}function u(h){h.key==="Escape"&&o()}return document.addEventListener("mousedown",c),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("keydown",u)}},[n]),a.jsx("div",{ref:l,className:q("flex shrink-0 items-center gap-0.5 border-b border-border bg-surface px-2 py-1",t),children:e.map(c=>{const u=n===c.id;return a.jsxs("div",{className:"relative",children:[a.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":u,onClick:()=>{s(null),r(h=>h===c.id?null:c.id)},className:q("rounded px-2.5 py-1 text-sm transition-colors",u?"bg-raised text-content":"text-muted hover:bg-raised hover:text-content"),children:c.label}),u&&a.jsx("div",{role:"menu","aria-label":c.label,style:{zIndex:kn.menuDropdown},className:q("absolute left-0 top-full mt-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:c.items.map(h=>{const d=(h.submenu?.length??0)>0,f=d&&i===h.id;return a.jsxs("div",{className:"relative",onMouseEnter:()=>s(d?h.id:null),children:[a.jsxs("button",{type:"button",disabled:h.disabled,"aria-haspopup":d?"menu":void 0,"aria-expanded":d?f:void 0,onClick:()=>{if(d){s(p=>p===h.id?null:h.id);return}h.onSelect(),o()},className:q("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[a.jsx("span",{children:h.label}),d?a.jsx("span",{"aria-hidden":!0,className:"text-muted",children:h.active?"● ▸":"▸"}):h.active&&a.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]}),f&&a.jsx("div",{role:"menu","aria-label":h.label,style:{zIndex:kn.floatingWindowNested},className:q("absolute left-full top-0 ml-1 min-w-44 rounded-md border border-border","bg-surface py-1 shadow-xl"),children:h.submenu.map(p=>a.jsxs("button",{type:"button",disabled:p.disabled,onClick:()=>{p.onSelect(),o()},className:q("flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors","text-content hover:bg-raised","disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[a.jsx("span",{children:p.label}),p.active&&a.jsx("span",{"aria-hidden":!0,className:"text-primary",children:"●"})]},p.id))})]},h.id)})})]},c.id)})})}const qP=240,VP=720;function cx({side:e,width:t,onResize:n,minWidth:r=qP,maxWidth:i=VP,"aria-label":s,children:l}){const o=g.useRef(null);function c(p){return Math.min(i,Math.max(r,p))}function u(p){p.preventDefault(),p.currentTarget.setPointerCapture?.(p.pointerId),o.current={startX:p.clientX,startWidth:t}}function h(p){const m=o.current;if(!m)return;const x=p.clientX-m.startX,w=e==="left"?x:-x;n(c(m.startWidth+w))}function d(p){if(!o.current)return;const m=p.clientX-o.current.startX,x=e==="left"?m:-m;o.current=null,n(c(t+x))}const f=a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":`resize ${e} dock`,onPointerDown:u,onPointerMove:h,onPointerUp:d,className:"shrink-0 cursor-col-resize bg-border hover:bg-border-strong",style:{flex:"0 0 4px",touchAction:"none"}});return a.jsxs("aside",{"aria-label":s??`${e} dock`,className:q("flex h-full shrink-0 bg-surface",e==="left"?"flex-row border-r border-border":"flex-row-reverse border-l border-border"),style:{width:t},children:[a.jsx("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:l}),f]})}function KP(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleTimeString()}catch{return""}}function GP({projectId:e,agentId:t}){RP(e,t);const{announcements:n,active:r}=fw(t),i=g.useRef(null);return g.useEffect(()=>{const s=i.current;s&&(s.scrollTop=s.scrollHeight)},[n]),r?a.jsxs("div",{"data-testid":"target-announcements-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-[4] flex flex-col bg-canvas/85 backdrop-blur-sm",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-surface/80 px-4 py-2",children:[a.jsx(Me,{size:14}),a.jsx("span",{className:"text-sm font-medium text-content",children:"Un agent est en train de lui parler…"})]}),a.jsx("div",{ref:i,className:"flex flex-1 flex-col justify-end gap-1.5 overflow-hidden px-6 py-4",children:n.map(s=>{const l=KP(s.atMs);return a.jsxs("div",{className:"flex items-baseline gap-2 text-sm text-muted",children:[l&&a.jsx("span",{className:"shrink-0 text-xs text-faint",children:l}),a.jsx("span",{className:"whitespace-pre-wrap break-words text-content/90",children:s.text})]},s.seq)})})]}):null}function YP({requester:e,ticketId:t,limit:n=3}){const r=MP(e,t);if(r.length===0)return null;const i=r.slice(Math.max(0,r.length-n));return a.jsxs("div",{"data-testid":"announcements-preview",className:"flex flex-col gap-1 rounded-md border border-primary/25 bg-primary/5 px-2.5 py-1.5",children:[a.jsxs("span",{className:"flex items-center gap-1.5 text-[0.65rem] font-medium uppercase tracking-wide text-primary",children:[a.jsx("span",{"aria-hidden":!0,className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-primary"}),"En attente d'un agent"]}),a.jsx("ul",{className:"flex flex-col gap-0.5",children:i.map(s=>a.jsx("li",{className:"truncate text-xs text-muted",title:s.text,children:s.text},s.seq))})]})}class XP{constructor(t,n){X(this,"handlers",new Map);this.pluginId=t,this.declaredCommandIds=n}register(t,n){if(!this.declaredCommandIds.has(t))throw new Error(`plugin "${this.pluginId}" tried to register command "${t}" which is not declared by any menu item in its manifest`);return this.handlers.set(t,n),{dispose:()=>{this.handlers.get(t)===n&&this.handlers.delete(t)}}}async run(t,...n){const r=this.handlers.get(t);r&&await r(...n)}has(t){return this.handlers.has(t)}}class QP{constructor(t,n){X(this,"components",new Map);this.pluginId=t,this.declaredLayoutTypes=n}register(t){if(!this.declaredLayoutTypes.has(t.type))throw new Error(`plugin "${this.pluginId}" tried to register layout type "${t.type}" which is not declared in its manifest`);return this.components.set(t.type,t.component),{dispose:()=>{this.components.get(t.type)===t.component&&this.components.delete(t.type)}}}get(t){return this.components.get(t)}}class JP{constructor(t){this.pluginId=t}get ownerPluginId(){return this.pluginId}}class fp{constructor(){X(this,"loaded",new Map)}add(t){this.loaded.set(t.pluginId,t)}async remove(t){const n=this.loaded.get(t);if(n)try{await n.dispose()}finally{this.loaded.delete(t)}}get(t){return this.loaded.get(t)}list(){return[...this.loaded.values()]}topLevelMenus(){return this.list().flatMap(t=>t.contributes.menus.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,menu:n})))}menuItems(){return this.list().flatMap(t=>t.contributes.menuItems.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,item:n})))}layoutComponent(t,n){return this.loaded.get(t)?.layouts.get(n)}layoutContributions(){return this.list().flatMap(t=>t.contributes.layouts.map(n=>({pluginId:t.pluginId,pluginDisplayName:t.displayName,layout:n})))}async runCommand(t,n,...r){await this.loaded.get(t)?.commands.run(n,...r)}}function ZP(e){return typeof e=="object"&&e!==null&&"activate"in e&&typeof e.activate=="function"}async function eA(e,t){try{const n=await import(e.bundleUrl);if(!ZP(n))return{failure:{pluginId:e.id,reason:'bundle does not export an "activate(ctx)" function'}};const r=new Set(e.contributes.menuItems.map(d=>d.command)),i=new Set(e.contributes.layouts.map(d=>d.type)),s=new XP(e.id,r),l=new QP(e.id,i),o=new JP(e.id),c={pluginId:e.id,pluginDisplayName:e.displayName,version:e.version,commands:s,layouts:l,menu:o,...t},u=await n.activate(c);return{plugin:{pluginId:e.id,displayName:e.displayName,contributes:e.contributes,commands:s,layouts:l,menu:o,dispose:async()=>{try{await u.dispose?.()}catch{}}}}}catch(n){return{failure:{pluginId:e.id,reason:n instanceof Error?n.message:String(n)}}}}async function tA(e,t){const n=new fp,r=[],i=await Promise.all(e.map(s=>eA(s,t)));for(const s of i)"failure"in s?r.push(s.failure):n.add(s.plugin);return{registry:n,failures:r}}const nA=new Set(["projectOpen","gitRepository","agentSelected","terminalFocused","layoutCellFocused"]);function rA(e){const t=[];let n=0;for(;n=this.tokens.length}}function sA(e,t){if(e===void 0||e.trim()==="")return{ok:!0,value:!0};const n=rA(e);if(!n)return{ok:!1,reason:`invalid "when" expression: ${e}`};try{const r=new iA(n),i=r.parseOr(t);if(!r.finished())throw new Error("unexpected trailing tokens");return{ok:!0,value:i}}catch(r){const i=r instanceof Error?r.message:String(r);return{ok:!1,reason:`invalid "when" expression "${e}": ${i}`}}}const lA={registry:new fp,failures:[],loading:!1},mw=g.createContext(lA);function aA({children:e,value:t}){const n=fe(),[r,i]=g.useState(t??{registry:new fp,failures:[],loading:!0});return g.useEffect(()=>{if(t)return;let s=!1;return n.plugin.listRuntimeContributions().then(l=>tA(l.plugins,{project:n.project,git:n.git,terminal:n.terminal,agents:n.agent,system:n.system})).then(l=>{s||i({registry:l.registry,failures:l.failures,loading:!1})}).catch(()=>{s||i(l=>({...l,loading:!1}))}),()=>{s=!0}},[]),a.jsx(mw.Provider,{value:r,children:e})}function pp(){return g.useContext(mw)}function ux({title:e,body:t,confirmLabel:n,danger:r=!1,busy:i=!1,onConfirm:s,onCancel:l}){const o=g.useRef(null);return g.useEffect(()=>{o.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.floatingWindow},onClick:l,children:a.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-md flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"whitespace-pre-line text-sm text-muted",children:t}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{ref:o,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),a.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:i,onClick:()=>void s(),children:n})]})]})})}function ei(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function oA(){const{plugin:e,system:t}=fe(),[n,r]=g.useState([]),[i,s]=g.useState(null),[l,o]=g.useState(!1),c=g.useCallback(async()=>{o(!0),s(null);try{r(await e.listPlugins())}catch(y){s(ei(y))}finally{o(!1)}},[e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async y=>{o(!0),s(null);try{return await e.reviewPackage(y)}catch(b){return s(ei(b)),null}finally{o(!1)}},[e]),h=g.useCallback(y=>u({sourceKind:"archive",path:y}),[u]),d=g.useCallback(y=>u({sourceKind:"directory",path:y}),[u]),f=g.useCallback(async y=>{o(!0),s(null);try{const b=await e.installFromArchive(y);return r(C=>[...C.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return s(ei(b)),!1}finally{o(!1)}},[e]),p=g.useCallback(async y=>{o(!0),s(null);try{const b=await e.installFromDirectory(y);return r(C=>[...C.filter(S=>S.id!==b.plugin.id),b.plugin]),!0}catch(b){return s(ei(b)),!1}finally{o(!1)}},[e]),m=g.useCallback(async(y,b)=>{o(!0),s(null);try{const C=await e.setEnabled(y,b);r(S=>S.map(N=>N.id===y?C:N))}catch(C){s(ei(C))}finally{o(!1)}},[e]),x=g.useCallback(async y=>{o(!0),s(null);try{await e.uninstall(y),r(b=>b.filter(C=>C.id!==y))}catch(b){s(ei(b))}finally{o(!1)}},[e]),w=g.useCallback(async y=>{try{await e.openPluginsFolder(y)}catch(b){s(ei(b))}},[e]),v=g.useCallback(()=>t.pickArchiveFile(),[t]),_=g.useCallback(()=>t.pickFolder(),[t]);return{plugins:n,error:i,busy:l,refresh:c,reviewArchive:h,reviewDirectory:d,installFromArchive:f,installFromDirectory:p,setEnabled:m,uninstall:x,openPluginsFolder:w,pickArchiveFile:v,pickDirectory:_}}const cA={enabled:"Activé",disabled:"Désactivé","pending-enable":"Activation en attente","pending-disable":"Désactivation en attente","pending-uninstall":"Désinstallation en attente",invalid:"Invalide"};function uA(){const e=oA(),[t,n]=g.useState(null),[r,i]=g.useState(null),[s,l]=g.useState(null);async function o(){l(null);const d=await e.pickArchiveFile();if(!d)return;const f=await e.reviewArchive(d);if(!f){l("La revue du paquet a échoué.");return}i({sourceKind:"archive",path:d,review:f})}async function c(){l(null);const d=await e.pickDirectory();if(!d)return;const f=await e.reviewDirectory(d);if(!f){l("La revue du paquet a échoué.");return}i({sourceKind:"directory",path:d,review:f})}async function u(){if(!r)return;(r.sourceKind==="archive"?await e.installFromArchive(r.path):await e.installFromDirectory(r.path))&&i(null)}async function h(){t&&(t.kind==="disable"?await e.setEnabled(t.plugin.id,!1):await e.uninstall(t.plugin.id),n(null))}return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:"Plugins"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{size:"sm",onClick:()=>void o(),disabled:e.busy,children:"Installer depuis une archive…"}),a.jsx(M,{size:"sm",variant:"secondary",onClick:()=>void c(),disabled:e.busy,children:"Installer depuis un dossier…"})]})]}),(e.error||s)&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error??s}),e.plugins.length===0?a.jsx(Se,{children:a.jsx("p",{className:"text-sm text-muted",children:"Aucun plugin installé."})}):a.jsx("ul",{className:"flex flex-col gap-2",children:e.plugins.map(d=>a.jsx("li",{children:a.jsxs(Se,{className:"flex items-center justify-between gap-4",children:[a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:d.displayName}),a.jsxs("span",{className:"text-xs text-faint",children:["v",d.version]}),d.publisher&&a.jsxs("span",{className:"text-xs text-faint",children:["· ",d.publisher]}),a.jsx("span",{className:"rounded bg-raised px-1.5 py-0.5 text-[0.65rem] uppercase text-muted",children:"full-trust"})]}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted",children:[a.jsx("span",{"aria-label":"plugin state",className:d.lifecycleState==="invalid"?"text-danger":void 0,children:cA[d.lifecycleState]}),d.restartRequired&&a.jsx("span",{className:"text-warning",children:"Redémarrage requis"}),d.sourceLabel&&a.jsxs("span",{children:["· ",d.sourceLabel]})]}),d.error&&a.jsx("p",{className:"text-xs text-danger",role:"alert",children:d.error})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[d.enabled?a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>n({kind:"disable",plugin:d}),disabled:e.busy,children:"Désactiver"}):a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.setEnabled(d.id,!0),disabled:e.busy,children:"Activer"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void e.openPluginsFolder(d.id),disabled:e.busy,children:"Ouvrir le dossier"}),a.jsx(M,{size:"sm",variant:"danger",onClick:()=>n({kind:"uninstall",plugin:d}),disabled:e.busy,children:"Désinstaller"})]})]})},d.id))}),r&&a.jsx(ux,{title:`Installer "${r.review.displayName}" ?`,body:dA(r.review),confirmLabel:r.review.installable?"Installer":"Corriger avant d'installer",busy:e.busy,danger:!r.review.installable,onConfirm:()=>{r.review.installable?u():i(null)},onCancel:()=>i(null)}),t&&a.jsx(ux,{title:t.kind==="disable"?`Désactiver "${t.plugin.displayName}" ?`:`Désinstaller "${t.plugin.displayName}" ?`,body:t.kind==="disable"?"Ses contributions seront masquées immédiatement ; un redémarrage sera peut-être nécessaire pour purger complètement le plugin.":"Le plugin, ses fichiers et ses contributions seront supprimés après redémarrage.",confirmLabel:t.kind==="disable"?"Désactiver":"Désinstaller",danger:t.kind==="uninstall",busy:e.busy,onConfirm:()=>void h(),onCancel:()=>n(null)})]})}function dA(e){const{contributionSummary:t}=e;return[`Éditeur : ${e.publisher??"inconnu"}`,`Version : ${e.version}`,e.description??null,"Confiance : full-trust — ce plugin peut exécuter du code arbitraire dans IdeA.",`Contributions : ${t.topLevelMenus} menu(s), ${t.menuItems} item(s), ${t.layouts} layout(s), ${t.mcpServers} serveur(s) MCP.`,...e.issues.map(r=>`${r.severity==="error"?"Erreur":"Avertissement"} : ${r.message}`)].filter(r=>!!r).join(` -`)}function hA(e){return e.topLevelMenus().map(({pluginId:t,pluginDisplayName:n,menu:r})=>({id:`plugin:${r.id}`,pluginId:t,pluginDisplayName:n,label:r.label,icon:r.icon,order:r.order??0})).sort((t,n)=>t.order-n.order||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.label.localeCompare(n.label))}function fA(e,t,n){return e.menuItems().filter(({item:r})=>r.targetMenuId===t).map(({pluginId:r,pluginDisplayName:i,item:s})=>{const l=sA(s.when,n);return{id:s.id,pluginId:r,pluginDisplayName:i,targetMenuId:s.targetMenuId,label:s.label,command:s.command,enabled:l.ok?l.value:!1,disabledReason:l.ok?void 0:l.reason,groupLabel:i,order:s.order??0,iconUrl:s.icon}}).sort((r,i)=>r.order-i.order||r.pluginDisplayName.localeCompare(i.pluginDisplayName)||r.label.localeCompare(i.label))}function pA(e,t){const n=g.useMemo(()=>(s,l)=>e.runCommand(s,l),[e]),r=g.useMemo(()=>s=>fA(e,s,t).map(l=>({id:l.id,label:`${l.label} · ${l.pluginDisplayName}`,disabled:!l.enabled,onSelect:()=>{n(l.pluginId,l.command)}})),[e,t,n]);return{topLevelMenus:g.useMemo(()=>hA(e).map(s=>({id:s.id,label:s.label,items:r(s.id)})),[e,r]),itemsFor:r,runCommand:n}}function mA(e,t,n){const r=e.get(t.pluginId);if(!r){const l=n?.find(o=>o.id===t.pluginId);return l&&!l.enabled?"plugin-disabled":"plugin-missing"}return!r.contributes.layouts.some(l=>l.type===t.layoutType)||!r.layouts.get(t.layoutType)?"incompatible":"available"}const gA={"plugin-disabled":"Le plugin fournisseur est désactivé.","plugin-missing":"Le plugin fournisseur n'est pas installé.",incompatible:"Le plugin fournisseur ne déclare plus ce type de layout."};function xA({cell:e,availability:t,providerDisplayName:n,onOpenPlugins:r,onChooseAnotherLayout:i}){return a.jsxs(Se,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[a.jsx("p",{className:"text-sm font-semibold text-content",children:"Layout indisponible"}),a.jsx("p",{className:"text-xs text-muted",children:gA[t]}),a.jsxs("p",{className:"text-xs text-faint",children:["Fourni par « ",n??e.pluginId," »"]}),a.jsxs("div",{className:"mt-2 flex gap-2",children:[a.jsx(M,{size:"sm",variant:"secondary",onClick:r,children:"Ouvrir Plugins"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:i,children:"Choisir un autre layout"})]})]})}function vA({projectId:e,cell:t,installedPlugins:n,onStateChange:r,onOpenPlugins:i,onChooseAnotherLayout:s}){const{registry:l}=pp(),o=fe(),c=mA(l,t,n);if(c!=="available"){const h=l.get(t.pluginId)?.displayName??n?.find(d=>d.id===t.pluginId)?.displayName;return a.jsx(xA,{cell:t,availability:c,providerDisplayName:h,onOpenPlugins:i,onChooseAnotherLayout:s})}const u=l.layoutComponent(t.pluginId,t.layoutType);return a.jsx(u,{projectId:e,nodeId:t.id,layoutType:t.layoutType,state:t.state,setState:r,availability:"available",gateways:{project:o.project,git:o.git,terminal:o.terminal,agents:o.agent,system:o.system}})}function _A(e){return e.layoutContributions().map(({pluginId:t,pluginDisplayName:n,layout:r})=>({pluginId:t,pluginDisplayName:n,layout:r})).sort((t,n)=>(t.layout.order??0)-(n.layout.order??0)||t.pluginDisplayName.localeCompare(n.pluginDisplayName)||t.layout.label.localeCompare(n.layout.label))}function yA({registry:e,onSelect:t}){const n=_A(e);return n.length===0?null:a.jsxs("div",{role:"group","aria-label":"Layouts plugins",children:[a.jsx("p",{className:"px-3 pt-2 text-[0.65rem] font-semibold uppercase tracking-wide text-faint",children:"Layouts plugins"}),n.map(r=>a.jsxs("button",{type:"button",role:"menuitem","aria-label":`create ${r.layout.label} layout`,onClick:()=>t(r),className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm text-content hover:bg-raised",children:[a.jsx("span",{children:r.layout.label}),a.jsx("span",{className:"text-xs text-faint",children:r.pluginDisplayName})]},`${r.pluginId}:${r.layout.type}`))]})}function dx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function bA(e){const{template:t}=fe(),[n,r]=g.useState([]),[i,s]=g.useState(!1),[l,o]=g.useState(null),c=g.useCallback(async()=>{s(!0),o(null);try{const d=await t.detectDrift(e);r(d)}catch(d){o(dx(d))}finally{s(!1)}},[t,e]);g.useEffect(()=>{c()},[c]);const u=g.useCallback(async(d,f)=>{s(!0),o(null);try{await t.syncAgent(e,d),f&&await f();const p=await t.detectDrift(e);r(p)}catch(p){o(dx(p))}finally{s(!1)}},[t,e]);return{driftByAgentId:new Map(n.map(d=>[d.agentId,d])),driftBusy:i,driftError:l,refreshDrift:c,syncAgent:u}}function Bn(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function wA(e){const{agent:t,profile:n,system:r,terminal:i,input:s}=fe(),[l,o]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState([]),[w,v]=g.useState(null),[_,y]=g.useState(!1),[b,C]=g.useState(null),[S,N]=g.useState({}),[R,D]=g.useState({}),[k,L]=g.useState({}),[A,P]=g.useState({}),I=g.useCallback(async()=>{y(!0),v(null);try{const[ee,J]=await Promise.all([t.listAgents(e),n.listProfiles()]);o(ee),p(J)}catch(ee){v(Bn(ee))}finally{y(!1)}},[t,n,e]),O=g.useCallback(async()=>{try{x(await t.listLiveAgents(e))}catch{x([])}},[t,e]);g.useEffect(()=>{I()},[I]),g.useEffect(()=>{O()},[O]),g.useEffect(()=>{if(!r)return;let ee,J=!1;return r.onDomainEvent(W=>{if((W.type==="agentLaunched"||W.type==="agentExited"||W.type==="agentProfileChanged")&&(I(),O()),W.type==="agentLaunched"&&P(Y=>{if(!(W.agentId in Y))return Y;const{[W.agentId]:z,...ce}=Y;return ce}),W.type==="orchestratorRequestProcessed"&&W.source!==void 0){const{requesterId:Y,source:z}=W;N(ce=>ce[Y]===z?ce:{...ce,[Y]:z})}switch(W.type){case"agentRateLimited":D(Y=>({...Y,[W.agentId]:{limitedUntil:W.resetsAtMs,resumeFireAt:Y[W.agentId]?.resumeFireAt,suspected:!1}}));break;case"agentResumeScheduled":D(Y=>({...Y,[W.agentId]:{...Y[W.agentId],resumeFireAt:W.fireAtMs}}));break;case"agentResumeCancelled":D(Y=>{const z=Y[W.agentId];if(!z)return Y;const{resumeFireAt:ce,...we}=z;return{...Y,[W.agentId]:we}});break;case"agentResumed":D(Y=>{if(!(W.agentId in Y))return Y;const{[W.agentId]:z,...ce}=Y;return ce});break;case"agentRateLimitSuspected":D(Y=>({...Y,[W.agentId]:{...Y[W.agentId],limitedUntil:W.resetsAtMs,suspected:!0}}));break;case"modelServerStatusChanged":L(Y=>({...Y,[W.serverId]:W.status}));break;case"agentLaunchFailed":P(Y=>({...Y,[W.agentId]:{cause:W.cause,code:W.code,message:W.message}}));break}}).then(W=>{J?W():ee=W}),()=>{J=!0,ee?.()}},[r,I,O]);const U=g.useCallback(async(ee,J,W)=>{y(!0),v(null);try{const Y=await t.createAgent(e,{name:ee,profileId:J,initialContent:W});o(z=>[...z,Y])}catch(Y){v(Bn(Y))}finally{y(!1)}},[t,e]),K=g.useCallback(async ee=>{y(!0),v(null);try{const J=await t.readContext(e,ee);u(ee),d(J)}catch(J){v(Bn(J))}finally{y(!1)}},[t,e]),E=g.useCallback(async ee=>{if(c){y(!0),v(null);try{await t.updateContext(e,c,ee),d(ee)}catch(J){v(Bn(J))}finally{y(!1)}}},[t,e,c]),F=g.useCallback(async(ee,J,W,Y)=>{y(!0),v(null);try{const{agent:z,relaunchedSession:ce}=await t.changeAgentProfile(e,ee,J,W,Y);return o(we=>we.map(Pe=>Pe.id===z.id?z:Pe)),O(),ce}catch(z){v(Bn(z));return}finally{y(!1)}},[t,e,O]),j=g.useCallback(async ee=>{y(!0),v(null);try{await t.deleteAgent(e,ee),o(J=>J.filter(W=>W.id!==ee)),u(J=>J===ee?null:J),c===ee&&d(""),C(J=>J===ee?null:J)}catch(J){v(Bn(J))}finally{y(!1)}},[t,e,c]),re=g.useCallback(async(ee,J,W)=>{v(null);try{const Y=await t.launchAgent(e,ee,J,W);return C(ee),O(),Y}catch(Y){throw v(Bn(Y)),Y}},[t,e,O]),V=g.useCallback(async ee=>{const J=ee??b,W=J?m.find(Y=>Y.agentId===J):null;if(C(Y=>Y===J||!J?null:Y),W?.sessionId)try{await i?.closeTerminal(W.sessionId),x(Y=>Y.filter(z=>z.agentId!==J))}catch(Y){v(Bn(Y)),await O()}},[m,O,b,i]),T=g.useCallback(async ee=>{D(J=>{const W=J[ee];if(!W?.resumeFireAt)return J;const{resumeFireAt:Y,...z}=W;return{...J,[ee]:z}});try{return await s?.cancelResume(ee)??!1}catch(J){return v(Bn(J)),!1}},[s]),ie=g.useCallback(async(ee,J)=>{try{await s?.setResumeAt(ee,J)}catch(W){v(Bn(W))}},[s]);return{agents:l,selectedAgentId:c,context:h,profiles:f,liveAgents:m,delegationSourceByRequester:S,limitByAgent:R,modelServerStatusByServer:k,launchFailureByAgent:A,error:w,busy:_,runningAgentId:b,refresh:I,refreshLiveAgents:O,createAgent:U,selectAgent:K,saveContext:E,changeAgentProfile:F,deleteAgent:j,launchAgent:re,stopAgent:V,cancelResume:T,setResumeAt:ie}}function gw(e,t,n){if(!e)return;const r=t.find(i=>i.id===e.profileId)?.opencode?.localModelServerId;return r?n[r]:void 0}function SA(e){if(!e)return null;switch(e.state){case"downloading":return"Téléchargement du modèle…";case"starting":case"probing":return"Chargement du serveur…";default:return null}}function Nu(e){if(!Number.isFinite(e)||e<=0)return"0 o";const t=["o","Ko","Mo","Go","To"];let n=e,r=0;for(;n>=1e3&&r{t&&t.listProfiles().then(i).catch(()=>{})},[t]);return g.useEffect(()=>{o()},[o]),g.useEffect(()=>{if(!n)return;let u,h=!1;return n.onDomainEvent(d=>{d.type==="modelServerStatusChanged"?l(f=>({...f,[d.serverId]:d.status})):d.type==="agentProfileChanged"&&o()}).then(d=>{h?d():u=d}),()=>{h=!0,u?.()}},[n,o]),{statusForAgent:g.useCallback(u=>gw(u,r,s),[r,s])}}function jA(e,t){const n=/^(\d{1,2}):(\d{2})$/.exec(e.trim());if(!n)return null;const r=Number(n[1]),i=Number(n[2]);if(r>23||i>59)return null;const s=new Date(t);return s.setHours(r,i,0,0),s.getTime()}function NA(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function EA(e){const t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function PA({state:e,onCancelResume:t,onSetResumeAt:n,busy:r=!1}){const{limitedUntil:i,resumeFireAt:s,suspected:l}=e,[o,c]=g.useState(()=>Date.now());g.useEffect(()=>{if(s===void 0)return;const m=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(m)},[s]);const[u,h]=g.useState(""),d=l===!0&&i===void 0&&s===void 0;function f(m){m.preventDefault();const x=jA(u,Date.now());x!==null&&(n(x),h(""))}const p=i!==void 0?`limité jusqu'à ${NA(i)}`:"limité";return a.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[a.jsx("span",{"aria-label":"session limit",title:l?"Limite de session détectée sans heure fiable":"Limite de session atteinte",className:q("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:p}),d&&a.jsxs("form",{onSubmit:f,className:"flex items-center gap-2","aria-label":"resume time form",children:[a.jsx("span",{className:"text-xs text-muted",role:"note",children:"heure inconnue"}),a.jsx(oe,{type:"time","aria-label":"resume time",value:u,disabled:r,onChange:m=>h(m.target.value),className:"h-8 w-28 text-xs"}),a.jsx(M,{type:"submit",size:"sm",variant:"primary","aria-label":"schedule resume",disabled:r||u.trim()==="",children:"Programmer la reprise"})]}),s!==void 0&&a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsxs("span",{"aria-label":"resume countdown",className:"text-xs text-muted",children:["reprise dans ",EA(s-o)]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel resume",disabled:r,onClick:t,children:"Annuler la reprise"})]})]})}function AA(e){switch(e.state){case"notConfigured":return null;case"probing":return{label:"vérification du serveur…",tone:"bg-muted/20 text-muted",role:"status"};case"starting":return{label:"démarrage du serveur…",tone:"bg-warning/20 text-warning",role:"status"};case"downloading":return{label:"téléchargement du modèle…",tone:"bg-warning/20 text-warning",role:"status"};case"ready":return e.reused?{label:"serveur prêt (réutilisé)",tone:"bg-success/20 text-success"}:{label:"serveur prêt",tone:"bg-success/20 text-success"};case"failed":return null}}function TA({status:e,failure:t}){const[n,r]=g.useState(!1),i=t||(e?.state==="failed"?{code:e.code,message:e.message}:null);if(i)return a.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[a.jsxs("span",{role:"alert","aria-label":"model server launch failed",className:q("rounded-full px-2 py-0.5 text-xs font-medium","bg-danger/20 text-danger"),children:["Échec du lancement : ",i.message]}),a.jsx("button",{type:"button","aria-label":"toggle launch failure detail",onClick:()=>r(l=>!l),className:"text-xs text-muted underline hover:text-content",children:"Détails"}),n&&a.jsxs("span",{"aria-label":"launch failure detail",className:"text-xs text-faint",children:["code ",i.code,i.cause?` · cause ${i.cause}`:""]})]});if(!e)return null;const s=AA(e);return s?a.jsx("span",{role:s.role,"aria-label":"model server status",className:q("rounded-full px-2 py-0.5 text-xs font-medium",s.tone),children:s.label}):null}function xw({projectId:e,projectRoot:t=""}){const n=wA(e),r=bA(e),i=fe(),s=i.template??null,[l,o]=g.useState(""),[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState([]),[m,x]=g.useState(!1);!m&&s&&(x(!0),s.listTemplates().then(p).catch(()=>{}));const w=i.skill??null,[v,_]=g.useState([]),[y,b]=g.useState(!1),[C,S]=g.useState("");async function N(){if(w)try{const[z,ce]=await Promise.all([w.listSkills(e,"global"),w.listSkills(e,"project")]);_([...ce,...z])}catch{}}!y&&w&&(b(!0),N());async function R(){if(!w||!n.selectedAgentId||!C)return;const z=v.find(ce=>ce.id===C);z&&(await w.assignSkill(e,n.selectedAgentId,z.id,z.scope),S(""),await n.refresh())}async function D(z){!w||!n.selectedAgentId||(await w.unassignSkill(e,n.selectedAgentId,z),await n.refresh())}const[k,L]=g.useState(n.context),[A,P]=g.useState(n.context);n.context!==A&&(P(n.context),L(n.context));const[I,O]=g.useState(null),[U,K]=g.useState({}),[E,F]=g.useState({}),[j,re]=g.useState(null);async function V(){if(!j)return;const{agentId:z,profileId:ce}=j;re(null);const we=await n.changeAgentProfile(z,ce,24,80);we&&z===I&&F(Pe=>({...Pe,[z]:we.sessionId}))}const T=l.trim().length>0&&!n.busy;async function ie(z){if(z.preventDefault(),!!T){if(h&&s)await s.createAgentFromTemplate(e,h,{name:l.trim(),synchronized:!0}),await n.refresh();else{const ce=c.trim()||"";await n.createAgent(l.trim(),ce)}o(""),u(""),d("")}}function ee(z){K(ce=>({...ce,[z]:ce[z]??crypto.randomUUID()})),O(z)}function J(z){n.stopAgent(z),O(null)}const W=n.agents.find(z=>z.id===n.selectedAgentId)??null,Y=h!=="";return a.jsxs(Se,{title:"Agents",className:"flex flex-col gap-0",children:[n.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),a.jsxs("form",{onSubmit:z=>void ie(z),className:"flex flex-col gap-3 border-b border-border p-4",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"agent-name-input",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(oe,{id:"agent-name-input","aria-label":"agent name",placeholder:"My agent",value:l,onChange:z=>o(z.target.value),className:"w-full"})]}),a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"agent-template-select",className:"text-xs font-medium text-muted",children:"Template"}),a.jsxs("select",{id:"agent-template-select","aria-label":"agent template",value:h,onChange:z=>d(z.target.value),className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:n.busy,children:[a.jsx("option",{value:"",children:"(none / from scratch)"}),f.map(z=>a.jsx("option",{value:z.id,children:z.name},z.id))]})]}),!Y&&a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsxs("label",{htmlFor:"agent-profile-select",className:"text-xs font-medium text-muted",children:["Profile",n.profiles.length===0&&a.jsx("span",{className:"ml-1 text-faint",children:"(no profiles configured — you can still enter an id)"})]}),n.profiles.length>0?a.jsxs("select",{id:"agent-profile-select","aria-label":"agent profile",value:c,onChange:z=>u(z.target.value),className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"",children:"— select profile —"}),n.profiles.map(z=>a.jsx("option",{value:z.id,children:z.name},z.id))]}):a.jsx(oe,{id:"agent-profile-select","aria-label":"agent profile",placeholder:"profile-id (optional)",value:c,onChange:z=>u(z.target.value),className:"min-w-32"})]}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"create agent",disabled:!T,loading:n.busy,className:"self-end",children:"Create"})]}),a.jsx("div",{className:"p-4",children:n.agents.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.agents.map(z=>{const ce=z.id===n.selectedAgentId,we=z.id===I,Pe=n.liveAgents.find(dt=>dt.agentId===z.id),B=n.profiles.find(dt=>dt.id===z.profileId)?.name??z.profileId,de=r.driftByAgentId.get(z.id),he=n.delegationSourceByRequester[z.id],Ne=n.limitByAgent[z.id],_t=gw(z,n.profiles,n.modelServerStatusByServer),Xr=n.launchFailureByAgent[z.id];return a.jsxs("li",{className:q("flex flex-col gap-2 py-3 first:pt-0 last:pb-0",ce&&"rounded-md bg-raised px-2"),children:[a.jsxs("button",{type:"button",onClick:()=>void n.selectAgent(z.id),className:"flex min-w-0 flex-col items-start gap-0.5 text-left","aria-pressed":ce,children:[a.jsxs("span",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-2",children:[a.jsx("span",{className:"font-medium text-content",children:z.name}),de&&a.jsx("span",{"aria-label":"update available",className:"rounded-full bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary",children:"update available"}),he&&a.jsx("span",{"aria-label":`delegation source ${he}`,title:he==="mcp"?"Last delegation arrived via the MCP server":"Last delegation arrived via .ideai/requests",className:"rounded-full bg-raised px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-muted",children:he})]}),a.jsx("span",{className:"text-xs text-muted",children:B}),Pe&&a.jsxs("span",{className:"block w-full min-w-0 truncate text-xs text-primary",children:["running in IdeA · ",Pe.sessionId??Pe.nodeId]})]}),Ne&&a.jsx(PA,{state:Ne,busy:n.busy,onCancelResume:()=>void n.cancelResume(z.id),onSetResumeAt:dt=>void n.setResumeAt(z.id,dt)}),a.jsx(TA,{status:_t,failure:Xr}),a.jsx(YP,{requester:z.id}),a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.profiles.length>0&&a.jsxs("select",{"aria-label":`profile for ${z.name}`,value:z.profileId,disabled:n.busy,onChange:dt=>{const vr=dt.target.value;vr&&vr!==z.profileId&&re({agentId:z.id,profileId:vr})},className:q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[n.profiles.every(dt=>dt.id!==z.profileId)&&a.jsx("option",{value:z.profileId,children:z.profileId}),n.profiles.map(dt=>a.jsx("option",{value:dt.id,children:dt.name},dt.id))]}),de&&a.jsx(M,{size:"sm",variant:"primary","aria-label":`sync ${z.name}`,disabled:n.busy||r.driftBusy,onClick:()=>void r.syncAgent(z.id,n.refresh),children:"Sync"}),we||Pe?a.jsx(M,{size:"sm",variant:"ghost","aria-label":`stop ${z.name}`,onClick:()=>J(z.id),className:"text-danger hover:text-danger",children:"Stop"}):a.jsx(M,{size:"sm",variant:"primary","aria-label":`launch ${z.name}`,disabled:n.busy||I!==null,onClick:()=>ee(z.id),children:"Launch"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete ${z.name}`,disabled:n.busy,onClick:()=>void n.deleteAgent(z.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},z.id)})})}),I!==null&&a.jsx("div",{className:"border-t border-border p-4",children:a.jsx("div",{className:"h-96 overflow-hidden rounded-lg border border-border bg-surface",children:a.jsx(up,{cwd:t,open:(z,ce)=>n.launchAgent(I,{...z,nodeId:U[I]},ce),reattach:(z,ce)=>i.agent.reattach(z,ce),sessionId:E[I]??null,onSessionId:z=>F(ce=>({...ce,[I]:z}))},I)})}),W&&w&&a.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[a.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Skills — ",W.name]}),W.skills.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No skills assigned."}):a.jsx("ul",{className:"flex flex-wrap gap-1.5",children:W.skills.map(z=>{const ce=v.find(we=>we.id===z.skillId)?.name??z.skillId;return a.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[a.jsx("span",{children:ce}),a.jsx("button",{type:"button","aria-label":`unassign ${ce}`,disabled:n.busy,onClick:()=>void D(z.skillId),className:"text-faint hover:text-danger",children:"✕"})]},z.skillId)})}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs("select",{"aria-label":"skill to assign",value:C,onChange:z=>S(z.target.value),disabled:n.busy,className:q("h-9 min-w-0 flex-1 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"",children:"— assign a skill —"}),v.filter(z=>!W.skills.some(ce=>ce.skillId===z.id)).map(z=>a.jsxs("option",{value:z.id,children:[z.name," (",z.scope,")"]},z.id))]}),a.jsx(M,{variant:"primary","aria-label":"assign skill",disabled:n.busy||!C,onClick:()=>void R(),children:"Assign"})]})]}),W&&a.jsxs("div",{className:"flex flex-col gap-2 border-t border-border p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Context — ",W.name]}),a.jsx("code",{className:"text-xs text-muted",children:W.contextPath})]}),a.jsx("textarea",{"aria-label":"agent context",value:k,onChange:z=>L(z.target.value),rows:10,className:q("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:n.busy}),a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.busy&&a.jsx(Me,{size:14}),a.jsx(M,{variant:"primary",disabled:n.busy,onClick:()=>void n.saveContext(k),children:"Save"})]})]}),j&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm profile change",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsx("h4",{className:"text-sm font-semibold text-content",children:"Changer le moteur IA"}),a.jsx("p",{className:"mt-2 text-sm text-muted",children:"Changer le moteur abandonne l'historique de conversation (le contexte et la mémoire sont conservés). Continuer ?"}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx(M,{variant:"ghost","aria-label":"cancel profile change",disabled:n.busy,onClick:()=>re(null),children:"Annuler"}),a.jsx(M,{variant:"primary","aria-label":"confirm profile change",loading:n.busy,disabled:n.busy,onClick:()=>void V(),children:"Continuer"})]})]})})]})}function Eu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function vw(e,t){const{layout:n,terminal:r}=fe(),[i,s]=g.useState(null),[l,o]=g.useState(0),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=g.useCallback(D=>{s(D),o(k=>k+1)},[]);g.useEffect(()=>{if(!e||!n){s(null);return}let D=!1;return d(!0),n.loadLayout(e,t).then(k=>{D||f(k)}).catch(k=>{D||u(Eu(k))}).finally(()=>{D||d(!1)}),()=>{D=!0}},[n,e,t,f]);const p=g.useCallback(async D=>{if(!(!e||!n)){d(!0),u(null);try{f(await n.mutateLayout(e,D,t))}catch(k){u(Eu(k))}finally{d(!1)}}},[n,e,t,f]),m=g.useCallback(async D=>{if(!(!e||!n||D.length===0)){d(!0),u(null);try{let k=null;for(const L of D)k=await n.mutateLayout(e,L,t);k&&f(k)}catch(k){u(Eu(k))}finally{d(!1)}}},[n,e,t,f]),x=g.useCallback((D,k)=>p(GE(D,k)),[p]),w=g.useCallback(async(D,k)=>{await p({type:"merge",container:D,keepIndex:k})},[p]),v=g.useCallback((D,k)=>p({type:"resize",container:D,weights:k}),[p]),_=g.useCallback((D,k)=>p({type:"move",from:D,to:k}),[p]),y=g.useCallback((D,k)=>p({type:"setSession",target:D,session:k}),[p]),b=g.useCallback(async(D,k)=>{const L=i?Qo(i).find(I=>I.id===D):void 0,A=L?.agent??null,P=L?.session??null;if(k!==A&&(await m([{type:"setCellAgent",target:D,agent:k},{type:"setSession",target:D,session:null},{type:"setCellConversation",target:D,conversationId:null}]),P&&!A&&r))try{await r.closeTerminal(P)}catch{}},[i,m,r]),C=g.useCallback(async(D,k,L)=>{const A=i?Qo(i).find(U=>U.id===D):void 0,P=A?.agent??null,I=A?.session??null,O=[];if(k!==P&&O.push({type:"setCellAgent",target:D,agent:k},{type:"setCellConversation",target:D,conversationId:null}),L!==I&&O.push({type:"setSession",target:D,session:L}),await m(O),I&&I!==L&&!P&&r)try{await r.closeTerminal(I)}catch{}},[i,m,r]),S=g.useCallback((D,k)=>p({type:"setCellConversation",target:D,conversationId:k}),[p]),N=g.useCallback((D,k)=>{s(L=>L&&VE(L,D,k)),o(L=>L+1)},[]),R=g.useCallback(D=>{s(k=>k&&KE(k,D)),o(k=>k+1)},[]);return{layout:i,layoutVersion:l,error:c,busy:h,split:x,merge:w,resize:v,move:_,setSession:y,setCellAgent:b,attachLiveAgentToCell:C,setCellConversation:S,setPluginLayoutState:N,replacePluginLayoutWithTerminal:R}}function LA(e,t,n){return e&&t&&!n}function DA({projectId:e,cwd:t,layoutId:n,onOpenConversation:r,onOpenPluginsSettings:i}){const s=vw(e,n),l=ea(e);return s.layout?a.jsxs("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%",position:"relative"},children:[s.error&&a.jsx("p",{role:"alert",style:{color:"crimson",margin:0},children:s.error}),a.jsx(mp,{node:s.layout.root,cwd:t,vm:s,parentSplit:null,projectId:e,workState:l.state,refreshWorkState:l.refresh,onOpenConversation:r,onOpenPluginsSettings:i})]}):a.jsx("div",{"data-testid":"layout-grid",style:{width:"100%",height:"100%"},children:s.error?a.jsx("p",{role:"alert",style:{color:"crimson"},children:s.error}):a.jsx("p",{children:"Loading layout…"})})}function mp({node:e,cwd:t,vm:n,parentSplit:r,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o,onOpenPluginsSettings:c}){switch(e.type){case"customPluginLayout":return a.jsx(vA,{projectId:i,cell:e.node,onStateChange:u=>n.setPluginLayoutState(e.node.id,u),onOpenPlugins:()=>c?.(),onChooseAnotherLayout:()=>n.replacePluginLayoutWithTerminal(e.node.id)});case"leaf":return a.jsx(MA,{id:e.node.id,session:e.node.session??null,agent:e.node.agent??null,conversationId:e.node.conversationId??null,agentWasRunning:e.node.agentWasRunning??!1,cwd:t,vm:n,parentSplit:r,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o});case"split":return a.jsx(IA,{split:e.node,cwd:t,vm:n,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o,onOpenPluginsSettings:c});case"grid":return a.jsx(BA,{grid:e.node,cwd:t,vm:n,projectId:i,workState:s,refreshWorkState:l,onOpenConversation:o,onOpenPluginsSettings:c})}}function RA(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}const qs={banner:3,veil:4,controls:5};function MA({id:e,session:t,agent:n,conversationId:r,agentWasRunning:i,cwd:s,vm:l,parentSplit:o,projectId:c,workState:u,refreshWorkState:h,onOpenConversation:d}){const f=o!==null&&o.siblings===2,p=o&&o.index===0?1:0,{agent:m,input:x,system:w}=fe(),{portal:v,overlay:_}=vP(c,n??null),[y,b]=g.useState([]);g.useEffect(()=>{if(!m)return;let le=!1;return m.listAgents(c).then(xe=>{le||b(xe)}).catch(()=>{}),()=>{le=!0}},[m,c]);const[C,S]=g.useState([]),N=()=>{m?.listLiveAgents&&m.listLiveAgents(c).then(S).catch(()=>{})};g.useEffect(()=>{if(!m?.listLiveAgents)return;let le=!1;return m.listLiveAgents(c).then(xe=>{le||S(xe)}).catch(()=>{}),()=>{le=!0}},[m,c]),g.useEffect(()=>{if(!w)return;let le,xe=!1;return w.onDomainEvent(Te=>{(Te.type==="agentLaunched"||Te.type==="agentExited")&&N()}).then(Te=>{xe?Te():le=Te}),()=>{xe=!0,le?.()}},[w,m,c]);const R=n??null,{active:D}=fw(R??""),{statusForAgent:k}=CA(),L=R?y.find(le=>le.id===R):void 0,A=k(L),P=SA(A),I=kA(A),O=R?u?.agents.find(le=>le.agentId===R):void 0,U=O?.tickets.find(le=>le.status==="inProgress"),K=O?.tickets.filter(le=>le.status==="queued")??[],E=Math.max(O?.inboxDepth??0,O?.inbox?.length??0,K.length),F=O?.backgroundTasks?.filter(le=>le.status==="completed"||le.status==="failed"||le.status==="cancelled")??[],j=O?.busy.state==="busy"||!!U,re=U?.source.kind==="agent"?U:void 0,V=U?.conversationId??r??null;async function T(){if(!(!R||!x))try{await x.interrupt(c,R),await h()}catch(le){z({message:hx(le)})}}const ie=le=>C.find(xe=>xe.agentId===le),ee=async(le,xe)=>{const Te=hx(le);if(!fx(le))return{message:Te};const Dt=(m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C).find(H=>H.agentId===xe);return{message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:Dt&&Dt.nodeId!==e?Dt.nodeId:void 0}},J=le=>{if(!l.layout)return;const xe=Qo(l.layout).find(Te=>Te.id!==e&&(Te.agent??null)===le);return xe?{nodeId:xe.id}:void 0},W=le=>{const xe=ie(le);if(!(!xe||xe.kind!=="pty"||xe.nodeId===e))return J(le)?void 0:xe},[Y,z]=g.useState(null),[ce,we]=g.useState(null),[Pe,B]=g.useState(null),[de,he]=g.useState(0);g.useEffect(()=>{if(!R||!m?.attachLiveAgent||ce)return;const le=W(R);if(!le?.sessionId||le.sessionId===t)return;let xe=!1;return(async()=>{const Te=await m.attachLiveAgent(c,R,e);xe||(await l.attachLiveAgentToCell(e,R,Te.sessionId??le.sessionId),xe||he(dn=>dn+1))})().catch(()=>{}),()=>{xe=!0}},[C,R,t]);const Ne=async(le,xe,Te)=>{const dn=W(R);if(dn?.sessionId&&m.attachLiveAgent){const te=(await m.attachLiveAgent(c,R,e)).sessionId??dn.sessionId;l.setSession(e,te);const me=await m.reattach(te,xe);return N(),me.handle}const Dt=await m.launchAgent(c,R,{...le,conversationId:Te,nodeId:e},xe).catch(async H=>{throw fx(H)&&z(await ee(H,R)),H});return Dt.assignedConversationId&&l.setCellConversation(e,Dt.assignedConversationId),Dt},_t=m&&R?(le,xe)=>r?(Promise.resolve(m.inspectConversation?.(c,R,r)).then(Te=>B(Te??{})).catch(()=>B({})),new Promise((Te,dn)=>{we({opts:le,onData:xe,resolve:Te,reject:dn})})):Ne(le,xe,void 0):void 0,Xr=()=>{const le=ce;le&&(we(null),B(null),Ne(le.opts,le.onData,r??void 0).then(le.resolve,le.reject))},dt=()=>{const le=ce;le&&(we(null),B(null),l.setCellConversation(e,null),Ne(le.opts,le.onData,void 0).then(le.resolve,le.reject))},vr=m&&R?(le,xe)=>m.reattach(le,xe):void 0;return a.jsxs("div",{"data-testid":"layout-leaf","data-node-id":e,style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0,border:"1px solid #2a2a2a",boxSizing:"border-box",overflow:"hidden"},children:[a.jsxs("div",{style:{position:"absolute",top:2,right:16,zIndex:qs.controls,display:"flex",gap:2,alignItems:"center"},children:[a.jsxs("select",{"aria-label":`agent selector ${e}`,value:R??"",onChange:le=>{const xe=le.target.value;if(xe===""){z(null),l.setCellAgent(e,null);return}(async()=>{const Te=m?.listLiveAgents?await m.listLiveAgents(c).catch(()=>C):C;S(Te);const dn=J(xe);if(dn){z({message:"Cet agent est déjà actif dans une autre cellule.",goToNodeId:dn.nodeId});return}const Dt=Te.find(te=>te.agentId===xe);if(Dt&&Dt.kind==="pty"&&Dt.nodeId!==e){if(!m?.attachLiveAgent||!Dt.sessionId){z({message:"Session active introuvable pour cet agent."});return}z(null);const te=await m.attachLiveAgent(c,xe,e);await l.attachLiveAgentToCell(e,xe,te.sessionId??Dt.sessionId),N();return}z(null),await l.setCellAgent(e,xe)})().catch(async Te=>z(await ee(Te,xe)))},style:{fontSize:11,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,padding:"1px 2px",maxWidth:100},children:[a.jsx("option",{value:"",children:"Plain"}),y.map(le=>{const xe=J(le.id),Te=W(le.id);return a.jsxs("option",{value:le.id,disabled:!!xe,children:[le.name,xe?" (visible ailleurs)":Te?" (arrière-plan)":""]},le.id)})]}),a.jsx("button",{type:"button",title:"Split into columns","aria-label":`split ${e} columns`,onClick:()=>void l.split(e,"row"),children:"⬌"}),a.jsx("button",{type:"button",title:"Split into rows","aria-label":`split ${e} rows`,onClick:()=>void l.split(e,"column"),children:"⬍"}),f&&a.jsx("button",{type:"button",title:"Close this terminal","aria-label":`close ${e}`,onClick:()=>void l.merge(o.container,p),children:"✕"})]}),R&&(j||E>0||F.length>0||V)&&a.jsxs("div",{role:"status","aria-live":"polite",style:{position:"absolute",top:30,left:4,zIndex:qs.banner,display:"flex",maxWidth:"calc(100% - 8px)",alignItems:"center",gap:4,overflow:"hidden"},children:[j&&a.jsx("span",{title:re?.requesterLabel??U?.taskPreview,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-warning, #d49b3a)",borderRadius:3,background:"rgba(212, 155, 58, 0.16)",color:"var(--color-warning, #d49b3a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:re?`Busy · ${re.requesterLabel}`:"Busy"}),!j&&E>0&&a.jsxs("span",{title:`${E} pending message${E===1?"":"s"}`,style:{maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued · ",E]}),j&&E>0&&a.jsxs("span",{title:`${E} queued message${E===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,background:"rgba(91, 155, 213, 0.14)",color:"var(--color-primary, #5b9bd5)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Queued ",E]}),F.length>0&&a.jsxs("span",{title:`${F.length} background task result${F.length===1?"":"s"}`,style:{flexShrink:0,border:"1px solid var(--color-success, #57b36a)",borderRadius:3,background:"rgba(87, 179, 106, 0.14)",color:"var(--color-success, #57b36a)",padding:"1px 6px",fontSize:11,fontWeight:600},children:["Task done ",F.length]}),j&&a.jsx("button",{type:"button","aria-label":`cancel current turn ${e}`,title:"Cancel current turn",onClick:()=>void T(),disabled:!x,style:{flexShrink:0,border:"1px solid var(--color-danger, #d45a5a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-danger, #d45a5a)",cursor:x?"pointer":"default",fontSize:11,padding:"1px 6px"},children:"Cancel"}),V&&d&&a.jsx("button",{type:"button","aria-label":`open cell conversation ${e}`,title:"Open conversation history",onClick:()=>d(V),style:{flexShrink:0,border:"1px solid var(--color-border, #3a3a3a)",borderRadius:3,background:"var(--color-surface, #1e1e1e)",color:"var(--color-content, #e0e0e0)",cursor:"pointer",fontSize:11,padding:"1px 6px"},children:"History"})]}),a.jsxs("div",{style:{position:"relative",width:"100%",height:"100%",minHeight:0,minWidth:0},children:[a.jsx(up,{cwd:s,open:_t,reattach:vr,sessionId:t,onSessionId:le=>void l.setSession(e,le),agentMode:R!=null,portal:R!=null?v:void 0,refitSignal:l.layoutVersion},`${e}-${R??"plain"}-${de}`),!P&&LA(R!=null,!!_,D)&&a.jsx("div",{"data-testid":"write-portal-overlay",role:"status","aria-live":"polite",style:{position:"absolute",inset:0,zIndex:qs.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.45)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:a.jsx("span",{style:{background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"6px 12px"},children:"Un agent est en train de parler…"})}),!P&&R!=null&&a.jsx(GP,{projectId:c,agentId:R}),P&&a.jsx("div",{"data-testid":"model-server-overlay",role:"status","aria-live":"polite","aria-label":"model server launch",style:{position:"absolute",inset:0,zIndex:qs.veil,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0, 0, 0, 0.55)",color:"var(--color-content, #e0e0e0)",fontSize:13,pointerEvents:"none",userSelect:"none"},children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0,maxWidth:"80%",background:"var(--color-surface, #1e1e1e)",border:"1px solid var(--color-border, #3a3a3a)",borderRadius:4,padding:"8px 14px"},children:[a.jsx("span",{children:P}),I&&a.jsxs(a.Fragment,{children:[a.jsx("div",{"data-testid":"model-server-progress",role:"progressbar","aria-label":"progression du téléchargement","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":I.percent!=null?Math.round(I.percent):void 0,style:{position:"relative",width:220,maxWidth:"100%",height:6,borderRadius:3,overflow:"hidden",background:"var(--color-raised, #2a2a2a)"},children:a.jsx("div",{style:I.percent!=null?{height:"100%",width:`${I.percent}%`,background:"var(--color-primary, #5b9bd5)",transition:"width 120ms linear"}:{position:"absolute",top:0,bottom:0,width:"40%",background:"var(--color-primary, #5b9bd5)",animation:"model-server-indeterminate 1.1s ease-in-out infinite"}})}),(I.percent!=null||I.bytesLabel)&&a.jsxs("span",{"data-testid":"model-server-progress-label",style:{fontSize:12,color:"var(--color-content-muted, #9a9a9a)"},children:[I.percent!=null?`${Math.round(I.percent)} %`:"",I.percent!=null&&I.bytesLabel?" · ":"",I.bytesLabel??""]}),I.source&&a.jsx("span",{"data-testid":"model-server-source",style:{fontSize:11,color:"var(--color-content-muted, #9a9a9a)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.source,children:I.source})]})]})})]}),Y&&a.jsxs("div",{role:"status",style:{position:"absolute",bottom:4,left:4,right:4,margin:0,fontSize:11,color:"var(--color-content-muted, #9a9a9a)",background:"var(--color-surface, #1e1e1e)",padding:"2px 6px",borderRadius:3,zIndex:qs.banner,display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[a.jsx("span",{style:{minWidth:0},children:Y.message}),Y.goToNodeId&&a.jsx("button",{type:"button","aria-label":"aller à la cellule",onClick:()=>{RA(Y.goToNodeId),z(null)},style:{flexShrink:0,fontSize:11,cursor:"pointer",background:"transparent",color:"var(--color-primary, #5b9bd5)",border:"1px solid var(--color-primary, #5b9bd5)",borderRadius:3,padding:"1px 6px"},children:"Aller à la cellule"})]}),ce&&a.jsx(hP,{agentWasRunning:i,details:Pe,onResume:Xr,onNewConversation:dt})]})}function IA({split:e,cwd:t,vm:n,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o}){const c=e.direction==="row",u=e.children.map(m=>m.weight),h=g.useRef(null),[d,f]=g.useState(null),p=Rh(d??u);return a.jsx("div",{ref:h,"data-testid":"layout-split","data-direction":e.direction,style:{display:"flex",flexDirection:c?"row":"column",width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.children.map((m,x)=>a.jsxs("div",{style:{display:"contents"},children:[a.jsx("div",{style:{flexBasis:`${p[x]}%`,flexGrow:0,flexShrink:0,minHeight:0,minWidth:0,overflow:"hidden"},children:a.jsx(mp,{node:m.node,cwd:t,vm:n,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o,parentSplit:{container:e.id,index:x,siblings:e.children.length}})}),xf(Qg(u,x,w)),onDragEnd:w=>{const v=Qg(u,x,w);f(null),n.resize(e.id,v)}})]},_w(m.node,x)))})}function OA({isRow:e,container:t,onDragMove:n,onDragEnd:r}){const i=g.useRef(null);function s(u){if(i.current===null)return null;const h=t.current?.getBoundingClientRect(),d=h?e?h.width:h.height:0;return d<=0?null:(u-i.current)/d}function l(u){u.preventDefault(),u.currentTarget.setPointerCapture(u.pointerId),i.current=e?u.clientX:u.clientY}function o(u){if(i.current===null)return;const h=s(e?u.clientX:u.clientY);h!==null&&n(h)}function c(u){const h=s(e?u.clientX:u.clientY);i.current=null,h!==null&&r(h)}return a.jsx("div",{role:"separator","aria-orientation":e?"vertical":"horizontal",onPointerDown:l,onPointerMove:o,onPointerUp:c,style:{flex:"0 0 6px",cursor:e?"col-resize":"row-resize",background:"#3a3a3a",touchAction:"none"}})}function BA({grid:e,cwd:t,vm:n,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o}){const c=Rh(e.colWeights).map(h=>`${h}fr`).join(" "),u=Rh(e.rowWeights).map(h=>`${h}fr`).join(" ");return a.jsx("div",{"data-testid":"layout-grid-container",style:{display:"grid",gridTemplateColumns:c,gridTemplateRows:u,width:"100%",height:"100%",minHeight:0,minWidth:0},children:e.cells.map((h,d)=>a.jsx("div",{style:{gridColumn:`${h.col+1} / span ${h.colSpan}`,gridRow:`${h.row+1} / span ${h.rowSpan}`,minHeight:0,minWidth:0,overflow:"hidden"},children:a.jsx(mp,{node:h.node,cwd:t,vm:n,parentSplit:null,projectId:r,workState:i,refreshWorkState:s,onOpenConversation:l,onOpenPluginsSettings:o})},_w(h.node,d)))})}function _w(e,t){return e.node.id??String(t)}function hx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function fx(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="AGENT_ALREADY_RUNNING"}function Mi(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function px(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="NOT_FOUND"}function zA(e){const{layout:t,system:n}=fe(),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{if(!(!e||!t))try{const{layouts:w,activeId:v}=await t.listLayouts(e);i(w),l(_=>_&&w.some(y=>y.id===_)?_:v)}catch(w){h(Mi(w))}},[t,e]);g.useEffect(()=>{if(!e||!t){i([]),l(null);return}let w=!1;return c(!0),t.listLayouts(e).then(({layouts:v,activeId:_})=>{w||(i(v),l(_))}).catch(v=>{w||h(Mi(v))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[t,e]),g.useEffect(()=>{if(!e||!n)return;let w=!1,v;return n.onDomainEvent(_=>{_.type==="layoutChanged"&&_.projectId===e&&d()}).then(_=>{w?_():v=_}),()=>{w=!0,v?.()}},[n,e,d]);const f=g.useCallback(async w=>{if(!(!e||!t)){c(!0),h(null);try{const v=await t.setActiveLayout(e,w);l(v?.activeId??w)}catch(v){h(Mi(v))}finally{c(!1)}}},[t,e]),p=g.useCallback(async(w,v)=>{if(!e||!t)return null;c(!0),h(null);try{const{layoutId:_}=await t.createLayout(e,w,v),y=await t.listLayouts(e);return i(y.layouts),_}catch(_){return h(Mi(_)),null}finally{c(!1)}},[t,e]),m=g.useCallback(async(w,v)=>{if(!(!e||!t)){c(!0),h(null);try{await t.renameLayout(e,w,v),i(_=>_.map(y=>y.id===w?{...y,name:v}:y))}catch(_){px(_)?await d():h(Mi(_))}finally{c(!1)}}},[t,e,d]),x=g.useCallback(async w=>{if(!(!e||!t)){if(r.length<=1){h("Cannot delete the last layout.");return}c(!0),h(null);try{const{activeId:v}=await t.deleteLayout(e,w);i(_=>_.filter(y=>y.id!==w)),l(v)}catch(v){px(v)?await d():h(Mi(v))}finally{c(!1)}}},[t,e,r.length,d]);return{layouts:r,activeId:s,busy:o,error:u,setActive:f,create:p,rename:m,deleteLayout:x}}function FA({projectId:e,onActiveLayoutChange:t}){const n=zA(e);g.useEffect(()=>{const _=n.layouts.find(y=>y.id===n.activeId);_&&t(_)},[n.activeId,n.layouts,t]);const[r,i]=g.useState(null),[s,l]=g.useState(""),o=g.useRef(null),[c,u]=g.useState(!1),{registry:h}=pp(),[d,f]=g.useState(null);async function p(_){await n.setActive(_)}async function m(_){n.layouts.length<=1||await n.deleteLayout(_)}function x(_,y){i(_),l(y),setTimeout(()=>o.current?.focus(),0)}async function w(){if(!r)return;const _=s.trim();_&&await n.rename(r,_),i(null),l("")}async function v(_){u(!1);const y=_==="gitGraph"?"Git Graph":"Layout",b=window.prompt("New layout name:",y);if(!b?.trim())return;const C=await n.create(b.trim(),_);C&&await n.setActive(C)}return n.layouts.length===0?null:a.jsxs("div",{"data-testid":"layout-tabs",className:"flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",children:[n.layouts.map(_=>{const y=_.id===n.activeId,b=_.id===r;return a.jsxs("div",{className:q("group flex items-center gap-1 rounded-md border px-1 transition-colors",y?"border-border-strong bg-raised":"border-transparent hover:bg-raised"),children:[b?a.jsx("input",{ref:o,value:s,onChange:C=>l(C.target.value),onBlur:()=>void w(),onKeyDown:C=>{C.key==="Enter"&&w(),C.key==="Escape"&&(i(null),l(""))},"aria-label":`rename layout ${_.name}`,className:"w-24 rounded border border-border bg-base px-1 py-0.5 text-sm text-content focus:outline-none focus:ring-1 focus:ring-primary"}):a.jsxs("button",{type:"button",role:"tab","aria-selected":y,onClick:()=>void p(_.id),onDoubleClick:()=>x(_.id,_.name),className:q("flex items-center gap-1 px-2 py-1 text-sm focus-visible:outline-none",y?"font-semibold text-content":"text-muted hover:text-content"),children:[_.kind==="gitGraph"&&a.jsx("span",{"aria-label":"git graph layout",className:"text-xs text-primary",title:"Git Graph",children:"⎇"}),_.name]}),a.jsx("button",{type:"button","aria-label":`delete layout ${_.name}`,disabled:n.layouts.length<=1,onClick:()=>void m(_.id),className:q("flex h-4 w-4 items-center justify-center rounded text-xs transition-opacity",n.layouts.length<=1?"cursor-not-allowed opacity-20":"opacity-60 hover:opacity-100 group-hover:opacity-100"),children:"×"})]},_.id)}),a.jsxs("div",{className:"relative",children:[a.jsx("button",{type:"button","aria-label":"create layout",onClick:()=>u(_=>!_),className:"flex h-6 w-6 items-center justify-center rounded border border-transparent text-sm text-muted transition-colors hover:border-border hover:text-content",children:"+"}),c&&a.jsxs("div",{role:"menu",className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col rounded-md border border-border bg-surface shadow-lg",children:[a.jsx("button",{type:"button",role:"menuitem","aria-label":"create terminal layout",onClick:()=>void v("terminal"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"Terminal"}),a.jsx("button",{type:"button",role:"menuitem","aria-label":"create git graph layout",onClick:()=>void v("gitGraph"),className:"px-3 py-2 text-left text-sm text-content hover:bg-raised",children:"⎇ Git graph"}),a.jsx(yA,{registry:h,onSelect:_=>{u(!1),f(`« ${_.layout.label} » (${_.pluginDisplayName}) : la création de layouts plugins nécessite une extension backend pas encore livrée.`)}})]})]}),(n.error||d)&&a.jsx("span",{className:"ml-2 text-xs text-danger",role:"alert",children:n.error??d})]})}class $A extends g.Component{constructor(){super(...arguments);X(this,"state",{error:null,retryKey:0});X(this,"retry",()=>{this.setState(({retryKey:n})=>({error:null,retryKey:n+1}))})}static getDerivedStateFromError(n){return{error:n}}render(){return this.state.error?a.jsx(Se,{title:"Work",children:a.jsxs("div",{role:"alert",className:"rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[a.jsx("p",{className:"font-medium",children:"Work panel failed to render."}),a.jsx("p",{className:"mt-1 text-xs text-danger/80",children:this.state.error.message}),a.jsx(M,{size:"sm",variant:"ghost",className:"mt-2",onClick:this.retry,children:"Retry"})]})}):a.jsx("div",{children:this.props.children},this.state.retryKey)}}function cr(e){return e.length<=8?e:e.slice(0,8)}function WA(e){return e==="inProgress"?"In progress":"Queued"}function HA(e){switch(e){case"running":return"Running";case"completed":return"Completed";case"failed":return"Failed";case"cancelled":return"Cancelled";case"delivered":return"Delivered";case"pending":return"Pending"}}function UA(e){return e==="completed"||e==="failed"||e==="cancelled"}function qA(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function VA(e){if(e.source.kind==="human")return"Human";const t=cr(e.source.agentId);return e.requesterLabel.trim()?`${e.requesterLabel} (${t})`:`Agent ${t}`}function KA(e){switch(e){case"ready":return"Summary";case"missing":return"No summary";case"partial":return"Partial";case"unavailable":return"Unavailable"}}function GA(e){if(e.objectivePreview)return`Goal: ${e.objectivePreview}`;if(e.summaryPreview)return e.summaryPreview;const t=(e.recentTurns??[]).at(-1);return t?`Last: ${t.textPreview}`:null}function mx(e){if(typeof document>"u")return;const t=document.querySelector(`[data-node-id="${e}"]`);if(!t)return;t.scrollIntoView?.({block:"nearest",inline:"nearest"});const n=t.style.outline;t.style.outline="2px solid var(--color-primary, #5b9bd5)",window.setTimeout(()=>{t.style.outline=n},1200)}async function YA(e){if(typeof navigator<"u"&&navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}throw new Error("Clipboard unavailable")}function XA({summary:e,onOpenConversation:t}){const n=GA(e),[r,i]=g.useState(!1),[s,l]=g.useState(!1);return n?a.jsxs("div",{className:"mt-1 min-w-0 pl-1 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsx("span",{className:q("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="ready"?"bg-success/10 text-success":"bg-raised text-muted"),children:KA(e.status)}),t?a.jsx("button",{type:"button","aria-label":`open conversation ${e.conversationId}`,className:"min-w-0 flex-1 break-words text-left hover:text-content hover:underline",onClick:()=>t(e.conversationId),children:n}):a.jsx("span",{className:"min-w-0 flex-1 break-words",children:n}),a.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content",onClick:()=>i(o=>!o),children:r?"Hide":"View"}),a.jsx("button",{type:"button",className:"shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content disabled:opacity-50",disabled:!n,onClick:()=>{YA(n).then(()=>{l(!0),window.setTimeout(()=>l(!1),1e3)})},children:s?"Copied":"Copy"})]}),r&&a.jsxs("div",{"aria-label":`conversation ${e.conversationId} details`,className:"mt-1 space-y-1 border-l border-border pl-2",children:[e.objectivePreview&&a.jsxs("p",{children:[a.jsx("span",{className:"font-medium text-content",children:"Goal:"})," ",e.objectivePreview]}),e.summaryPreview&&a.jsxs("p",{children:[a.jsx("span",{className:"font-medium text-content",children:"Summary:"})," ",e.summaryPreview]}),(e.recentTurns??[]).length>0&&a.jsx("ul",{className:"space-y-0.5",children:(e.recentTurns??[]).map(o=>a.jsxs("li",{children:[a.jsxs("span",{className:"font-medium text-content",children:[o.role,":"]})," ",o.textPreview]},`${o.atMs}-${o.role}-${o.textPreview}`))})]})]}):null}function QA({ticket:e,summary:t,onOpenConversation:n}){const r=e.taskLen>e.taskPreview.length;return a.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsxs("span",{className:q("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",e.status==="inProgress"?"bg-warning/15 text-warning":"bg-raised text-muted"),children:["#",e.position+1," ",WA(e.status)]}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"font-medium text-content",children:VA(e)}),a.jsx("span",{className:"text-muted",children:" · "}),a.jsx("span",{className:"break-words",children:e.taskPreview}),r&&a.jsxs("span",{"aria-label":`${e.taskLen-e.taskPreview.length} more characters`,className:"text-muted",children:[" ","+",e.taskLen-e.taskPreview.length]})]}),a.jsx("code",{"aria-label":`ticket ${cr(e.ticketId)}`,title:e.ticketId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.ticketId)})]}),t&&a.jsx(XA,{summary:t,onOpenConversation:n})]})}function JA({item:e}){return a.jsx("li",{className:"min-w-0 text-xs text-muted",children:a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium text-muted",children:e.kind}),a.jsx("span",{className:"min-w-0 flex-1 break-words",children:e.body}),a.jsx("code",{title:e.id,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.id)})]})})}function ZA({task:e,onRefresh:t}){const{workState:n}=fe(),[r,i]=g.useState(!1),[s,l]=g.useState(!1),[o,c]=g.useState(null),u=!!(e.stdoutTail||e.stderrTail),h=e.status==="running"||e.status==="pending",d=e.status==="failed"||e.status==="cancelled";async function f(p){l(!0),c(null);try{await p(e.taskId),await t()}catch(m){c(m instanceof Error?m.message:String(m))}finally{l(!1)}}return a.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[a.jsx("span",{className:q("mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",qA(e.status)),children:HA(e.status)}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"font-medium text-content",children:e.kind}),e.exitCode!==null&&a.jsxs("span",{className:"text-muted",children:[" · exit ",e.exitCode]})]}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!h||s,loading:s,onClick:()=>void f(p=>n.cancelBackgroundTask(p)),children:"Cancel"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!u,onClick:()=>i(p=>!p),children:"Output"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!d||s,loading:s,onClick:()=>void f(p=>n.retryBackgroundTask(p)),children:"Retry"}),a.jsx("code",{title:e.taskId,className:"mt-0.5 shrink-0 rounded bg-raised px-1.5 py-0.5 text-[11px] text-muted",children:cr(e.taskId)})]}),e.summary&&UA(e.status)&&a.jsx("p",{"aria-label":`task ${cr(e.taskId)} summary`,title:e.summary,className:"mt-1 truncate pl-1 text-[11px] text-muted",children:e.summary}),o&&a.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:o}),r&&u&&a.jsxs("pre",{"aria-label":`task ${cr(e.taskId)} output`,className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-canvas p-2 text-[11px] text-muted",children:[e.stdoutTail?`stdout -${e.stdoutTail}`:"",e.stdoutTail&&e.stderrTail?` - -`:"",e.stderrTail?`stderr -${e.stderrTail}`:""]})]})}function eT({agent:e,conversations:t,visibleLeaves:n,layout:r,projectId:i,onRefresh:s,onOpenConversation:l}){const{agent:o}=fe(),[c,u]=g.useState(null),[h,d]=g.useState(!1),f=e.live!==void 0,p=e.busy??{state:"idle"},m=p.state==="busy",x=[...e.tickets??[]].sort((k,L)=>k.position-L.position),w=[...e.inbox??[]].sort((k,L)=>k.createdAtMs-L.createdAtMs),v=[...e.backgroundTasks??[]].sort((k,L)=>L.updatedAtMs-k.updatedAtMs||k.taskId.localeCompare(L.taskId)),_=Math.max(e.inboxDepth??0,w.length,x.length),y=new Set(n.map(k=>k.id)),b=f&&y.has(e.live.nodeId),C=n.find(k=>!k.session&&!k.agent),S=m||x.some(k=>k.status==="inProgress");async function N(){await s()}async function R(){if(!(!e.live||!C||!o?.attachLiveAgent)){d(!0),u(null);try{const k=await o.attachLiveAgent(i,e.agentId,C.id);await r.attachLiveAgentToCell(C.id,e.agentId,k.sessionId),await N(),mx(C.id)}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!1)}}}async function D(){if(!e.live||!o?.stopLiveAgent)return;const k=S?" The current turn will be interrupted.":"";if(window.confirm(`Stop ${e.name}?${k}`)){d(!0),u(null);try{const L=await o.stopLiveAgent(i,e.agentId);if(y.has(e.live.nodeId)){const A=n.find(P=>P.id===e.live?.nodeId);(!A?.session||A.session===L.sessionId)&&await r.setSession(e.live.nodeId,null)}await N()}catch(L){u(L instanceof Error?L.message:String(L))}finally{d(!1)}}}return a.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),a.jsx("code",{className:"truncate text-xs text-muted",children:e.profileId})]}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx("span",{className:q("rounded-full px-2 py-0.5 text-xs font-medium",f?"bg-success/15 text-success":"bg-raised text-muted"),children:f?"Live":"Offline"}),a.jsx("span",{className:q("rounded-full px-2 py-0.5 text-xs font-medium",m?"bg-warning/15 text-warning":"bg-raised text-muted"),children:m?"Busy":"Idle"}),_>0&&a.jsxs("span",{"aria-label":`${e.name} queue depth ${_}`,className:"rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary",children:["Queue ",_]}),p.state==="busy"&&a.jsx("code",{"aria-label":`busy ticket ${cr(p.ticket)}`,title:p.ticket,className:"rounded bg-raised px-1.5 py-0.5 text-xs text-muted",children:cr(p.ticket)}),e.live&&b&&a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>mx(e.live.nodeId),children:"Open"}),e.live&&!b&&a.jsx(M,{size:"sm",variant:"ghost",disabled:!C||!o?.attachLiveAgent,loading:h,title:C?void 0:"No empty visible cell available",onClick:()=>void R(),children:"Attach"}),e.live&&a.jsx(M,{size:"sm",variant:"danger",loading:h,disabled:!o?.stopLiveAgent,onClick:()=>void D(),children:"Stop"})]})]}),e.live&&!b&&!C&&a.jsx("p",{className:"mt-1 text-xs text-muted",children:"No empty visible cell."}),c&&a.jsx("p",{role:"alert",className:"mt-1 text-xs text-danger",children:c}),x.length>0&&a.jsx("ul",{"aria-label":`${e.name} tickets`,className:"mt-2 flex flex-col gap-1",children:x.map(k=>a.jsx(QA,{ticket:k,summary:t.get(k.conversationId),onOpenConversation:l},k.ticketId))}),w.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),a.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:w.map(k=>a.jsx(JA,{item:k},k.id))})]}),v.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Background tasks"}),a.jsx("ul",{"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:v.map(k=>a.jsx(ZA,{task:k,onRefresh:N},k.taskId))})]})]})}function tT({projectId:e,onOpenConversation:t}){const n=ea(e),r=vw(e),i=n.state?.agents??[],s=r.layout?Qo(r.layout):[],l=new Map((n.state?.conversations??[]).map(o=>[o.conversationId,o]));return a.jsxs(Se,{title:"Work",actions:a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"}),children:[n.error&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),n.busy&&n.state===null?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Loading work state…"})]}):i.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No agent work state."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:i.map(o=>a.jsx(eT,{agent:o,conversations:l,visibleLeaves:s,layout:r,projectId:e,onRefresh:n.refresh,onOpenConversation:t},o.agentId))})]})}function nT(e){return a.jsx($A,{children:a.jsx(tT,{...e})})}function Pu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Au(e){const t=new Set,n=[];for(const r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function rT(e,t){const{conversation:n}=fe(),[r,i]=g.useState([]),[s,l]=g.useState(!1),[o,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useRef([]),f=g.useRef(!1),p=g.useCallback(v=>{d.current=v,i(v)},[]),m=g.useCallback(async()=>{if(!f.current){f.current=!0,l(!0),c(null);try{const v=await n.readPage(e,t,{direction:"backward"});p(Au(v.turns)),h(v.hasMore)}catch(v){c(Pu(v))}finally{l(!1),f.current=!1}}},[n,e,t,p]),x=g.useCallback(async()=>{if(f.current)return;const v=d.current[0];if(!v){await m();return}f.current=!0,l(!0),c(null);try{const _=await n.readPage(e,t,{direction:"backward",anchor:v.id});_.turns.length>0&&p(Au([..._.turns,...d.current])),h(_.hasMore)}catch(_){c(Pu(_))}finally{l(!1),f.current=!1}},[n,e,t,m,p]),w=g.useCallback(async()=>{if(!f.current){if(d.current.length===0){await m();return}f.current=!0,l(!0),c(null);try{for(;;){const v=d.current.at(-1);if(!v)break;const _=await n.readPage(e,t,{direction:"forward",anchor:v.id});if(_.turns.length===0||(p(Au([...d.current,..._.turns])),!_.hasMore))break}}catch(v){c(Pu(v))}finally{l(!1),f.current=!1}}},[n,e,t,m,p]);return g.useEffect(()=>{p([]),h(!1),m()},[m,p]),{turns:r,busy:s,error:o,hasMore:u,loadOlder:x,refreshTail:w}}function gx(e){return e.length<=8?e:e.slice(0,8)}function Tu(e){return e.kind==="human"?"human":`agent:${e.agentId}`}function iT(e){if(!Number.isFinite(e)||e<=0)return"";try{return new Date(e).toLocaleString()}catch{return""}}function sT(e){switch(e){case"prompt":return"Prompt";case"response":return"Response";case"toolActivity":return"Tool"}}function lT({turn:e,sideClass:t}){const[n,r]=g.useState(!1);return a.jsx("div",{className:q("flex flex-col",t),children:a.jsxs("div",{className:"max-w-[80%] rounded-md border border-border bg-surface/60 px-3 py-1.5 text-xs text-muted",children:[a.jsxs("button",{type:"button",className:"flex items-center gap-1.5 font-medium hover:text-content",onClick:()=>r(i=>!i),"aria-expanded":n,children:[a.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),"Tool activity",a.jsxs("span",{className:"text-faint",children:["· ",e.textLen," chars"]})]}),n&&a.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap break-words font-mono text-[11px] text-muted",children:e.text})]})})}function aT({projectId:e,conversationId:t,onClose:n}){const r=rT(e,t),i=ea(e),s=g.useMemo(()=>{const u=new Map;for(const h of i.state?.agents??[])h.name.trim()&&u.set(h.agentId,h.name.trim());return u},[i.state]),l=g.useMemo(()=>{const u=[],h=new Map;for(const d of r.turns){const f=Tu(d.source);if(h.has(f))continue;const p=u.length===0?"left":"right",m=d.source.kind==="human"?"User":s.get(d.source.agentId)??`Agent ${gx(d.source.agentId)}`;h.set(f,{label:m,side:p}),u.push(f)}return{order:u,meta:h}},[r.turns,s]),o=g.useMemo(()=>{const u=l.order.map(h=>l.meta.get(h)?.label??"?");return u.length>=2?`${u[0]} ↔ ${u[1]}`:u.length===1?u[0]:"Conversation"},[l]);function c(u){return l.meta.get(Tu(u))?.side??"left"}return a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border bg-surface px-4 py-2",children:[a.jsxs("div",{className:"flex min-w-0 flex-col",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:o}),a.jsx("code",{className:"truncate text-xs text-muted",title:t,children:gx(t)})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.refreshTail(),loading:r.busy,children:"Refresh"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"← Retour aux terminaux"})]})]}),r.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),a.jsxs("div",{className:"flex flex-1 flex-col gap-2 overflow-auto px-4 py-3",children:[r.hasMore&&a.jsx("div",{className:"flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void r.loadOlder(),loading:r.busy,children:"Charger les tours précédents"})}),r.busy&&r.turns.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Chargement du fil…"})]}):r.turns.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun tour pour le moment."}):r.turns.map(u=>{const h=c(u.source),d=h==="right"?"items-end":"items-start";if(u.role==="toolActivity")return a.jsx(lT,{turn:u,sideClass:d},u.id);const f=l.meta.get(Tu(u.source)),p=iT(u.atMs);return a.jsx("div",{className:q("flex flex-col",d),children:a.jsxs("div",{className:q("max-w-[80%] rounded-lg border px-3 py-2 text-sm",h==="right"?"border-primary/20 bg-primary/10 text-content":"border-border bg-raised text-content"),children:[a.jsxs("div",{className:"mb-1 flex items-baseline gap-2 text-xs text-muted",children:[a.jsx("span",{className:"font-medium text-content",children:f?.label??"?"}),a.jsxs("span",{children:["· ",sT(u.role)]}),p&&a.jsxs("span",{className:"text-faint",children:["· ",p]})]}),a.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.text})]})},u.id)})]})]})}function Lu(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function oT(e){if(e&&typeof e=="object"&&"code"in e)return String(e.code)}function cT(){const{modelServer:e}=fe(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(!1),o=g.useCallback(async()=>{l(!0),i(null);try{n(await e.listModelServers())}catch(f){i(Lu(f))}finally{l(!1)}},[e]);g.useEffect(()=>{o()},[o]);const c=g.useCallback(async f=>{l(!0),i(null);try{const p=await e.saveModelServer(f);return n(m=>{const x=m.findIndex(w=>w.id===p.id);if(x>=0){const w=m.slice();return w[x]=p,w}return[...m,p]}),p}catch(p){return i(Lu(p)),null}finally{l(!1)}},[e]),u=g.useCallback(async f=>{l(!0),i(null);try{return await e.deleteModelServer(f),n(p=>p.filter(m=>m.id!==f)),!0}catch(p){return oT(p)==="model_server_in_use"?i("Ce serveur est encore utilisé par un profil : détache-le d'abord (choisis « aucun » ou un autre serveur) avant de le supprimer."):i(Lu(p)),!1}finally{l(!1)}},[e]),h=g.useCallback(async f=>{try{return await e.previewModelServerCommand(f)}catch{return null}},[e]),d=g.useCallback(()=>i(null),[]);return{servers:t,error:r,busy:s,reload:o,save:c,remove:u,preview:h,clearError:d}}function uT(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function dT(e){return e.startsWith("/")||e.startsWith("\\")?!0:/^[a-zA-Z]:[/\\]/.test(e)}function hT(e){if(/\s/.test(e)||e.startsWith("http://")||e.startsWith("https://")||(e.match(/:/g)??[]).length>1)return!1;const[t,n]=e.includes(":")?[e.slice(0,e.indexOf(":")),e.slice(e.indexOf(":")+1)]:[e,void 0];if(n!==void 0&&n.length===0)return!1;const r=t.split("/");return r.length===2&&r[0].length>0&&r[1].length>0}function fT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),uT(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&(t.port="Port must be an integer between 1 and 65535."),e.servedModelName.trim().length===0&&(t.servedModelName="Le nom du modèle est requis."),(e.host.trim().length===0||/\s/.test(e.host))&&(t.host="L'adresse d'écoute est requise et ne doit pas contenir d'espace.");const n=e.modelSource;return n&&(n.type==="localPath"?n.path.trim().length===0?t.modelSource="Le chemin du fichier .gguf est requis.":dT(n.path.trim())||(t.modelSource="Le chemin du fichier doit être absolu."):n.repo.trim().length===0?t.modelSource="Le modèle Hugging Face est requis.":hT(n.repo.trim())||(t.modelSource="Format attendu : auteur/modèle ou auteur/modèle:quant (ex. unsloth/Qwen3.5-9B-GGUF:Q4_K_M).")),e.autoStart&&!n&&(t.modelSource="Le démarrage automatique nécessite une source de modèle."),t}function pT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`srv-${Math.random().toString(36).slice(2,10)}`}function mT(){return{id:pT(),kind:"llamaCpp",name:"",baseURL:"http://localhost:8080/v1",port:8080,servedModelName:"",host:"127.0.0.1",jinja:!1,args:[],autoStart:!1,stopPolicy:"stopOnAppExit"}}function gT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function xT(e){if(!e)return"";if(e.type==="localPath"){const r=e.path.trim();return r.length===0?"":(r.split(/[/\\]/).pop()??"").replace(/\.gguf$/i,"")}const t=e.repo.trim();return t.length===0?"":(t.includes(":")?t.slice(0,t.indexOf(":")):t).split("/").pop()??""}const vT=["--model","-m","-hf","--port","--host","-ngl","--gpu-layers","-c","--ctx-size","--jinja"];function _T(e){const t=new Set(vT),n=new Set;for(const r of e){const i=r.includes("=")?r.slice(0,r.indexOf("=")):r;t.has(i)&&n.add(i)}return[...n]}function Et({children:e}){return a.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function Ii({children:e}){return a.jsx("small",{className:"text-xs text-muted",children:e})}const yT=[{value:"stopOnAppExit",label:"Stop on app exit"},{value:"keepAlive",label:"Keep alive"},{value:"stopWhenUnused",label:"Stop when unused"}];function bT({vm:e}){const[t,n]=g.useState(null);function r(){e.clearError(),n(mT())}function i(l){e.clearError(),n({...l})}async function s(){if(!t)return;await e.save(t)&&n(null)}return a.jsx(Se,{"aria-label":"local model servers",title:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:"Local model servers"}),a.jsx(M,{size:"sm","aria-label":"add model server",onClick:r,className:"ml-auto",children:"Add server"})]}),children:a.jsxs("div",{className:"flex flex-col gap-3",children:[e.error&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.error}),e.servers.length===0&&!t&&a.jsx("p",{className:"text-xs text-muted",children:"No local server declared yet. Add one to auto-manage a `llama-server`, or keep using an external endpoint."}),a.jsx("ul",{className:"flex list-none flex-col gap-2 p-0",children:e.servers.map(l=>a.jsxs("li",{className:"flex items-center gap-2 rounded-md border border-border bg-raised p-2",children:[a.jsxs("span",{className:"flex min-w-0 flex-col",children:[a.jsx("strong",{className:"truncate text-sm text-content",children:l.name}),a.jsxs("span",{className:"truncate text-xs text-muted",children:[l.baseURL," · ",l.servedModelName,l.autoStart?" · auto-start":""]})]}),a.jsxs("span",{className:"ml-auto flex items-center gap-1",children:[a.jsx(M,{size:"sm","aria-label":`edit ${l.name}`,onClick:()=>i(l),disabled:e.busy,children:"Edit"}),a.jsx(ir,{size:"sm","aria-label":`delete ${l.name}`,onClick:()=>void e.remove(l.id),disabled:e.busy,children:"×"})]})]},l.id))}),t&&a.jsx(kT,{draft:t,busy:e.busy,preview:e.preview,onChange:n,onCancel:()=>{e.clearError(),n(null)},onSubmit:()=>void s()})]})})}function wT({kind:e,onSelect:t}){const n=(r,i)=>{const s=e===r;return a.jsx("button",{type:"button","aria-pressed":s,onClick:()=>t(r),className:q("h-8 flex-1 rounded-md px-3 text-xs font-medium transition-colors",s?"bg-primary text-white":"bg-raised text-muted hover:text-content"),children:i})};return a.jsxs("div",{role:"group","aria-label":"source du modèle",className:"flex gap-1 rounded-md border border-border p-1",children:[n("huggingFace","Télécharger depuis Hugging Face"),n("localPath","Fichier .gguf local")]})}function ST({preview:e,autoStart:t}){const[n,r]=g.useState(!1),i=t?"Commande générée":"Commande à lancer manuellement";async function s(){if(e)try{await navigator.clipboard.writeText(e.display),r(!0),setTimeout(()=>r(!1),1500)}catch{}}return a.jsxs("section",{"aria-label":"command preview",className:"flex flex-col gap-1 rounded-md border border-border bg-raised p-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Et,{children:i}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"copier la commande",onClick:()=>void s(),disabled:!e,className:"ml-auto",children:n?"Copié":"Copier"})]}),e?a.jsx("code",{"aria-label":"preview command line",className:"whitespace-pre-wrap break-all font-mono text-xs text-content",children:e.display}):a.jsx("span",{className:"text-xs text-muted",children:"Renseigne une source de modèle pour voir la commande."})]})}function kT({draft:e,busy:t,preview:n,onChange:r,onCancel:i,onSubmit:s}){const l=fT(e),o=Object.keys(l).length===0,c=b=>r({...e,...b}),[u,h]=g.useState(e.modelSource?.type??"huggingFace"),d=e.modelSource?.type==="huggingFace"?e.modelSource.repo:"",f=e.modelSource?.type==="localPath"?e.modelSource.path:"";function p(b){const C={modelSource:b};if(e.servedModelName.trim().length===0){const S=xT(b);S.length>0&&(C.servedModelName=S)}c(C)}function m(b){b!==u&&(h(b),c({modelSource:void 0}))}const[x,w]=g.useState(null),v=JSON.stringify({modelSource:e.modelSource,port:e.port,host:e.host,gpuLayers:e.gpuLayers,contextSize:e.contextSize,jinja:e.jinja,binaryPath:e.binaryPath,args:e.args}),_=g.useRef(e);_.current=e,g.useEffect(()=>{if(!e.modelSource){w(null);return}let b=!1;const C=setTimeout(()=>{n(_.current).then(S=>{b||w(S)})},250);return()=>{b=!0,clearTimeout(C)}},[v,n]);const y=_T(e.args);return a.jsxs("fieldset",{"aria-label":"model server editor",className:"flex flex-col gap-3 rounded-md border border-primary/40 p-3",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:e.name.trim().length>0?e.name:"New server"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Nom"}),a.jsx(oe,{"aria-label":"server name",value:e.name,invalid:!!l.name,onChange:b=>c({name:b.target.value})}),l.name&&a.jsx("small",{className:"text-xs text-danger",children:l.name})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Source du modèle"}),a.jsx(wT,{kind:u,onSelect:m})]}),u==="huggingFace"?a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Modèle Hugging Face"}),a.jsx(oe,{"aria-label":"hugging face model",value:d,placeholder:"unsloth/Qwen3.5-9B-GGUF:Q4_K_M",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"huggingFace",repo:C})}}),a.jsx(Ii,{children:"llama.cpp téléchargera/cache le fichier automatiquement."}),l.modelSource&&a.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}):a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Fichier .gguf"}),a.jsx(oe,{"aria-label":"local gguf file",value:f,placeholder:"/home/me/models/qwen.gguf",invalid:!!l.modelSource,onChange:b=>{const C=b.target.value;p(C.trim().length===0?void 0:{type:"localPath",path:C})}}),a.jsx(Ii,{children:"Chemin absolu vers un .gguf déjà présent."}),l.modelSource&&a.jsx("small",{className:"text-xs text-danger",children:l.modelSource})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Nom du modèle dans IdeA"}),a.jsx(oe,{"aria-label":"server served model name",value:e.servedModelName,placeholder:"qwen3-coder-30b",invalid:!!l.servedModelName,onChange:b=>c({servedModelName:b.target.value})}),a.jsx(Ii,{children:"Nom envoyé aux clients OpenAI-compatible."}),l.servedModelName&&a.jsx("small",{className:"text-xs text-danger",children:l.servedModelName})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs("label",{className:"flex min-w-[12rem] flex-1 flex-col gap-1",children:[a.jsx(Et,{children:"Commande serveur"}),a.jsx(oe,{"aria-label":"server binary path",value:e.binaryPath??"",placeholder:"llama-server",onChange:b=>{const C=b.target.value;c({binaryPath:C.length===0?void 0:C})}}),a.jsx(Ii,{children:"Laisse vide pour résoudre `llama-server` via le PATH."})]}),a.jsxs("label",{className:"flex min-w-[6rem] flex-col gap-1",children:[a.jsx(Et,{children:"Port"}),a.jsx(oe,{"aria-label":"server port",value:Number.isNaN(e.port)?"":e.port.toString(),inputMode:"numeric",invalid:!!l.port,onChange:b=>c({port:Number.parseInt(b.target.value,10)})}),l.port&&a.jsx("small",{className:"text-xs text-danger",children:l.port})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Base URL (OpenAI-compatible)"}),a.jsx(oe,{"aria-label":"server base url",value:e.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!l.baseURL,onChange:b=>c({baseURL:b.target.value})}),l.baseURL&&a.jsx("small",{className:"text-xs text-danger",children:l.baseURL})]}),a.jsxs("label",{className:"flex items-start gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":"server auto start",checked:e.autoStart,disabled:!e.modelSource,onChange:b=>c({autoStart:b.target.checked}),className:"mt-1 accent-primary disabled:opacity-50"}),a.jsxs("span",{className:"flex flex-col",children:[a.jsx(Et,{children:"Démarrer automatiquement"}),!e.modelSource&&a.jsx(Ii,{children:"Renseigne d'abord une source de modèle pour l'activer."})]})]}),a.jsxs("details",{className:"rounded-md border border-border p-2",children:[a.jsx("summary",{className:"cursor-pointer text-xs font-medium text-muted",children:"Réglages llama.cpp"}),a.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsxs(Et,{children:["Couches GPU ",a.jsx("span",{className:"text-muted",children:"(-ngl)"})]}),a.jsx(oe,{"aria-label":"gpu layers",value:e.gpuLayers===void 0?"":String(e.gpuLayers),inputMode:"numeric",placeholder:"99",onChange:b=>{const C=b.target.value.trim();c({gpuLayers:C.length===0?void 0:Number.parseInt(C,10)})}}),a.jsx(Ii,{children:"0 = CPU seul."})]}),a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsxs(Et,{children:["Taille de contexte ",a.jsx("span",{className:"text-muted",children:"(-c)"})]}),a.jsx(oe,{"aria-label":"context size",value:e.contextSize===void 0?"":String(e.contextSize),inputMode:"numeric",placeholder:"16384",onChange:b=>{const C=b.target.value.trim();c({contextSize:C.length===0?void 0:Number.parseInt(C,10)})}})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsxs(Et,{children:["Adresse d'écoute ",a.jsx("span",{className:"text-muted",children:"(--host)"})]}),a.jsx(oe,{"aria-label":"listen host",value:e.host,placeholder:"127.0.0.1",invalid:!!l.host,onChange:b=>c({host:b.target.value})}),l.host&&a.jsx("small",{className:"text-xs text-danger",children:l.host})]}),a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":"jinja template",checked:e.jinja,onChange:b=>c({jinja:b.target.checked}),className:"accent-primary"}),a.jsxs(Et,{children:["Template chat Jinja ",a.jsx("span",{className:"text-muted",children:"(--jinja)"})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(Et,{children:"Arguments supplémentaires"}),a.jsx(oe,{"aria-label":"extra arguments",value:e.args.join(" "),placeholder:"--flash-attn --parallel 2",onChange:b=>c({args:gT(b.target.value)})}),y.length>0&&a.jsxs("small",{className:"text-xs text-warning",role:"status",children:[y.join(", ")," : cette option est déjà pilotée par un champ ci-dessus."]})]}),a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx(Et,{children:"Stop policy"}),a.jsx("select",{"aria-label":"server stop policy",value:e.stopPolicy,onChange:b=>c({stopPolicy:b.target.value}),className:q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:yT.map(b=>a.jsx("option",{value:b.value,children:b.label},b.value))})]})]})]}),a.jsx(ST,{preview:x,autoStart:e.autoStart}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{variant:"primary",size:"sm","aria-label":"save model server",onClick:s,disabled:t||!o,children:"Save server"}),a.jsx(M,{variant:"ghost",size:"sm","aria-label":"cancel model server",onClick:i,disabled:t,children:"Cancel"})]})]})}const Du="";function CT({servers:e,value:t,onChange:n,ariaLabel:r="local model server"}){const i=t!==void 0&&!e.some(s=>s.id===t);return a.jsxs("select",{"aria-label":r,value:t??Du,onChange:s=>n(s.target.value===Du?void 0:s.target.value),className:q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none focus:border-primary"),children:[a.jsx("option",{value:Du,children:"None (external endpoint)"}),e.map(s=>a.jsxs("option",{value:s.id,children:[s.name," — ",s.servedModelName]},s.id)),i&&a.jsxs("option",{value:t,children:[t," (unknown / removed)"]})]})}function jT({mode:e,configured:t,references:n}){if(e==="firstRun")return n.map(l=>({profile:l,selected:!1,available:null}));const r=new Set(t.map(l=>l.id)),i=t.map(l=>({profile:l,selected:!0,available:null})),s=n.filter(l=>!r.has(l.id)).map(l=>({profile:l,selected:!1,available:null}));return[...i,...s]}const NT=3e3;function Da(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function ET(e="firstRun"){const{profile:t}=fe(),[n,r]=g.useState(null),[i,s]=g.useState([]),[l,o]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),f=g.useRef(0),p=g.useRef(null);g.useEffect(()=>()=>{f.current+=1,p.current!==null&&clearTimeout(p.current)},[]);const m=g.useCallback(async(S,N)=>{const R=f.current+1;f.current=R;const D=()=>f.current!==R;d(!0),p.current!==null&&clearTimeout(p.current),p.current=setTimeout(()=>{D()||d(!1)},NT);try{const k=await t.detectProfiles(S);if(D())return;const L=new Map(k.map(A=>[A.profile.id,A.available]));s(A=>A.map(P=>{const I=L.get(P.profile.id)??P.available;return{...P,available:I,selected:N.preselect?I===!0:P.selected}}))}catch(k){if(D())return;N.reportError&&o(Da(k))}finally{D()||(p.current!==null&&clearTimeout(p.current),p.current=null,d(!1))}},[t]),x=g.useCallback(async()=>{u(!0),o(null);let S=null;try{const[N,R]=await Promise.all([t.firstRunState(),e==="edit"?t.listProfiles():Promise.resolve([])]);r(N.isFirstRun);const D=jT({mode:e,configured:R,references:N.referenceProfiles});S=D.map(k=>k.profile),s(D)}catch(N){o(Da(N)),r(!1)}finally{u(!1)}S!==null&&m(S,{preselect:e==="firstRun",reportError:!1})},[t,m,e]);g.useEffect(()=>{x()},[x]);const w=g.useCallback(S=>{s(N=>N.map(R=>R.profile.id===S?{...R,selected:!R.selected}:R))},[]),v=g.useCallback((S,N)=>{s(R=>R.map(D=>D.profile.id===S?{...D,profile:N}:D))},[]),_=g.useCallback(async S=>{o(null);try{const N=await t.cloneOpenCodeProfileFromSeed(S);s(R=>[...R,{profile:N,selected:!0,available:null}])}catch(N){o(Da(N))}},[t]),y=g.useCallback(S=>{s(N=>N.filter(R=>R.profile.id!==S))},[]),b=g.useCallback(async()=>{o(null),await m(i.map(S=>S.profile),{preselect:!1,reportError:!0})},[m,i]),C=g.useCallback(async()=>{u(!0),o(null);try{const S=i.filter(N=>N.selected).map(N=>N.profile);await t.configureProfiles(S),r(!1)}catch(S){o(Da(S))}finally{u(!1)}},[t,i]);return{isFirstRun:n,entries:i,error:l,busy:c,detecting:h,toggle:w,updateProfile:v,addOpenCodeProfile:_,remove:y,detect:b,finish:C,reload:x}}function PT(e){return e.length===0||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:/.test(e)?!1:!e.split(/[/\\]/).includes("..")}function yw(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function bw(e){return e.trim().length===0?!1:e.startsWith("http://")||e.startsWith("https://")}function Ru(e,t){return e===void 0?!0:Number.isInteger(e)&&e>0&&e<=t}const xx=4294967295,AT=65535;function TT(e){const t={};return bw(e.endpoint)||(t.endpoint="Endpoint must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),e.apiKeyEnv!==void 0&&e.apiKeyEnv.length>0&&!yw(e.apiKeyEnv)&&(t.apiKeyEnv="Must be a valid env var name (not the key itself)."),Ru(e.requestTimeoutMs,xx)||(t.requestTimeoutMs="Must be a positive integer (ms)."),Ru(e.connectTimeoutMs,xx)||(t.connectTimeoutMs="Must be a positive integer (ms)."),Ru(e.maxToolIterations,AT)||(t.maxToolIterations="Must be a positive integer."),t}function LT(e){const t={};return bw(e.baseURL)||(t.baseURL="Base URL must start with http:// or https://."),e.model.trim().length===0&&(t.model="Model is required."),t}function DT(e){const t={};e.name.trim().length===0&&(t.name="Name is required."),e.command.trim().length===0&&(t.command="Command is required.");const n=e.contextInjection;return n.strategy==="conventionFile"?PT(n.target)||(t.target="Target must be a relative file name (no .. or absolute)."):n.strategy==="flag"?n.flag.trim().length===0&&(t.flag="Flag is required."):n.strategy==="env"&&(yw(n.var)||(t.var="Must be a valid env var identifier.")),e.structuredAdapter==="openAiCompatible"&&(e.chatHttp?Object.assign(t,TT(e.chatHttp)):(t.endpoint="Endpoint must start with http:// or https://.",t.model="Model is required.")),e.structuredAdapter==="openCode"&&!e.opencodeProvider&&(e.opencode?Object.assign(t,LT(e.opencode)):(t.baseURL="Base URL must start with http:// or https://.",t.model="Model is required.")),t}function RT(){return{endpoint:"http://localhost:11434/v1",model:"qwen2.5-coder",requestTimeoutMs:12e4,connectTimeoutMs:5e3,maxToolIterations:16}}function MT(){return{baseURL:"http://localhost:8080/v1",apiKey:"sk-no-key",model:"qwen3-coder-30b"}}function IT(e){return e.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)}function qe({children:e}){return a.jsx("span",{className:"text-xs font-medium text-muted",children:e})}function ww(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function OT(){const{profile:e}=fe(),[t,n]=g.useState(null),[r,i]=g.useState(!1),[s,l]=g.useState(null),o=g.useCallback(async()=>{i(!0),l(null);try{n(await e.listOpenCodeProviders())}catch(c){n(null),l(ww(c))}finally{i(!1)}},[e]);return g.useEffect(()=>{o()},[o]),{providers:t,loading:r,error:s,reload:()=>void o()}}function Sw({onDone:e,forceOpen:t=!1}){const n=ET(t?"edit":"firstRun"),r=cT(),i=OT();if(n.isFirstRun===null||!t&&n.isFirstRun===!1)return null;async function s(){await n.finish(),e?.()}return a.jsx(Se,{"aria-label":"first run setup",className:"border-primary/40",title:a.jsxs("div",{className:"flex flex-col",children:[a.jsx("h2",{className:"text-base font-semibold text-content",children:"Welcome to IdeA"}),a.jsx("p",{className:"text-sm text-muted",children:"Choose which AI CLIs to configure. Commands are pre-filled and editable."})]}),children:a.jsxs("div",{className:"flex flex-col gap-4",children:[n.error&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),a.jsxs(pw,{children:[a.jsx(M,{onClick:()=>void n.detect(),disabled:n.busy,className:"whitespace-nowrap",children:"Detect installed CLIs"}),n.detecting&&a.jsx("span",{role:"status",className:"text-xs text-muted",children:"Detecting…"}),a.jsx(M,{onClick:()=>void n.addOpenCodeProfile(),disabled:n.busy,className:"whitespace-nowrap",children:"Add OpenCode profile"})]}),a.jsx(bT,{vm:r}),a.jsx("ul",{className:"flex list-none flex-col gap-3 p-0",children:n.entries.map(l=>a.jsx(BT,{entry:l,servers:r.servers,providerCatalog:i,onToggle:()=>n.toggle(l.profile.id),onChange:o=>n.updateProfile(l.profile.id,o),onRemove:()=>n.remove(l.profile.id),onDuplicate:l.profile.structuredAdapter==="openCode"?()=>n.addOpenCodeProfile({name:`${l.profile.name} (copy)`,opencode:l.profile.opencode}):void 0},l.profile.id))}),a.jsx("footer",{className:"flex gap-2",children:a.jsx(M,{variant:"primary",onClick:()=>void s(),disabled:n.busy,children:"Save and continue"})})]})})}function BT({entry:e,servers:t,providerCatalog:n,onToggle:r,onChange:i,onRemove:s,onDuplicate:l}){const{profile:o,selected:c,available:u}=e,h=DT(o),d=o.structuredAdapter==="openCode";return a.jsxs("li",{className:"flex flex-col gap-2 rounded-md border border-border bg-raised p-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:r,"aria-label":`use ${o.name}`,className:"accent-primary"}),a.jsx("strong",{className:"text-sm text-content",children:o.name})]}),a.jsx("span",{"aria-label":`${o.name} availability`,className:q("text-xs",u===null?"text-faint":u?"text-success":"text-danger"),children:u===null?"—":u?"✓ installed":"✗ not found"}),a.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[l&&a.jsx(M,{size:"sm","aria-label":`duplicate ${o.name}`,onClick:l,children:"Duplicate"}),a.jsx(ir,{size:"sm","aria-label":`remove ${o.name}`,onClick:s,children:"×"})]})]}),d&&a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Name"}),a.jsx(oe,{"aria-label":`${o.name} name`,value:o.name,invalid:!!h.name,onChange:f=>i({...o,name:f.target.value})}),h.name&&a.jsx("small",{className:"text-xs text-danger",children:h.name})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Command"}),a.jsx(oe,{"aria-label":`${o.name} command`,value:o.command,invalid:!!h.command,onChange:f=>i({...o,command:f.target.value})}),h.command&&a.jsx("small",{className:"text-xs text-danger",children:h.command})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Arguments"}),a.jsx(oe,{"aria-label":`${o.name} args`,value:o.args.join(" "),onChange:f=>i({...o,args:IT(f.target.value)})})]}),o.structuredAdapter==="openAiCompatible"&&a.jsx(WT,{profile:o,errors:h,onChange:i}),o.structuredAdapter==="openCode"&&a.jsx(zT,{profile:o,errors:h,servers:t,providerCatalog:n,onChange:i})]})}function zT({profile:e,errors:t,servers:n,providerCatalog:r,onChange:i}){const[s,l]=g.useState(e.opencodeProvider?"cloud":"local");return a.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[a.jsx("div",{role:"radiogroup","aria-label":"mode du profil OpenCode",className:"flex w-fit gap-1 rounded-md border border-border bg-raised p-0.5",children:[{id:"local",label:"Local (llama.cpp)"},{id:"cloud",label:"Provider cloud"}].map(o=>{const c=s===o.id;return a.jsx("button",{type:"button",role:"radio","aria-checked":c,onClick:()=>l(o.id),className:q("rounded px-2.5 py-1 text-xs font-medium transition-colors",c?"bg-primary text-on-primary":"text-muted hover:text-content"),children:o.label},o.id)})}),s==="local"&&a.jsx($T,{profile:e,errors:t,servers:n,onChange:i}),s==="cloud"&&a.jsx(FT,{profile:e,catalog:r,onChange:i})]})}const vx="__custom__",_x="@ai-sdk/openai-compatible";function FT({profile:e,catalog:t,onChange:n}){const{profile:r}=fe(),i=e.opencodeProvider,[s,l]=g.useState(i?.custom?"custom":"catalog"),[o,c]=g.useState(i?.providerId??""),[u,h]=g.useState(i?.model??""),[d,f]=g.useState(""),[p,m]=g.useState(i?.custom?.npm??_x),[x,w]=g.useState(i?.custom?.baseUrl??""),[v,_]=g.useState(i?.custom?.displayName??""),[y,b]=g.useState(""),[C,S]=g.useState(!1),[N,R]=g.useState(!1),[D,k]=g.useState(null),[L,A]=g.useState({}),P=i!==void 0,I=t.providers?.find(F=>F.providerId===o)?.models??[],O=t.providers!==null&&!t.loading,U=(t.providers??[]).filter(F=>{if(F.providerId===o)return!0;const j=d.trim().toLowerCase();return j.length===0?!0:F.displayName.toLowerCase().includes(j)||F.providerId.toLowerCase().includes(j)}),K=N||y.length===0||s==="catalog"&&(!O||!!t.error);async function E(){const F={};if(o.trim().length===0&&(F.providerId="Le provider est obligatoire."),u.trim().length===0&&(F.model="Le modèle est obligatoire."),s==="custom"&&(p.trim().length===0&&(F.npm="Le paquet npm est obligatoire."),x.trim().length===0&&(F.baseUrl="L'URL de base est obligatoire.")),y.length===0&&(F.apiKey="La clé API est obligatoire."),A(F),!(Object.keys(F).length>0)){R(!0),k(null);try{const j=await r.saveOpenCodeProviderProfile({profile:e,providerId:o.trim(),model:u.trim(),apiKey:y,...s==="custom"?{custom:{npm:p.trim(),baseUrl:x.trim(),displayName:v.trim().length>0?v.trim():void 0}}:{}});n(j),b("")}catch(j){k(ww(j))}finally{R(!1)}}}return a.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider cloud (OpenCode)"}),D&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:D}),t.loading&&a.jsx("p",{className:"text-xs text-faint",children:"Chargement des providers…"}),t.error&&a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("p",{role:"alert",className:"text-sm text-danger",children:"Impossible de charger la liste des providers cloud."}),a.jsx(M,{size:"sm",onClick:()=>t.reload(),className:"w-fit",children:"Réessayer"})]}),s==="catalog"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Provider"}),O&&a.jsx("input",{type:"text","aria-label":`${e.name} provider search`,placeholder:"Rechercher un provider…",value:d,onChange:F=>f(F.target.value),className:"h-8 w-full rounded-md border border-border bg-raised px-3 text-xs text-content outline-none"}),a.jsxs("select",{"aria-label":`${e.name} provider`,value:o,disabled:!O,onChange:F=>{const j=F.target.value;j===vx?(l("custom"),c(""),h("")):(c(j),h("")),A(re=>({...re,providerId:void 0}))},className:q("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",L.providerId?"border-danger":"border-border"),children:[a.jsx("option",{value:"",disabled:!0,children:t.loading?"Chargement des providers…":"Choisir un provider…"}),U.map(F=>a.jsx("option",{value:F.providerId,children:F.displayName},F.providerId)),a.jsx("option",{value:vx,children:"Autre / personnalisé…"})]}),L.providerId&&a.jsx("small",{className:"text-xs text-danger",children:L.providerId})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Modèle"}),a.jsxs("select",{"aria-label":`${e.name} model`,value:u,disabled:o.length===0,onChange:F=>{h(F.target.value),A(j=>({...j,model:void 0}))},className:q("h-9 w-full rounded-md border bg-raised px-3 text-sm text-content outline-none","disabled:cursor-not-allowed disabled:opacity-50",L.model?"border-danger":"border-border"),children:[a.jsx("option",{value:"",disabled:!0,children:o.length===0?"—":"Choisir un modèle…"}),I.map(F=>a.jsx("option",{value:F,children:F},F))]}),L.model&&a.jsx("small",{className:"text-xs text-danger",children:L.model})]})]}),s==="custom"&&a.jsxs("fieldset",{className:"flex flex-col gap-2 rounded-md border border-border/50 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Provider personnalisé"}),a.jsx(M,{variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{l("catalog"),c(""),h(""),A({})},children:"← Choisir un provider du catalogue"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Identifiant du provider"}),a.jsx(oe,{"aria-label":`${e.name} custom provider id`,value:o,placeholder:"ex. mon-provider",invalid:!!L.providerId,onChange:F=>{c(F.target.value),A(j=>({...j,providerId:void 0}))}}),L.providerId&&a.jsx("small",{className:"text-xs text-danger",children:L.providerId})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Paquet npm"}),a.jsx(oe,{"aria-label":`${e.name} custom npm package`,value:p,placeholder:_x,invalid:!!L.npm,onChange:F=>{m(F.target.value),A(j=>({...j,npm:void 0}))}}),L.npm&&a.jsx("small",{className:"text-xs text-danger",children:L.npm})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"URL de base"}),a.jsx(oe,{"aria-label":`${e.name} custom base url`,value:x,placeholder:"https://api.mon-provider.example/v1",invalid:!!L.baseUrl,onChange:F=>{w(F.target.value),A(j=>({...j,baseUrl:void 0}))}}),L.baseUrl&&a.jsx("small",{className:"text-xs text-danger",children:L.baseUrl})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Modèle"}),a.jsx(oe,{"aria-label":`${e.name} model`,value:u,placeholder:"ex. mon-modele-1",invalid:!!L.model,onChange:F=>{h(F.target.value),A(j=>({...j,model:void 0}))}}),L.model&&a.jsx("small",{className:"text-xs text-danger",children:L.model})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Libellé du modèle (optionnel)"}),a.jsx(oe,{"aria-label":`${e.name} custom display name`,value:v,placeholder:"ex. Mon modèle",onChange:F=>_(F.target.value)})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Clé API"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(oe,{"aria-label":`${e.name} api key`,type:C?"text":"password",value:y,placeholder:P?"Ressaisissez la clé API pour confirmer l'enregistrement":"ex. sk-ant-…",invalid:!!L.apiKey,onChange:F=>{b(F.target.value),A(j=>({...j,apiKey:void 0}))}}),a.jsx(ir,{size:"sm","aria-label":"afficher/masquer la clé API",onClick:()=>S(F=>!F),children:C?"🙈":"👁"})]}),L.apiKey&&a.jsx("small",{className:"text-xs text-danger",children:L.apiKey}),a.jsx("small",{className:"text-xs text-faint",children:"Jamais affichée ni renvoyée par IdeA une fois enregistrée ; stockée chiffrée localement."}),P&&a.jsx("small",{className:"text-xs text-muted",children:"Pour des raisons de sécurité, la clé n'est jamais réaffichée : ressaisissez-la à chaque modification de ce profil."})]}),a.jsx(M,{variant:"primary",size:"sm",loading:N,disabled:K,onClick:()=>void E(),className:"w-fit",children:"Enregistrer"})]})}function $T({profile:e,errors:t,servers:n,onChange:r}){const i=e.opencode??MT(),s=l=>r({...e,opencode:{...i,...l}});return a.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local model (OpenCode + llama.cpp)"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Base URL"}),a.jsx(oe,{"aria-label":`${e.name} base url`,value:i.baseURL,placeholder:"http://localhost:8080/v1",invalid:!!t.baseURL,onChange:l=>s({baseURL:l.target.value})}),t.baseURL&&a.jsx("small",{className:"text-xs text-danger",children:t.baseURL})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Model"}),a.jsx(oe,{"aria-label":`${e.name} model`,value:i.model,placeholder:"qwen3-coder-30b",invalid:!!t.model,onChange:l=>s({model:l.target.value})}),t.model&&a.jsx("small",{className:"text-xs text-danger",children:t.model})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"API key (optional — a local llama.cpp needs none)"}),a.jsx(oe,{"aria-label":`${e.name} api key`,value:i.apiKey??"",placeholder:"e.g. sk-no-key",onChange:l=>{const o=l.target.value;s({apiKey:o.length===0?void 0:o})}})]}),a.jsxs("div",{className:"flex flex-wrap gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":`${e.name} reasoning`,checked:i.reasoning??!0,onChange:l=>s({reasoning:l.target.checked}),className:"accent-primary"}),a.jsx(qe,{children:"Reasoning"})]}),a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox","aria-label":`${e.name} attachment`,checked:i.attachment??!1,onChange:l=>s({attachment:l.target.checked}),className:"accent-primary"}),a.jsx(qe,{children:"Attachments"})]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Local model server (bind to a managed llama.cpp server, or none)"}),a.jsx(CT,{ariaLabel:`${e.name} local model server`,servers:n,value:i.localModelServerId,onChange:l=>s({localModelServerId:l})})]})]})}function Mu(e){const t=e.trim();if(t.length===0)return;const n=Number(t);return Number.isFinite(n)?n:NaN}function WT({profile:e,errors:t,onChange:n}){const r=e.chatHttp??RT(),i=s=>n({...e,chatHttp:{...r,...s}});return a.jsxs("fieldset",{className:"mt-1 flex flex-col gap-2 rounded-md border border-border/70 p-2",children:[a.jsx("legend",{className:"px-1 text-xs font-medium text-muted",children:"Local / LAN model (OpenAI-compatible)"}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Endpoint"}),a.jsx(oe,{"aria-label":`${e.name} endpoint`,value:r.endpoint,placeholder:"http://localhost:11434/v1",invalid:!!t.endpoint,onChange:s=>i({endpoint:s.target.value})}),t.endpoint&&a.jsx("small",{className:"text-xs text-danger",children:t.endpoint})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"Model"}),a.jsx(oe,{"aria-label":`${e.name} model`,value:r.model,placeholder:"qwen2.5-coder",invalid:!!t.model,onChange:s=>i({model:s.target.value})}),t.model&&a.jsx("small",{className:"text-xs text-danger",children:t.model})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx(qe,{children:"API key — environment variable name (never the key itself)"}),a.jsx(oe,{"aria-label":`${e.name} api key env`,value:r.apiKeyEnv??"",placeholder:"e.g. OPENAI_API_KEY (variable name, not the secret)",invalid:!!t.apiKeyEnv,onChange:s=>{const l=s.target.value.trim();i({apiKeyEnv:l.length===0?void 0:l})}}),t.apiKeyEnv&&a.jsx("small",{className:"text-xs text-danger",children:t.apiKeyEnv})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsx(qe,{children:"Request timeout (ms)"}),a.jsx(oe,{"aria-label":`${e.name} request timeout`,value:r.requestTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.requestTimeoutMs,onChange:s=>i({requestTimeoutMs:Mu(s.target.value)})}),t.requestTimeoutMs&&a.jsx("small",{className:"text-xs text-danger",children:t.requestTimeoutMs})]}),a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsx(qe,{children:"Connect timeout (ms)"}),a.jsx(oe,{"aria-label":`${e.name} connect timeout`,value:r.connectTimeoutMs?.toString()??"",inputMode:"numeric",invalid:!!t.connectTimeoutMs,onChange:s=>i({connectTimeoutMs:Mu(s.target.value)})}),t.connectTimeoutMs&&a.jsx("small",{className:"text-xs text-danger",children:t.connectTimeoutMs})]}),a.jsxs("label",{className:"flex min-w-[8rem] flex-1 flex-col gap-1",children:[a.jsx(qe,{children:"Max tool iterations"}),a.jsx(oe,{"aria-label":`${e.name} max tool iterations`,value:r.maxToolIterations?.toString()??"",inputMode:"numeric",invalid:!!t.maxToolIterations,onChange:s=>i({maxToolIterations:Mu(s.target.value)})}),t.maxToolIterations&&a.jsx("small",{className:"text-xs text-danger",children:t.maxToolIterations})]})]})]})}function kw(){const{profile:e}=fe(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(!1),o=g.useCallback(async()=>{i(null);try{n(await e.listProfiles())}catch(u){i(u&&typeof u=="object"&&"message"in u?String(u.message):String(u))}},[e]);g.useEffect(()=>{o()},[o]);async function c(u){await e.deleteProfile(u),await o()}return s?a.jsx(Sw,{forceOpen:!0,onDone:()=>{l(!1),o()}}):a.jsx(Se,{"aria-label":"ai profiles settings",title:"Profils IA",actions:a.jsx(M,{size:"sm",onClick:()=>l(!0),children:"Configurer les profils"}),children:a.jsxs("div",{className:"flex flex-col gap-3",children:[r&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:r}),t.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun profil configuré."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(u=>a.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[a.jsxs("span",{className:"flex items-baseline gap-2",children:[a.jsx("strong",{className:"text-sm text-content",children:u.name}),a.jsx("code",{className:"text-xs text-muted",children:u.command})]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`supprimer ${u.name}`,onClick:()=>void c(u.id),children:"Supprimer"})]},u.id))})]})})}const HT=3e3,UT=2500;function yx(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function qT(){const{device:e}=fe(),[t,n]=g.useState(null),[r,i]=g.useState(null),[s,l]=g.useState(!1),[o,c]=g.useState(!1),[u,h]=g.useState(null),[d,f]=g.useState([]),[p,m]=g.useState(!1),x=g.useRef(null),w=g.useCallback(async()=>{try{const R=await e.listDevices();return n(R),i(null),R}catch(R){return i(yx(R)),null}},[e]),v=g.useCallback(async()=>{const R=await w();R&&(x.current=new Set(R.map(D=>D.deviceId)))},[w]);g.useEffect(()=>{v()},[v]),g.useEffect(()=>{if(!u)return;const R=setInterval(()=>{(async()=>{const D=await w();if(!D)return;const k=x.current;if(x.current=new Set(D.map(A=>A.deviceId)),!k)return;const L=D.filter(A=>!k.has(A.deviceId)).map(A=>A.deviceId);L.length>0&&f(L)})()},HT);return()=>clearInterval(R)},[u,w]),g.useEffect(()=>{if(d.length===0)return;const R=setTimeout(()=>f([]),UT);return()=>clearTimeout(R)},[d]);const _=g.useCallback(async R=>{l(!0),i(null);try{return await R(),!0}catch(D){return i(yx(D)),!1}finally{l(!1)}},[]),y=g.useCallback(async()=>{c(!0);try{await _(async()=>{h(await e.createPairingCode())})}finally{c(!1)}},[e,_]),b=g.useCallback(()=>h(null),[]),C=g.useCallback(async(R,D)=>{await _(()=>e.renameDevice(R,D))&&await v()},[e,_,v]),S=g.useCallback(async R=>{const D=R.isCurrentDevice;await _(()=>e.revokeDevice(R.deviceId))&&(D?m(!0):await v())},[e,_,v]),N=g.useCallback(async()=>{const R=t?.some(D=>D.isCurrentDevice)??!1;await _(()=>e.revokeAllDevices())&&(R?m(!0):await v())},[t,e,_,v]);return{devices:t,error:r,busy:s,generating:o,code:u,freshDeviceIds:d,sessionEnded:p,refresh:v,generateCode:y,dismissCode:b,rename:C,revoke:S,revokeAll:N}}const VT=2*60*1e3;function bx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function KT(e){return e.toLocaleTimeString("fr-FR",{hour:"2-digit",minute:"2-digit"})}function Cw(e,t=new Date){const n=new Date(e),r=n.getFullYear()===t.getFullYear();return n.toLocaleDateString("fr-FR",{day:"numeric",month:"short",...r?{}:{year:"numeric"}})}function GT(e,t=new Date){if(t.getTime()-eIu(e.expiresAtMs)),[s,l]=g.useState(!1);g.useEffect(()=>{i(Iu(e.expiresAtMs));const c=setInterval(()=>i(Iu(e.expiresAtMs)),1e3);return()=>clearInterval(c)},[e.expiresAtMs]),g.useEffect(()=>{l(!1)},[e.code]),g.useEffect(()=>{if(!s)return;const c=setTimeout(()=>l(!1),2e3);return()=>clearTimeout(c)},[s]);const o=r===null;return a.jsx(Se,{"data-testid":"pairing-code-panel",className:"flex flex-col gap-3",children:o?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-muted",children:"Ce code a expiré."}),a.jsx("div",{children:a.jsx(M,{size:"sm",onClick:t,children:"Générer un nouveau code"})})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-muted",children:"Saisissez ce code sur le nouvel appareil."}),a.jsx("p",{"data-testid":"pairing-code-value","aria-label":e.code,className:"flex gap-3 font-mono text-2xl font-semibold tracking-[0.2em] text-content sm:text-3xl",children:XT(e.code).map((c,u)=>a.jsx("span",{"aria-hidden":"true",children:c},u))}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void QT(e.code).then(c=>l(c)),children:s?"Copié":"Copier"}),a.jsx("span",{className:"text-xs text-faint","data-testid":"pairing-code-countdown",children:r}),a.jsx(M,{size:"sm",variant:"ghost",className:"ml-auto",onClick:n,children:"Fermer"})]})]})})}function wx({title:e,body:t,confirmLabel:n,danger:r=!1,busy:i=!1,onConfirm:s,onCancel:l}){const o=g.useRef(null);return g.useEffect(()=>{o.current?.focus()},[]),g.useEffect(()=>{function c(u){u.key==="Escape"&&l()}return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[l]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.floatingWindow},onClick:l,children:a.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e,onClick:c=>c.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"text-sm text-muted",children:t}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{ref:o,size:"sm",variant:"ghost",onClick:l,children:"Annuler"}),a.jsx(M,{size:"sm",variant:r?"danger":"primary",loading:i,onClick:()=>void s(),children:n})]})]})})}const gp=40,jw="Cet appareil",ZT=[[/\bEdg(?:e|A|iOS)?\//,"Edge"],[/\bOPR\/|\bOpera\//,"Opera"],[/\bFirefox\/|\bFxiOS\//,"Firefox"],[/\bChrome\/|\bCriOS\//,"Chrome"],[/\bSafari\//,"Safari"]],eL=[[/\bWindows\b/,"Windows"],[/\bMac OS X\b|\bMacintosh\b/,"Mac"],[/\bCrOS\b/,"ChromeOS"],[/\bLinux\b|\bX11\b/,"Linux"]];function tL(e){const t=e??"";if(/\biPhone\b/.test(t))return"iPhone";if(/\biPad\b/.test(t))return"iPad";if(/\bAndroid\b/.test(t))return"Android";const n=ZT.find(([i])=>i.test(t))?.[1],r=eL.find(([i])=>i.test(t))?.[1];return n&&r?`${n} sur ${r}`:n??r??jw}function Sx(e){return Array.from(e.trim()).slice(0,gp).join("")}function nL(){return typeof navigator>"u"||!navigator.userAgent?jw:tL(navigator.userAgent)}function Nw({onSessionEnded:e}){const t=qT(),[n,r]=g.useState(null),[i,s]=g.useState(!1),[l,o]=g.useState(null);g.useEffect(()=>{t.sessionEnded&&e?.()},[t.sessionEnded,e]);const c=t.devices;return a.jsxs("section",{"data-testid":"devices-screen",className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Appareils"}),a.jsx("p",{className:"text-sm text-muted",children:"Les appareils autorisés à accéder à cette instance IdeA."})]}),a.jsx(M,{onClick:()=>void t.generateCode(),loading:t.generating,children:"Appairer"})]}),t.code&&a.jsx(JT,{code:t.code,onRegenerate:()=>void t.generateCode(),onDismiss:t.dismissCode}),t.error&&a.jsx(Se,{className:"border-danger/40",children:a.jsx("p",{role:"alert",className:"text-sm text-danger",children:t.error})}),c===null?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Me,{size:12})," Chargement des appareils…"]}):c.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun appareil appairé."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"device-list",children:c.map(u=>a.jsx(rL,{device:u,fresh:t.freshDeviceIds.includes(u.deviceId),renaming:l===u.deviceId,onStartRename:()=>o(u.deviceId),onCancelRename:()=>o(null),onRename:async h=>{await t.rename(u.deviceId,h),o(null)},onRevoke:()=>r(u)},u.deviceId))}),c!==null&&c.length>0&&a.jsx("div",{className:"pt-1",children:a.jsx(M,{variant:"ghost",size:"sm",onClick:()=>s(!0),children:"Révoquer tous les appareils"})}),n&&a.jsx(wx,{title:"Révoquer cet appareil ?",body:n.isCurrentDevice?"Il devra être appairé à nouveau pour accéder à IdeA. Vous serez déconnecté immédiatement.":"Il devra être appairé à nouveau pour accéder à IdeA.",confirmLabel:"Révoquer",busy:t.busy,onConfirm:async()=>{const u=n;r(null),await t.revoke(u)},onCancel:()=>r(null)}),i&&a.jsx(wx,{title:"Révoquer tous les appareils ?",body:"Tous les appareils, y compris celui-ci, devront être appairés à nouveau. Vous serez déconnecté immédiatement.",confirmLabel:"Tout révoquer",danger:!0,busy:t.busy,onConfirm:async()=>{s(!1),await t.revokeAll()},onCancel:()=>s(!1)})]})}function rL({device:e,fresh:t,renaming:n,onStartRename:r,onCancelRename:i,onRename:s,onRevoke:l}){return a.jsx("li",{"data-testid":"device-row","data-fresh":t||void 0,className:q("py-3 transition-colors first:pt-0 last:pb-0",t&&"bg-success/10"),children:n?a.jsx(iL,{device:e,onSubmit:s,onCancel:i}):a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:e.name}),e.isCurrentDevice&&a.jsx("span",{className:"shrink-0 rounded-full bg-primary/15 px-2 py-0.5 text-[0.65rem] font-medium text-primary",children:"Cet appareil"})]}),a.jsx("span",{className:"text-xs text-muted",children:GT(e.lastSeenAtMs)}),a.jsx("span",{className:"text-[0.7rem] text-faint",children:YT(e.pairedAtMs)})]}),a.jsx(sL,{deviceName:e.name,onRename:r,onRevoke:l})]})})}function iL({device:e,onSubmit:t,onCancel:n}){const[r,i]=g.useState(e.name),s=r.trim();return a.jsxs("form",{className:"flex flex-col gap-2",onSubmit:l=>{l.preventDefault(),s.length>0&&t(s)},children:[a.jsx(qt,{label:"Nom de l'appareil",hideLabel:!0,children:({id:l})=>a.jsx(oe,{id:l,value:r,autoFocus:!0,maxLength:gp,onChange:o=>i(o.target.value),onKeyDown:o=>{o.key==="Escape"&&n()}})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{type:"submit",size:"sm",disabled:s.length===0,children:"Renommer"}),a.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:n,children:"Annuler"})]})]})}function sL({deviceName:e,onRename:t,onRevoke:n}){const[r,i]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const s=()=>i(!1);return window.addEventListener("click",s),()=>window.removeEventListener("click",s)},[r]),a.jsxs("div",{className:"relative shrink-0",onClick:s=>s.stopPropagation(),children:[a.jsx("button",{type:"button","aria-haspopup":"menu","aria-expanded":r,"aria-label":`Actions pour ${e}`,onClick:()=>i(s=>!s),className:"rounded-md px-2 py-1 text-sm text-muted transition-colors hover:bg-raised hover:text-content",children:"⋯"}),r&&a.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-10 mt-1 flex min-w-36 flex-col rounded-md border border-border bg-raised py-1 shadow-lg",children:[a.jsx("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),t()},className:"px-3 py-1.5 text-left text-sm text-content transition-colors hover:bg-canvas",children:"Renommer"}),a.jsx("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),n()},className:"px-3 py-1.5 text-left text-sm text-danger transition-colors hover:bg-canvas",children:"Révoquer"})]})]})}const lL=250;function Vs(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function aL(){const{desktopServer:e}=fe(),[t,n]=g.useState(null),[r,i]=g.useState({state:"stopped"}),[s,l]=g.useState([]),[o,c]=g.useState(),[u,h]=g.useState([]),[d,f]=g.useState(null),[p,m]=g.useState(null),[x,w]=g.useState(!1),[v,_]=g.useState(!1),y=g.useRef(0);g.useEffect(()=>{let P=!0;return(async()=>{try{const[I,O]=await Promise.all([e.getExposureSettings(),e.status()]);if(!P)return;n(I),i(O)}catch(I){P&&m(Vs(I))}})(),()=>{P=!1}},[e]),g.useEffect(()=>{let P=!0;return(async()=>{try{const I=await e.previewExposure({mode:"localOnly",autoStart:!1,port:0,trustedProxies:[]});P&&l(I.candidateLanAddresses)}catch{}})(),()=>{P=!1}},[e]),g.useEffect(()=>{let P,I=!1;return e.onStatusChanged(i).then(O=>{I?O():P=O}),()=>{I=!0,P?.()}},[e]),g.useEffect(()=>{if(!t)return;const P=++y.current,I=setTimeout(()=>{e.previewExposure(t).then(O=>{P===y.current&&(c(O.upstreamUrl),h(O.warnings),f(null))},O=>{P===y.current&&(c(void 0),h([]),f(Vs(O)))})},lL);return()=>clearTimeout(I)},[e,t]);const b=g.useCallback(P=>{m(null),n(I=>I&&{...I,...P})},[]),C=g.useCallback(P=>{b(P==="localOnly"?{mode:P,publicOrigin:void 0,lanBindAddress:void 0,trustedProxies:[]}:P==="remoteProxyLocal"?{mode:P,lanBindAddress:void 0,trustedProxies:[]}:{mode:P})},[b]),S=g.useCallback(P=>b({publicOrigin:P.trim()||void 0}),[b]),N=g.useCallback(P=>b({lanBindAddress:P||void 0}),[b]),R=g.useCallback(P=>b({trustedProxies:P.split(/[\s,]+/).map(I=>I.trim()).filter(Boolean)}),[b]),D=g.useCallback(P=>b({port:P}),[b]),k=g.useCallback(async P=>{if(!t)return;const I={...t,autoStart:P};_(!0),m(null);try{await e.saveExposureSettings(I),n(I)}catch(O){m(Vs(O))}finally{_(!1)}},[e,t]),L=g.useCallback(async()=>{if(t){w(!0),m(null);try{await e.saveExposureSettings(t),i(await e.start())}catch(P){m(Vs(P))}finally{w(!1)}}},[e,t]),A=g.useCallback(async()=>{w(!0),m(null);try{i(await e.stop())}catch(P){m(Vs(P))}finally{w(!1)}},[e]);return{ready:t!==null,settings:t,status:r,candidateLanAddresses:s,upstreamUrl:o,warnings:u,validationError:d,actionError:p,busy:x,autoStartBusy:v,setMode:C,setPublicOrigin:S,setLanBindAddress:N,setTrustedProxies:R,setPort:D,setAutoStart:k,start:L,stop:A}}const oL=[{mode:"localOnly",title:"Cet ordinateur uniquement",description:"Pour utiliser IdeA uniquement sur cet ordinateur. Les appareils distants ne peuvent pas se connecter."},{mode:"remoteProxyLocal",title:"Accès distant, proxy sur cet ordinateur",description:"À utiliser quand le proxy HTTPS tourne sur la même machine qu'IdeA Desktop."},{mode:"remoteProxyOtherMachine",title:"Accès distant, proxy sur une autre machine",description:"À utiliser quand le proxy HTTPS tourne sur une autre machine. IdeA n'acceptera que le trafic provenant de ce proxy."}],cL={stopped:"Arrêté",starting:"Démarrage…",running:"En cours d'exécution",stopping:"Arrêt…",failed:"Échec"};function uL({value:e,label:t}){const[n,r]=g.useState(!1),i=typeof navigator<"u"&&!!navigator.clipboard;return a.jsx(M,{size:"sm",variant:"ghost","aria-label":t,disabled:!i,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),window.setTimeout(()=>r(!1),1500)},()=>r(!1))},children:n?"Copié":"Copier"})}function dL({value:e,copyLabel:t}){return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("code",{className:"flex-1 truncate rounded-md border border-border bg-raised px-2 py-1.5 font-mono text-xs text-content",children:e}),a.jsx(uL,{value:e,label:t})]})}function hL(){const e=aL(),t=g.useRef(null);if(!e.ready||!e.settings)return a.jsx(Se,{"aria-label":"deployment settings",title:"Déploiement",children:a.jsx("p",{className:"text-sm text-muted",children:"Chargement…"})});const{settings:n,status:r}=e,i=r.state==="running",s=n.mode!=="localOnly",l=n.mode==="remoteProxyOtherMachine",o=r.state==="starting"||r.state==="stopping";return a.jsxs("div",{"aria-label":"deployment settings",className:"flex flex-col gap-4",children:[a.jsx(Se,{title:"Serveur",actions:i||r.state==="stopping"?a.jsx(M,{size:"sm",onClick:()=>void e.stop(),disabled:e.busy||o,children:"Arrêter"}):a.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy||o,children:"Démarrer"}),children:a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsxs("p",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{"aria-hidden":!0,className:q("size-2 rounded-full",i&&"bg-success",r.state==="failed"&&"bg-danger",(r.state==="stopped"||o)&&"bg-faint")}),a.jsx("span",{className:"text-content",children:cL[r.state]})]}),r.localUrl&&a.jsxs("p",{className:"text-xs text-muted",children:["URL locale : ",a.jsx("code",{className:"font-mono text-content",children:r.localUrl})]}),r.publicUrl&&a.jsxs("p",{className:"text-xs text-muted",children:["URL publique : ",a.jsx("code",{className:"font-mono text-content",children:r.publicUrl})]}),r.state==="failed"&&r.error&&(r.error.code==="PORT_IN_USE"?a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsxs("p",{role:"alert",className:"text-sm text-danger",children:["Le serveur n'a pas démarré automatiquement. ",r.error.message]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>{t.current?.scrollIntoView?.({behavior:"smooth",block:"center"}),t.current?.focus()},children:"Modifier le port"}),a.jsx(M,{size:"sm",onClick:()=>void e.start(),disabled:e.busy,children:"Réessayer"})]})]}):a.jsx("p",{role:"alert",className:"text-sm text-danger",children:r.error.message})),e.actionError&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.actionError}),a.jsxs("label",{className:"flex cursor-pointer items-start gap-2 pt-2",children:[a.jsx("input",{type:"checkbox",className:"mt-0.5","aria-label":"Démarrer le serveur au lancement d'IdeA",checked:n.autoStart,disabled:e.autoStartBusy,onChange:c=>void e.setAutoStart(c.target.checked)}),a.jsxs("span",{className:"flex flex-col gap-0.5",children:[a.jsx("span",{className:"text-sm text-content",children:"Démarrer le serveur au lancement d'IdeA"}),a.jsx("span",{className:"text-xs text-muted",children:"IdeA utilisera les réglages réseau enregistrés ci-dessous au prochain démarrage de l'application desktop."})]})]})]})}),a.jsx(Se,{title:"Accès réseau",children:a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx("div",{role:"radiogroup","aria-label":"mode d'accès réseau",className:"flex flex-col gap-2",children:oL.map(c=>{const u=n.mode===c.mode;return a.jsxs("label",{className:q("flex cursor-pointer gap-3 rounded-lg border p-3 transition-colors",u?"border-border-strong bg-raised":"border-border hover:bg-raised"),children:[a.jsx("input",{type:"radio",name:"exposure-mode",className:"mt-1",checked:u,onChange:()=>e.setMode(c.mode)}),a.jsxs("span",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),a.jsx("span",{className:"text-xs text-muted",children:c.description})]})]},c.mode)})}),a.jsx(qt,{label:"Port",children:({id:c})=>a.jsx(oe,{ref:t,id:c,type:"number",value:String(n.port),onChange:u=>e.setPort(Number(u.target.value))})}),s&&a.jsx(qt,{label:"Origine publique",hint:"Exemple : https://idea.example.com",children:({id:c,describedBy:u})=>a.jsx(oe,{id:c,"aria-describedby":u,placeholder:"https://idea.example.com",value:n.publicOrigin??"",onChange:h=>e.setPublicOrigin(h.target.value)})}),l&&a.jsxs(a.Fragment,{children:[a.jsx(qt,{label:"Adresse LAN d'écoute",hint:"L'adresse de cette machine à laquelle le proxy se connectera.",children:({id:c,describedBy:u})=>e.candidateLanAddresses.length>0?a.jsxs("select",{id:c,"aria-describedby":u,className:"rounded-md border border-border bg-surface px-2 py-1.5 text-sm text-content",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value),children:[a.jsx("option",{value:"",children:"Sélectionner une adresse…"}),e.candidateLanAddresses.map(h=>a.jsx("option",{value:h,children:h},h))]}):a.jsx(oe,{id:c,"aria-describedby":u,placeholder:"192.168.1.42",value:n.lanBindAddress??"",onChange:h=>e.setLanBindAddress(h.target.value)})}),a.jsx(qt,{label:"IP/CIDR du proxy autorisé",hint:"Ce n'est pas l'adresse d'écoute d'IdeA. C'est la machine autorisée à contacter IdeA.",children:({id:c,describedBy:u})=>a.jsx(oe,{id:c,"aria-describedby":u,placeholder:"203.0.113.7 or 203.0.113.0/24",value:n.trustedProxies.join(", "),onChange:h=>e.setTrustedProxies(h.target.value)})}),a.jsx("p",{className:"rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Si votre proxy n'est pas sur cet ordinateur, choisissez ce mode. Sinon, le proxy peut expirer sans erreur IdeA."})]}),e.warnings.map(c=>a.jsx("p",{className:"text-xs text-warning",children:c.message},c.code)),e.validationError&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:e.validationError})]})}),s&&a.jsx(Se,{title:"Configuration du proxy",children:a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("p",{className:"text-xs text-muted",children:"Faites pointer votre proxy inverse HTTPS vers cet upstream."}),e.upstreamUrl?a.jsx(dL,{value:e.upstreamUrl,copyLabel:"copier l'URL upstream"}):a.jsx("p",{className:"text-xs text-faint",children:"Complétez les paramètres ci-dessus pour obtenir l'URL upstream."})]})}),a.jsx(Se,{title:"Appairage",children:a.jsxs("p",{className:"text-sm text-muted",children:["L'appairage est géré dans"," ",a.jsx("span",{className:"text-content",children:"Paramètres → Appareils"}),", où vous pouvez générer un code et révoquer des appareils."]})})]})}const Ew={aiProfiles:"Profils IA",deployment:"Déploiement",devices:"Appareils",plugins:"Plugins"},Pw=["aiProfiles","deployment","devices","plugins"];function fL({section:e,onSectionChange:t,onClose:n}){return a.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[a.jsxs("nav",{"aria-label":"settings sections",className:"flex w-52 shrink-0 flex-col gap-1 border-r border-border p-3",children:[Pw.map(r=>{const i=r===e;return a.jsx("button",{type:"button","aria-current":i?"page":void 0,onClick:()=>t(r),className:q("rounded-md px-3 py-2 text-left text-sm transition-colors",i?"bg-raised font-semibold text-content":"text-muted hover:bg-raised hover:text-content"),children:Ew[r]},r)}),a.jsx("div",{className:"mt-auto pt-2",children:a.jsx(M,{size:"sm",variant:"ghost",className:"w-full",onClick:n,children:"Fermer les paramètres"})})]}),a.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:a.jsx("div",{className:"w-full max-w-2xl",children:e==="aiProfiles"?a.jsx(kw,{}):e==="deployment"?a.jsx(hL,{}):e==="plugins"?a.jsx(uA,{}):a.jsx(Nw,{})})})]})}function Ks(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const pL={branches:[],current:null},kx=20;function mL(e){const{git:t}=fe(),[n,r]=g.useState([]),[i,s]=g.useState(pL),[l,o]=g.useState([]),[c,u]=g.useState(!1),[h,d]=g.useState(null),f=g.useCallback(async()=>{u(!0),d(null);try{const[v,_,y]=await Promise.all([t.status(e),t.branches(e),t.log(e,kx)]);r(v),s(_),o(y)}catch(v){d(Ks(v))}finally{u(!1)}},[t,e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async v=>{u(!0),d(null);try{await t.stage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!0}:y))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async v=>{u(!0),d(null);try{await t.unstage(e,v),r(_=>_.map(y=>y.path===v?{...y,staged:!1}:y))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]),x=g.useCallback(async v=>{u(!0),d(null);try{const _=await t.commit(e,v);r(y=>y.filter(b=>!b.staged)),o(y=>[_,...y].slice(0,kx))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]),w=g.useCallback(async v=>{u(!0),d(null);try{await t.checkout(e,v),s(_=>({branches:_.branches.includes(v)?_.branches:[..._.branches,v],current:v}))}catch(_){d(Ks(_))}finally{u(!1)}},[t,e]);return{files:n,branches:i,log:l,busy:c,error:h,refresh:f,stage:p,unstage:m,commit:x,checkout:w}}function Cx(e){const t={children:[]};for(const n of e){const r=n.path.split("/").filter(Boolean);let i=t;r.forEach((s,l)=>{const o=l===r.length-1,c=r.slice(0,l+1).join("/");let u=i.children.find(h=>h.name===s&&h.isDir===!o);u||(u={name:s,path:c,isDir:!o,staged:n.staged,children:[]},i.children.push(u)),i=u})}return Aw(t),t.children}function Aw(e){e.children.sort((t,n)=>t.isDir!==n.isDir?t.isDir?-1:1:t.name.localeCompare(n.name)),e.children.forEach(Aw)}function zh({nodes:e,depth:t,action:n,onAction:r,busy:i}){return a.jsx("ul",{className:"flex flex-col gap-0.5",children:e.map(s=>s.isDir?a.jsxs("li",{children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-xs text-muted",style:{paddingLeft:`${t*14+8}px`},children:[a.jsx("span",{"aria-hidden":!0,className:"text-faint",children:"▸"}),a.jsx("span",{className:"truncate",children:s.name})]}),a.jsx(zh,{nodes:s.children,depth:t+1,action:n,onAction:r,busy:i})]},s.path):a.jsxs("li",{className:"flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:bg-raised",style:{paddingLeft:`${t*14+8}px`},children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx("span",{"aria-hidden":!0,className:q("size-1.5 shrink-0 rounded-full",n==="unstage"?"bg-success":"bg-warning")}),a.jsx("code",{className:"min-w-0 truncate text-xs text-content",children:s.name})]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`${n} ${s.path}`,disabled:i,onClick:()=>r(s.path),className:"shrink-0 text-muted hover:text-content",children:n==="unstage"?"Unstage":"Stage"})]},s.path))})}function Tw({projectId:e}){const t=mL(e),[n,r]=g.useState(""),[i,s]=g.useState(""),l=t.files.filter(f=>f.staged),o=t.files.filter(f=>!f.staged),c=n.trim().length>0&&l.length>0&&!t.busy;async function u(f){f.preventDefault(),c&&(await t.commit(n.trim()),r(""))}async function h(f){await t.checkout(f)}async function d(f){f.preventDefault();const p=i.trim();!p||t.busy||(await t.checkout(p),s(""))}return a.jsxs(Se,{title:"Git",className:"flex flex-col gap-0",children:[t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("section",{"aria-label":"Changes",className:"border-b border-border p-4",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Changes"}),t.busy&&a.jsx(Me,{size:12})]}),t.files.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No changes."}):a.jsxs("div",{className:"flex flex-col gap-3",children:[l.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Staged"}),a.jsx(zh,{nodes:Cx(l),depth:0,action:"unstage",onAction:f=>void t.unstage(f),busy:t.busy})]}),o.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"mb-1 text-xs font-medium text-muted",children:"Unstaged"}),a.jsx(zh,{nodes:Cx(o),depth:0,action:"stage",onAction:f=>void t.stage(f),busy:t.busy})]})]})]}),a.jsxs("section",{"aria-label":"Commit",className:"border-b border-border p-4",children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Commit"}),a.jsxs("form",{onSubmit:u,className:"flex flex-col gap-2",children:[a.jsx(oe,{"aria-label":"commit message",placeholder:"Commit message",value:n,onChange:f=>r(f.target.value)}),a.jsx(M,{type:"submit",variant:"primary",disabled:!c,loading:t.busy,className:"self-end",children:"Commit"})]})]}),a.jsxs("section",{"aria-label":"Branches",className:"border-b border-border p-4",children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Branches"}),a.jsxs("p",{className:"mb-2 text-sm text-content",children:["Current:"," ",a.jsx("span",{className:"font-medium",children:t.branches.current??"(none)"})]}),t.branches.branches.length>0&&a.jsx("ul",{className:"mb-3 flex flex-col gap-0.5",children:t.branches.branches.map(f=>{const p=f===t.branches.current;return a.jsxs("li",{className:q("flex items-center justify-between gap-2 rounded-md px-2 py-1",p&&"bg-raised"),children:[a.jsx("span",{className:q("text-sm",p?"font-semibold text-primary":"text-content"),children:f}),!p&&a.jsx(M,{size:"sm",variant:"ghost","aria-label":`checkout ${f}`,disabled:t.busy,onClick:()=>void h(f),className:"shrink-0 text-muted hover:text-content",children:"Checkout"})]},f)})}),a.jsxs("form",{onSubmit:d,className:"flex items-center gap-2",children:[a.jsx(oe,{"aria-label":"new branch name",placeholder:"New branch",value:i,onChange:f=>s(f.target.value),className:"flex-1"}),a.jsx(M,{type:"submit",variant:"ghost",disabled:!i.trim()||t.busy,children:"Create & checkout"})]})]}),a.jsxs("section",{"aria-label":"Log",className:"p-4",children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-faint",children:"Log"}),t.log.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No commits yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.log.map(f=>a.jsxs("li",{className:"flex items-baseline gap-2 py-1.5",children:[a.jsx("code",{className:"shrink-0 text-xs text-faint",children:f.hash.slice(0,7)}),a.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:f.summary})]},f.hash))})]})]})}const jx=["#4f9cf9","#a78bfa","#34d399","#fbbf24","#f87171","#38bdf8","#fb923c","#c084fc","#f472b6","#2dd4bf"];function Gs(e){return jx[e%jx.length]}function gL(e){return e.indexOf(null)}function Nx(e,t){const n=gL(e);return n!==-1?(e[n]=t,n):(e.push(t),e.length-1)}function xL(e){const t=[],n=[];for(const r of e){const{hash:i,parents:s}=r,l=t.slice();let o=t.indexOf(i);o===-1&&(o=Nx(t,i));for(let f=0;f{o(!0),u(null);try{const d=await t.graph(e,vL);r(d),s(xL(d))}catch(d){u(d&&typeof d=="object"&&"message"in d?String(d.message):String(d))}finally{o(!1)}},[t,e]);return g.useEffect(()=>{h()},[h]),{commits:n,rows:i,busy:l,error:c,refresh:h}}const ec=16,po=36,Ex=4.5,Fh=e=>e*ec+ec/2;function Px(e,t,n){const r=Fh(e.fromLane),i=Fh(e.toLane);if(r===i)return`M ${r} ${t} L ${i} ${n}`;const s=(t+n)/2;return`M ${r} ${t} C ${r} ${s} ${i} ${s} ${i} ${n}`}function yL({row:e,laneCount:t}){const n=t*ec+ec/2,r=po/2,i=Fh(e.lane);return a.jsxs("svg",{width:n,height:po,"aria-hidden":!0,className:"shrink-0 overflow-visible",children:[e.incoming.map((s,l)=>a.jsx("path",{d:Px(s,0,r),fill:"none",stroke:s.color,strokeWidth:2},`in-${l}`)),e.outgoing.map((s,l)=>a.jsx("path",{d:Px(s,r,po),fill:"none",stroke:s.color,strokeWidth:2},`out-${l}`)),a.jsx("circle",{cx:i,cy:r,r:Ex+1.5,className:"fill-canvas"}),a.jsx("circle",{cx:i,cy:r,r:Ex,fill:e.color,stroke:"var(--color-canvas)",strokeWidth:1})]})}function bL(e){const t=Math.floor(Date.now()/1e3)-e;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:t<31536e3?`${Math.floor(t/2592e3)}mo ago`:`${Math.floor(t/31536e3)}y ago`}function wL({commit:e,onClose:t}){const n=r=>r.startsWith("tag:");return a.jsxs("aside",{"aria-label":"commit detail",className:"flex w-80 shrink-0 flex-col gap-3 overflow-y-auto border-l border-border bg-surface p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e.summary}),a.jsx("button",{type:"button","aria-label":"close commit detail",onClick:t,className:"shrink-0 text-muted hover:text-content",children:"×"})]}),a.jsxs("dl",{className:"flex flex-col gap-2 text-xs",children:[a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Hash"}),a.jsx("dd",{children:a.jsx("code",{className:"text-content break-all",children:e.hash})})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Author"}),a.jsx("dd",{className:"text-content",children:e.author})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Date"}),a.jsx("dd",{className:"text-content",children:new Date(e.timestamp*1e3).toLocaleString()})]}),e.parents.length>0&&a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Parents"}),a.jsx("dd",{className:"flex flex-col gap-0.5",children:e.parents.map(r=>a.jsx("code",{className:"text-content",children:r.slice(0,8)},r))})]}),e.refs.length>0&&a.jsxs("div",{children:[a.jsx("dt",{className:"font-medium text-faint",children:"Refs"}),a.jsx("dd",{className:"flex flex-wrap gap-1",children:e.refs.map(r=>a.jsx("span",{className:q("rounded px-1 py-0.5 text-xs font-medium text-base",n(r)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:r},r))})]})]})]})}function SL({projectId:e}){const t=_L(e),[n,r]=g.useState(null),i=n!=null?t.commits.find(o=>o.hash===n)??null:null,s=t.rows.reduce((o,c)=>Math.max(o,c.laneCount),1),l=o=>o.startsWith("tag:");return a.jsxs("div",{className:"flex flex-1 overflow-hidden","aria-label":"git graph",children:[a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border bg-surface px-3 py-2",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:"Git Graph"}),t.busy&&a.jsx(Me,{size:14}),a.jsx("button",{type:"button","aria-label":"refresh git graph",onClick:()=>void t.refresh(),disabled:t.busy,className:"ml-auto text-xs text-muted hover:text-content disabled:opacity-40",children:"Refresh"})]}),t.error&&a.jsx("p",{role:"alert",className:"mx-3 mt-2 shrink-0 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger",children:t.error}),a.jsxs("div",{className:"flex-1 overflow-y-auto",role:"list","aria-label":"commits",children:[t.rows.length===0&&!t.busy&&a.jsx("p",{className:"p-4 text-sm text-muted",children:"No commits found."}),t.rows.map(o=>{const c=o.commit.hash===n;return a.jsxs("div",{role:"listitem","aria-label":`commit ${o.commit.hash.slice(0,8)}: ${o.commit.summary}`,onClick:()=>r(c?null:o.commit.hash),className:q("flex cursor-pointer items-center gap-2 border-b border-border/50 px-2 hover:bg-raised",c&&"bg-raised"),style:{height:po},children:[a.jsx(yL,{row:o,laneCount:s}),o.commit.refs.length>0&&a.jsx("div",{className:"flex shrink-0 flex-wrap gap-1",children:o.commit.refs.map(u=>a.jsx("span",{className:q("rounded px-1 py-0.5 text-xs font-medium",l(u)?"bg-warning/20 text-warning":"bg-primary/20 text-primary"),children:u},u))}),a.jsx("code",{className:"shrink-0 text-xs text-faint",children:o.commit.hash.slice(0,8)}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:o.commit.summary}),a.jsx("span",{className:"shrink-0 text-xs text-muted",children:o.commit.author}),a.jsx("span",{className:"shrink-0 text-xs text-faint",children:bL(o.commit.timestamp)})]},o.commit.hash)})]})]}),i&&a.jsx(wL,{commit:i,onClose:()=>r(null)})]})}function Ra(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function kL(){const{project:e}=fe(),[t,n]=g.useState([]),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(null),[u,h]=g.useState(!1),d=g.useCallback(async()=>{h(!0),c(null);try{n(await e.listProjects())}catch(v){c(Ra(v))}finally{h(!1)}},[e]);g.useEffect(()=>{d()},[d]);const f=g.useCallback(v=>{i(_=>_.some(y=>y.id===v.id)?_:[..._,v]),l(v.id)},[]),p=g.useCallback(async v=>{h(!0),c(null);try{const _=await e.openProject(v);f(_)}catch(_){c(Ra(_))}finally{h(!1)}},[e,f]),m=g.useCallback(async(v,_)=>{h(!0),c(null);try{const y=await e.createProject(v,_);n(b=>[...b,y]),f(y)}catch(y){c(Ra(y))}finally{h(!1)}},[e,f]),x=g.useCallback(async v=>{c(null);try{await e.closeProject(v)}catch(_){c(Ra(_))}i(_=>{const y=_.filter(b=>b.id!==v);return l(b=>b===v?y.at(-1)?.id??null:b),y})},[e]),w=g.useCallback(v=>{l(v)},[]);return{projects:t,openTabs:r,activeTabId:s,error:o,busy:u,refresh:d,createProject:m,openProject:p,closeTab:x,activateTab:w}}function CL({items:e,activeTabId:t,onSelect:n,onClose:r,projectsPanelOpen:i,onOpenProjectsPanel:s,className:l}){return a.jsxs("div",{className:q("flex shrink-0 items-center gap-1 border-b border-border bg-surface px-2 py-1",l),children:[e.length===0?a.jsx("p",{className:"px-2 text-sm text-muted",children:"No open tabs."}):a.jsx(FP,{items:e,value:t,onSelect:n,onClose:r}),a.jsx(M,{size:"sm",variant:"secondary",onClick:s,"aria-label":"open projects panel","aria-pressed":i,title:"Ajouter un projet",className:q("shrink-0",i&&"ring-1 ring-border-strong"),children:"+"})]})}function jL(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const NL=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EL=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,PL={};function Ax(e,t){return(PL.jsx?EL:NL).test(e)}const AL=/[ \t\n\f\r]/g;function TL(e){return typeof e=="object"?e.type==="text"?Tx(e.value):!1:Tx(e)}function Tx(e){return e.replace(AL,"")===""}class ta{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}ta.prototype.normal={};ta.prototype.property={};ta.prototype.space=void 0;function Lw(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new ta(n,r,t)}function $h(e){return e.toLowerCase()}class Qt{constructor(t,n){this.attribute=n,this.property=t}}Qt.prototype.attribute="";Qt.prototype.booleanish=!1;Qt.prototype.boolean=!1;Qt.prototype.commaOrSpaceSeparated=!1;Qt.prototype.commaSeparated=!1;Qt.prototype.defined=!1;Qt.prototype.mustUseProperty=!1;Qt.prototype.number=!1;Qt.prototype.overloadedBoolean=!1;Qt.prototype.property="";Qt.prototype.spaceSeparated=!1;Qt.prototype.space=void 0;let LL=0;const ge=Ei(),tt=Ei(),Wh=Ei(),Z=Ei(),De=Ei(),gi=Ei(),tn=Ei();function Ei(){return 2**++LL}const Hh=Object.freeze(Object.defineProperty({__proto__:null,boolean:ge,booleanish:tt,commaOrSpaceSeparated:tn,commaSeparated:gi,number:Z,overloadedBoolean:Wh,spaceSeparated:De},Symbol.toStringTag,{value:"Module"})),Ou=Object.keys(Hh);class xp extends Qt{constructor(t,n,r,i){let s=-1;if(super(t,n),Lx(this,"space",i),typeof r=="number")for(;++s4&&n.slice(0,4)==="data"&&OL.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(Dx,FL);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!Dx.test(s)){let l=s.replace(IL,zL);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}i=xp}return new i(r,t)}function zL(e){return"-"+e.toLowerCase()}function FL(e){return e.charAt(1).toUpperCase()}const $L=Lw([Dw,DL,Iw,Ow,Bw],"html"),vp=Lw([Dw,RL,Iw,Ow,Bw],"svg");function WL(e){return e.join(" ").trim()}var _p={},Rx=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,HL=/\n/g,UL=/^\s*/,qL=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,VL=/^:\s*/,KL=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,GL=/^[;\s]*/,YL=/^\s+|\s+$/g,XL=` -`,Mx="/",Ix="*",ai="",QL="comment",JL="declaration";function ZL(e,t){if(typeof e!="string")throw new TypeError("First argument must be a string");if(!e)return[];t=t||{};var n=1,r=1;function i(m){var x=m.match(HL);x&&(n+=x.length);var w=m.lastIndexOf(XL);r=~w?m.length-w:r+m.length}function s(){var m={line:n,column:r};return function(x){return x.position=new l(m),u(),x}}function l(m){this.start=m,this.end={line:n,column:r},this.source=t.source}l.prototype.content=e;function o(m){var x=new Error(t.source+":"+n+":"+r+": "+m);if(x.reason=m,x.filename=t.source,x.line=n,x.column=r,x.source=e,!t.silent)throw x}function c(m){var x=m.exec(e);if(x){var w=x[0];return i(w),e=e.slice(w.length),x}}function u(){c(UL)}function h(m){var x;for(m=m||[];x=d();)x!==!1&&m.push(x);return m}function d(){var m=s();if(!(Mx!=e.charAt(0)||Ix!=e.charAt(1))){for(var x=2;ai!=e.charAt(x)&&(Ix!=e.charAt(x)||Mx!=e.charAt(x+1));)++x;if(x+=2,ai===e.charAt(x-1))return o("End of comment missing");var w=e.slice(2,x-2);return r+=2,i(w),e=e.slice(x),r+=2,m({type:QL,comment:w})}}function f(){var m=s(),x=c(qL);if(x){if(d(),!c(VL))return o("property missing ':'");var w=c(KL),v=m({type:JL,property:Ox(x[0].replace(Rx,ai)),value:w?Ox(w[0].replace(Rx,ai)):ai});return c(GL),v}}function p(){var m=[];h(m);for(var x;x=f();)x!==!1&&(m.push(x),h(m));return m}return u(),p()}function Ox(e){return e?e.replace(YL,ai):ai}var eD=ZL,tD=vo&&vo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_p,"__esModule",{value:!0});_p.default=rD;const nD=tD(eD);function rD(e,t){let n=null;if(!e||typeof e!="string")return n;const r=(0,nD.default)(e),i=typeof t=="function";return r.forEach(s=>{if(s.type!=="declaration")return;const{property:l,value:o}=s;i?t(l,o,s):o&&(n=n||{},n[l]=o)}),n}var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.camelCase=void 0;var iD=/^--[a-zA-Z0-9_-]+$/,sD=/-([a-z])/g,lD=/^[^-]+$/,aD=/^-(webkit|moz|ms|o|khtml)-/,oD=/^-(ms)-/,cD=function(e){return!e||lD.test(e)||iD.test(e)},uD=function(e,t){return t.toUpperCase()},Bx=function(e,t){return"".concat(t,"-")},dD=function(e,t){return t===void 0&&(t={}),cD(e)?e:(e=e.toLowerCase(),t.reactCompat?e=e.replace(oD,Bx):e=e.replace(aD,Bx),e.replace(sD,uD))};Cc.camelCase=dD;var hD=vo&&vo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},fD=hD(_p),pD=Cc;function Uh(e,t){var n={};return!e||typeof e!="string"||(0,fD.default)(e,function(r,i){r&&i&&(n[(0,pD.camelCase)(r,t)]=i)}),n}Uh.default=Uh;var mD=Uh;const gD=ef(mD),zw=Fw("end"),yp=Fw("start");function Fw(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function xD(e){const t=yp(e),n=zw(e);if(t&&n)return{start:t,end:n}}function _l(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?zx(e.position):"start"in e||"end"in e?zx(e):"line"in e||"column"in e?qh(e):""}function qh(e){return Fx(e&&e.line)+":"+Fx(e&&e.column)}function zx(e){return qh(e&&e.start)+"-"+qh(e&&e.end)}function Fx(e){return e&&typeof e=="number"?e:1}class Lt extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",s={},l=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s={...n}),typeof t=="string"?i=t:!s.cause&&t&&(l=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?s.ruleId=r:(s.source=r.slice(0,c),s.ruleId=r.slice(c+1))}if(!s.place&&s.ancestors&&s.ancestors){const c=s.ancestors[s.ancestors.length-1];c&&(s.place=c.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=_l(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=l&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Lt.prototype.file="";Lt.prototype.name="";Lt.prototype.reason="";Lt.prototype.message="";Lt.prototype.stack="";Lt.prototype.column=void 0;Lt.prototype.line=void 0;Lt.prototype.ancestors=void 0;Lt.prototype.cause=void 0;Lt.prototype.fatal=void 0;Lt.prototype.place=void 0;Lt.prototype.ruleId=void 0;Lt.prototype.source=void 0;const bp={}.hasOwnProperty,vD=new Map,_D=/[A-Z]/g,yD=new Set(["table","tbody","thead","tfoot","tr"]),bD=new Set(["td","th"]),$w="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function wD(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=AD(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=PD(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?vp:$L,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=Ww(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function Ww(e,t,n){if(t.type==="element")return SD(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return kD(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return jD(e,t,n);if(t.type==="mdxjsEsm")return CD(e,t);if(t.type==="root")return ND(e,t,n);if(t.type==="text")return ED(e,t)}function SD(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=vp,e.schema=i),e.ancestors.push(t);const s=Uw(e,t.tagName,!1),l=TD(e,t);let o=Sp(e,t);return yD.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!TL(c):!0})),Hw(e,l,s,t),wp(l,o),e.ancestors.pop(),e.schema=r,e.create(t,s,l,n)}function kD(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}Hl(e,t.position)}function CD(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Hl(e,t.position)}function jD(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=vp,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:Uw(e,t.name,!0),l=LD(e,t),o=Sp(e,t);return Hw(e,l,s,t),wp(l,o),e.ancestors.pop(),e.schema=r,e.create(t,s,l,n)}function ND(e,t,n){const r={};return wp(r,Sp(e,t)),e.create(t,e.Fragment,r,n)}function ED(e,t){return t.value}function Hw(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function wp(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function PD(e,t,n){return r;function r(i,s,l,o){const u=Array.isArray(l.children)?n:t;return o?u(s,l,o):u(s,l)}}function AD(e,t){return n;function n(r,i,s,l){const o=Array.isArray(s.children),c=yp(r);return t(i,s,l,o,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function TD(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&bp.call(t.properties,i)){const s=DD(e,i,t.properties[i]);if(s){const[l,o]=s;e.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&bD.has(t.tagName)?r=o:n[l]=o}}if(r){const s=n.style||(n.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function LD(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const s=r.data.estree.body[0];s.type;const l=s.expression;l.type;const o=l.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else Hl(e,t.position);else{const i=r.name;let s;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,s=e.evaluater.evaluateExpression(o.expression)}else Hl(e,t.position);else s=r.value===null?!0:r.value;n[i]=s}return n}function Sp(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:vD;for(;++ri?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),e.splice(...l);else for(n&&e.splice(t,n);s0?(an(e,e.length,0,t),e):t}const Hx={}.hasOwnProperty;function Vw(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Dn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const It=Yr(/[A-Za-z]/),At=Yr(/[\dA-Za-z]/),WD=Yr(/[#-'*+\--9=?A-Z^-~]/);function tc(e){return e!==null&&(e<32||e===127)}const Vh=Yr(/\d/),HD=Yr(/[\dA-Fa-f]/),UD=Yr(/[!-/:-@[-`{-~]/);function ue(e){return e!==null&&e<-2}function Re(e){return e!==null&&(e<0||e===32)}function ye(e){return e===-2||e===-1||e===32}const jc=Yr(/\p{P}|\p{S}/u),ki=Yr(/\s/);function Yr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Cs(e){const t=[];let n=-1,r=0,i=0;for(;++n55295&&s<57344){const o=e.charCodeAt(n+1);s<56320&&o>56319&&o<57344?(l=String.fromCharCode(s,o),i=1):l="�"}else l=String.fromCharCode(s);l&&(t.push(e.slice(r,n),encodeURIComponent(l)),r=n+i+1,l=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function Ce(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let s=0;return l;function l(c){return ye(c)?(e.enter(n),o(c)):t(c)}function o(c){return ye(c)&&s++l))return;const N=t.events.length;let R=N,D,k;for(;R--;)if(t.events[R][0]==="exit"&&t.events[R][1].type==="chunkFlow"){if(D){k=t.events[R][1].end;break}D=!0}for(v(r),S=N;Sy;){const C=n[b];t.containerState=C[1],C[0].exit.call(t,e)}n.length=y}function _(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function YD(e,t,n){return Ce(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function xs(e){if(e===null||Re(e)||ki(e))return 1;if(jc(e))return 2}function Nc(e,t,n){const r=[];let i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[r][1].end},f={...e[n][1].start};qx(d,-c),qx(f,c),l={type:c>1?"strongSequence":"emphasisSequence",start:d,end:{...e[r][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},s={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?"strong":"emphasis",start:{...l.start},end:{...o.end}},e[r][1].end={...l.start},e[n][1].start={...o.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=vn(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=vn(u,[["enter",i,t],["enter",l,t],["exit",l,t],["enter",s,t]]),u=vn(u,Nc(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=vn(u,[["exit",s,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(h=2,u=vn(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):h=0,an(e,r-1,n-r+3,u),n=r+u.length-h-2;break}}for(n=-1;++n0&&ye(S)?Ce(e,_,"linePrefix",s+1)(S):_(S)}function _(S){return S===null||ue(S)?e.check(Vx,x,b)(S):(e.enter("codeFlowValue"),y(S))}function y(S){return S===null||ue(S)?(e.exit("codeFlowValue"),_(S)):(e.consume(S),y)}function b(S){return e.exit("codeFenced"),t(S)}function C(S,N,R){let D=0;return k;function k(O){return S.enter("lineEnding"),S.consume(O),S.exit("lineEnding"),L}function L(O){return S.enter("codeFencedFence"),ye(O)?Ce(S,A,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):A(O)}function A(O){return O===o?(S.enter("codeFencedFenceSequence"),P(O)):R(O)}function P(O){return O===o?(D++,S.consume(O),P):D>=l?(S.exit("codeFencedFenceSequence"),ye(O)?Ce(S,I,"whitespace")(O):I(O)):R(O)}function I(O){return O===null||ue(O)?(S.exit("codeFencedFence"),N(O)):R(O)}}}function aR(e,t,n){const r=this;return i;function i(l){return l===null?n(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s)}function s(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const zu={name:"codeIndented",tokenize:cR},oR={partial:!0,tokenize:uR};function cR(e,t,n){const r=this;return i;function i(u){return e.enter("codeIndented"),Ce(e,s,"linePrefix",5)(u)}function s(u){const h=r.events[r.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(u):n(u)}function l(u){return u===null?c(u):ue(u)?e.attempt(oR,l,c)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||ue(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),o)}function c(u){return e.exit("codeIndented"),t(u)}}function uR(e,t,n){const r=this;return i;function i(l){return r.parser.lazy[r.now().line]?n(l):ue(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),i):Ce(e,s,"linePrefix",5)(l)}function s(l){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(l):ue(l)?i(l):n(l)}}const dR={name:"codeText",previous:fR,resolve:hR,tokenize:pR};function hR(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&Ys(this.left,r),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Ys(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Ys(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):e.interrupt(r.parser.constructs.flow,n,t)(l)}}function Jw(e,t,n,r,i,s,l,o,c){const u=c||Number.POSITIVE_INFINITY;let h=0;return d;function d(v){return v===60?(e.enter(r),e.enter(i),e.enter(s),e.consume(v),e.exit(s),f):v===null||v===32||v===41||tc(v)?n(v):(e.enter(r),e.enter(l),e.enter(o),e.enter("chunkString",{contentType:"string"}),x(v))}function f(v){return v===62?(e.enter(s),e.consume(v),e.exit(s),e.exit(i),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(o),f(v)):v===null||v===60||ue(v)?n(v):(e.consume(v),v===92?m:p)}function m(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function x(v){return!h&&(v===null||v===41||Re(v))?(e.exit("chunkString"),e.exit(o),e.exit(l),e.exit(r),t(v)):h999||p===null||p===91||p===93&&!c||p===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(e.exit(s),e.enter(i),e.consume(p),e.exit(i),e.exit(r),t):ue(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||ue(p)||o++>999?(e.exit("chunkString"),h(p)):(e.consume(p),c||(c=!ye(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),o++,d):d(p)}}function eS(e,t,n,r,i,s){let l;return o;function o(f){return f===34||f===39||f===40?(e.enter(r),e.enter(i),e.consume(f),e.exit(i),l=f===40?41:f,c):n(f)}function c(f){return f===l?(e.enter(i),e.consume(f),e.exit(i),e.exit(r),t):(e.enter(s),u(f))}function u(f){return f===l?(e.exit(s),c(l)):f===null?n(f):ue(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Ce(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===l||f===null||ue(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:h)}function d(f){return f===l||f===92?(e.consume(f),h):h(f)}}function yl(e,t){let n;return r;function r(i){return ue(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):ye(i)?Ce(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const wR={name:"definition",tokenize:kR},SR={partial:!0,tokenize:CR};function kR(e,t,n){const r=this;let i;return s;function s(p){return e.enter("definition"),l(p)}function l(p){return Zw.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return i=Dn(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),c):n(p)}function c(p){return Re(p)?yl(e,u)(p):u(p)}function u(p){return Jw(e,h,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(SR,d,d)(p)}function d(p){return ye(p)?Ce(e,f,"whitespace")(p):f(p)}function f(p){return p===null||ue(p)?(e.exit("definition"),r.parser.defined.push(i),t(p)):n(p)}}function CR(e,t,n){return r;function r(o){return Re(o)?yl(e,i)(o):n(o)}function i(o){return eS(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return ye(o)?Ce(e,l,"whitespace")(o):l(o)}function l(o){return o===null||ue(o)?t(o):n(o)}}const jR={name:"hardBreakEscape",tokenize:NR};function NR(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return ue(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const ER={name:"headingAtx",resolve:PR,tokenize:AR};function PR(e,t){let n=e.length-2,r=3,i,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},an(e,r,n-r+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function AR(e,t,n){let r=0;return i;function i(h){return e.enter("atxHeading"),s(h)}function s(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&r++<6?(e.consume(h),l):h===null||Re(h)?(e.exit("atxHeadingSequence"),o(h)):n(h)}function o(h){return h===35?(e.enter("atxHeadingSequence"),c(h)):h===null||ue(h)?(e.exit("atxHeading"),t(h)):ye(h)?Ce(e,o,"whitespace")(h):(e.enter("atxHeadingText"),u(h))}function c(h){return h===35?(e.consume(h),c):(e.exit("atxHeadingSequence"),o(h))}function u(h){return h===null||h===35||Re(h)?(e.exit("atxHeadingText"),o(h)):(e.consume(h),u)}}const TR=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Gx=["pre","script","style","textarea"],LR={concrete:!0,name:"htmlFlow",resolveTo:MR,tokenize:IR},DR={partial:!0,tokenize:BR},RR={partial:!0,tokenize:OR};function MR(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function IR(e,t,n){const r=this;let i,s,l,o,c;return u;function u(T){return h(T)}function h(T){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(T),d}function d(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),s=!0,x):T===63?(e.consume(T),i=3,r.interrupt?t:j):It(T)?(e.consume(T),l=String.fromCharCode(T),w):n(T)}function f(T){return T===45?(e.consume(T),i=2,p):T===91?(e.consume(T),i=5,o=0,m):It(T)?(e.consume(T),i=4,r.interrupt?t:j):n(T)}function p(T){return T===45?(e.consume(T),r.interrupt?t:j):n(T)}function m(T){const ie="CDATA[";return T===ie.charCodeAt(o++)?(e.consume(T),o===ie.length?r.interrupt?t:A:m):n(T)}function x(T){return It(T)?(e.consume(T),l=String.fromCharCode(T),w):n(T)}function w(T){if(T===null||T===47||T===62||Re(T)){const ie=T===47,ee=l.toLowerCase();return!ie&&!s&&Gx.includes(ee)?(i=1,r.interrupt?t(T):A(T)):TR.includes(l.toLowerCase())?(i=6,ie?(e.consume(T),v):r.interrupt?t(T):A(T)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(T):s?_(T):y(T))}return T===45||At(T)?(e.consume(T),l+=String.fromCharCode(T),w):n(T)}function v(T){return T===62?(e.consume(T),r.interrupt?t:A):n(T)}function _(T){return ye(T)?(e.consume(T),_):k(T)}function y(T){return T===47?(e.consume(T),k):T===58||T===95||It(T)?(e.consume(T),b):ye(T)?(e.consume(T),y):k(T)}function b(T){return T===45||T===46||T===58||T===95||At(T)?(e.consume(T),b):C(T)}function C(T){return T===61?(e.consume(T),S):ye(T)?(e.consume(T),C):y(T)}function S(T){return T===null||T===60||T===61||T===62||T===96?n(T):T===34||T===39?(e.consume(T),c=T,N):ye(T)?(e.consume(T),S):R(T)}function N(T){return T===c?(e.consume(T),c=null,D):T===null||ue(T)?n(T):(e.consume(T),N)}function R(T){return T===null||T===34||T===39||T===47||T===60||T===61||T===62||T===96||Re(T)?C(T):(e.consume(T),R)}function D(T){return T===47||T===62||ye(T)?y(T):n(T)}function k(T){return T===62?(e.consume(T),L):n(T)}function L(T){return T===null||ue(T)?A(T):ye(T)?(e.consume(T),L):n(T)}function A(T){return T===45&&i===2?(e.consume(T),U):T===60&&i===1?(e.consume(T),K):T===62&&i===4?(e.consume(T),re):T===63&&i===3?(e.consume(T),j):T===93&&i===5?(e.consume(T),F):ue(T)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(DR,V,P)(T)):T===null||ue(T)?(e.exit("htmlFlowData"),P(T)):(e.consume(T),A)}function P(T){return e.check(RR,I,V)(T)}function I(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),O}function O(T){return T===null||ue(T)?P(T):(e.enter("htmlFlowData"),A(T))}function U(T){return T===45?(e.consume(T),j):A(T)}function K(T){return T===47?(e.consume(T),l="",E):A(T)}function E(T){if(T===62){const ie=l.toLowerCase();return Gx.includes(ie)?(e.consume(T),re):A(T)}return It(T)&&l.length<8?(e.consume(T),l+=String.fromCharCode(T),E):A(T)}function F(T){return T===93?(e.consume(T),j):A(T)}function j(T){return T===62?(e.consume(T),re):T===45&&i===2?(e.consume(T),j):A(T)}function re(T){return T===null||ue(T)?(e.exit("htmlFlowData"),V(T)):(e.consume(T),re)}function V(T){return e.exit("htmlFlow"),t(T)}}function OR(e,t,n){const r=this;return i;function i(l){return ue(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),s):n(l)}function s(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function BR(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(na,t,n)}}const zR={name:"htmlText",tokenize:FR};function FR(e,t,n){const r=this;let i,s,l;return o;function o(j){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(j),c}function c(j){return j===33?(e.consume(j),u):j===47?(e.consume(j),C):j===63?(e.consume(j),y):It(j)?(e.consume(j),R):n(j)}function u(j){return j===45?(e.consume(j),h):j===91?(e.consume(j),s=0,m):It(j)?(e.consume(j),_):n(j)}function h(j){return j===45?(e.consume(j),p):n(j)}function d(j){return j===null?n(j):j===45?(e.consume(j),f):ue(j)?(l=d,K(j)):(e.consume(j),d)}function f(j){return j===45?(e.consume(j),p):d(j)}function p(j){return j===62?U(j):j===45?f(j):d(j)}function m(j){const re="CDATA[";return j===re.charCodeAt(s++)?(e.consume(j),s===re.length?x:m):n(j)}function x(j){return j===null?n(j):j===93?(e.consume(j),w):ue(j)?(l=x,K(j)):(e.consume(j),x)}function w(j){return j===93?(e.consume(j),v):x(j)}function v(j){return j===62?U(j):j===93?(e.consume(j),v):x(j)}function _(j){return j===null||j===62?U(j):ue(j)?(l=_,K(j)):(e.consume(j),_)}function y(j){return j===null?n(j):j===63?(e.consume(j),b):ue(j)?(l=y,K(j)):(e.consume(j),y)}function b(j){return j===62?U(j):y(j)}function C(j){return It(j)?(e.consume(j),S):n(j)}function S(j){return j===45||At(j)?(e.consume(j),S):N(j)}function N(j){return ue(j)?(l=N,K(j)):ye(j)?(e.consume(j),N):U(j)}function R(j){return j===45||At(j)?(e.consume(j),R):j===47||j===62||Re(j)?D(j):n(j)}function D(j){return j===47?(e.consume(j),U):j===58||j===95||It(j)?(e.consume(j),k):ue(j)?(l=D,K(j)):ye(j)?(e.consume(j),D):U(j)}function k(j){return j===45||j===46||j===58||j===95||At(j)?(e.consume(j),k):L(j)}function L(j){return j===61?(e.consume(j),A):ue(j)?(l=L,K(j)):ye(j)?(e.consume(j),L):D(j)}function A(j){return j===null||j===60||j===61||j===62||j===96?n(j):j===34||j===39?(e.consume(j),i=j,P):ue(j)?(l=A,K(j)):ye(j)?(e.consume(j),A):(e.consume(j),I)}function P(j){return j===i?(e.consume(j),i=void 0,O):j===null?n(j):ue(j)?(l=P,K(j)):(e.consume(j),P)}function I(j){return j===null||j===34||j===39||j===60||j===61||j===96?n(j):j===47||j===62||Re(j)?D(j):(e.consume(j),I)}function O(j){return j===47||j===62||Re(j)?D(j):n(j)}function U(j){return j===62?(e.consume(j),e.exit("htmlTextData"),e.exit("htmlText"),t):n(j)}function K(j){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),E}function E(j){return ye(j)?Ce(e,F,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):F(j)}function F(j){return e.enter("htmlTextData"),l(j)}}const jp={name:"labelEnd",resolveAll:UR,resolveTo:qR,tokenize:VR},$R={tokenize:KR},WR={tokenize:GR},HR={tokenize:YR};function UR(e){let t=-1;const n=[];for(;++t=3&&(u===null||ue(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===i?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),ye(u)?Ce(e,o,"whitespace")(u):o(u))}}const Ht={continuation:{tokenize:sM},exit:aM,name:"list",tokenize:iM},nM={partial:!0,tokenize:oM},rM={partial:!0,tokenize:lM};function iM(e,t,n){const r=this,i=r.events[r.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,l=0;return o;function o(p){const m=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Vh(p)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(mo,n,u)(p):u(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(p)}return n(p)}function c(p){return Vh(p)&&++l<10?(e.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):n(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(na,r.interrupt?n:h,e.attempt(nM,f,d))}function h(p){return r.containerState.initialBlankLine=!0,s++,f(p)}function d(p){return ye(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function sM(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(na,i,s);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Ce(e,t,"listItemIndent",r.containerState.size+1)(o)}function s(o){return r.containerState.furtherBlankLines||!ye(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(rM,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Ce(e,e.attempt(Ht,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function lM(e,t,n){const r=this;return Ce(e,i,"listItemIndent",r.containerState.size+1);function i(s){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(s):n(s)}}function aM(e){e.exit(this.containerState.type)}function oM(e,t,n){const r=this;return Ce(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const l=r.events[r.events.length-1];return!ye(s)&&l&&l[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const Yx={name:"setextUnderline",resolveTo:cM,tokenize:uM};function cM(e,t){let n=e.length,r,i,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const l={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",l,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end={...e[s][1].end}):e[r][1]=l,e.push(["exit",l,t]),e}function uM(e,t,n){const r=this;let i;return s;function s(u){let h=r.events.length,d;for(;h--;)if(r.events[h][1].type!=="lineEnding"&&r.events[h][1].type!=="linePrefix"&&r.events[h][1].type!=="content"){d=r.events[h][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),i=u,l(u)):n(u)}function l(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),ye(u)?Ce(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||ue(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const dM={tokenize:hM};function hM(e){const t=this,n=e.attempt(na,r,e.attempt(this.parser.constructs.flowInitial,i,Ce(e,e.attempt(this.parser.constructs.flow,i,e.attempt(xR,i)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const fM={resolveAll:nS()},pM=tS("string"),mM=tS("text");function tS(e){return{resolveAll:nS(e==="text"?gM:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],s=n.attempt(i,l,o);return l;function l(h){return u(h)?s(h):o(h)}function o(h){if(h===null){n.consume(h);return}return n.enter("data"),n.consume(h),c}function c(h){return u(h)?(n.exit("data"),s(h)):(n.consume(h),c)}function u(h){if(h===null)return!0;const d=i[h];let f=-1;if(d)for(;++f-1){const o=l[0];typeof o=="string"?l[0]=o.slice(r):l.shift()}s>0&&l.push(e[i].slice(0,s))}return l}function PM(e,t){let n=-1;const r=[];let i;for(;++n0){const Cn=me.tokenStack[me.tokenStack.length-1];(Cn[1]||Qx).call(me,void 0,Cn[0])}for(te.position={start:Sr(H.length>0?H[0][1].start:{line:1,column:1,offset:0}),end:Sr(H.length>0?H[H.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le0&&(r.className=["language-"+i[0]]);let s={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function HM(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function UM(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qM(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),i=Cs(r.toLowerCase()),s=e.footnoteOrder.indexOf(r);let l,o=e.footnoteCounts.get(r);o===void 0?(o=0,e.footnoteOrder.push(r),l=e.footnoteOrder.length):l=s+1,o+=1,e.footnoteCounts.set(r,o);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function VM(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function KM(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function sS(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});const l=i[i.length-1];return l&&l.type==="text"?l.value+=r:i.push({type:"text",value:r}),i}function GM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return sS(e,t);const i={src:Cs(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function YM(e,t){const n={src:Cs(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function XM(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function QM(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return sS(e,t);const i={href:Cs(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function JM(e,t){const n={href:Cs(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ZM(e,t,n){const r=e.all(t),i=n?eI(n):lS(t),s={},l=[];if(typeof t.checked=="boolean"){const h=r[0];let d;h&&h.type==="element"&&h.tagName==="p"?d=h:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o1}function tI(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},o=yp(t.children[1]),c=zw(t.children[t.children.length-1]);o&&c&&(l.position={start:o,end:c}),i.push(l)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function lI(e,t,n){const r=n?n.children:void 0,s=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,o=l?l.length:t.children.length;let c=-1;const u=[];for(;++c0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return s.push(ev(t.slice(i),i>0,!1)),s.join("")}function ev(e,t,n){let r=0,i=e.length;if(t){let s=e.codePointAt(r);for(;s===Jx||s===Zx;)r++,s=e.codePointAt(r)}if(n){let s=e.codePointAt(i-1);for(;s===Jx||s===Zx;)i--,s=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function cI(e,t){const n={type:"text",value:oI(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function uI(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const dI={blockquote:FM,break:$M,code:WM,delete:HM,emphasis:UM,footnoteReference:qM,heading:VM,html:KM,imageReference:GM,image:YM,inlineCode:XM,linkReference:QM,link:JM,listItem:ZM,list:tI,paragraph:nI,root:rI,strong:iI,table:sI,tableCell:aI,tableRow:lI,text:cI,thematicBreak:uI,toml:Ma,yaml:Ma,definition:Ma,footnoteDefinition:Ma};function Ma(){}const aS=-1,Ec=0,bl=1,nc=2,Np=3,Ep=4,Pp=5,Ap=6,oS=7,cS=8,hI=typeof self=="object"?self:globalThis,tv=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new hI[e](t)},fI=(e,t)=>{const n=(i,s)=>(e.set(s,i),i),r=i=>{if(e.has(i))return e.get(i);const[s,l]=t[i];switch(s){case Ec:case aS:return n(l,i);case bl:{const o=n([],i);for(const c of l)o.push(r(c));return o}case nc:{const o=n({},i);for(const[c,u]of l)o[r(c)]=r(u);return o}case Np:return n(new Date(l),i);case Ep:{const{source:o,flags:c}=l;return n(new RegExp(o,c),i)}case Pp:{const o=n(new Map,i);for(const[c,u]of l)o.set(r(c),r(u));return o}case Ap:{const o=n(new Set,i);for(const c of l)o.add(r(c));return o}case oS:{const{name:o,message:c}=l;return n(tv(o,c),i)}case cS:return n(BigInt(l),i);case"BigInt":return n(Object(BigInt(l)),i);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:o}=new Uint8Array(l);return n(new DataView(o),l)}}return n(tv(s,l),i)};return r},nv=e=>fI(new Map,e)(0),Oi="",{toString:pI}={},{keys:mI}=Object,Xs=e=>{const t=typeof e;if(t!=="object"||!e)return[Ec,t];const n=pI.call(e).slice(8,-1);switch(n){case"Array":return[bl,Oi];case"Object":return[nc,Oi];case"Date":return[Np,Oi];case"RegExp":return[Ep,Oi];case"Map":return[Pp,Oi];case"Set":return[Ap,Oi];case"DataView":return[bl,n]}return n.includes("Array")?[bl,n]:n.includes("Error")?[oS,n]:[nc,n]},Ia=([e,t])=>e===Ec&&(t==="function"||t==="symbol"),gI=(e,t,n,r)=>{const i=(l,o)=>{const c=r.push(l)-1;return n.set(o,c),c},s=l=>{if(n.has(l))return n.get(l);let[o,c]=Xs(l);switch(o){case Ec:{let h=l;switch(c){case"bigint":o=cS,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);h=null;break;case"undefined":return i([aS],l)}return i([o,h],l)}case bl:{if(c){let f=l;return c==="DataView"?f=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(f=new Uint8Array(l)),i([c,[...f]],l)}const h=[],d=i([o,h],l);for(const f of l)h.push(s(f));return d}case nc:{if(c)switch(c){case"BigInt":return i([c,l.toString()],l);case"Boolean":case"Number":case"String":return i([c,l.valueOf()],l)}if(t&&"toJSON"in l)return s(l.toJSON());const h=[],d=i([o,h],l);for(const f of mI(l))(e||!Ia(Xs(l[f])))&&h.push([s(f),s(l[f])]);return d}case Np:return i([o,l.toISOString()],l);case Ep:{const{source:h,flags:d}=l;return i([o,{source:h,flags:d}],l)}case Pp:{const h=[],d=i([o,h],l);for(const[f,p]of l)(e||!(Ia(Xs(f))||Ia(Xs(p))))&&h.push([s(f),s(p)]);return d}case Ap:{const h=[],d=i([o,h],l);for(const f of l)(e||!Ia(Xs(f)))&&h.push(s(f));return d}}const{message:u}=l;return i([o,{name:c,message:u}],l)};return s},rv=(e,{json:t,lossy:n}={})=>{const r=[];return gI(!(t||n),!!t,new Map,r)(e),r},rc=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?nv(rv(e,t)):structuredClone(e):(e,t)=>nv(rv(e,t));function xI(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function vI(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function _I(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||xI,r=e.options.footnoteBackLabel||vI,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&m.push({type:"text",value:" "});let _=typeof n=="string"?n:n(c,p);typeof _=="string"&&(_={type:"text",value:_}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const w=h[h.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const _=w.children[w.children.length-1];_&&_.type==="text"?_.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...m)}else h.push(...m);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(h,!0)};e.patch(u,v),o.push(v)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:{...rc(l),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:` -`}]}}const Pc=function(e){if(e==null)return SI;if(typeof e=="function")return Ac(e);if(typeof e=="object")return Array.isArray(e)?yI(e):bI(e);if(typeof e=="string")return wI(e);throw new Error("Expected function, string, or object as test")};function yI(e){const t=[];let n=-1;for(;++n":""))+")"})}return f;function f(){let p=uS,m,x,w;if((!t||s(c,u,h[h.length-1]||void 0))&&(p=NI(n(c,h)),p[0]===Gh))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==jI)for(x=(r?v.children.length:-1)+l,w=h.concat(v);x>-1&&x0&&n.push({type:"text",value:` -`}),n}function iv(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function sv(e,t){const n=PI(e,t),r=n.one(e,void 0),i=_I(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&s.children.push({type:"text",value:` -`},i),s}function RI(e,t){return e&&"run"in e?async function(n,r){const i=sv(n,{file:r,...t});await e.run(i,r)}:function(n,r){return sv(n,{file:r,...e||t})}}function lv(e){if(e)throw e}var go=Object.prototype.hasOwnProperty,hS=Object.prototype.toString,av=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,cv=function(t){return typeof Array.isArray=="function"?Array.isArray(t):hS.call(t)==="[object Array]"},uv=function(t){if(!t||hS.call(t)!=="[object Object]")return!1;var n=go.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&go.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var i;for(i in t);return typeof i>"u"||go.call(t,i)},dv=function(t,n){av&&n.name==="__proto__"?av(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},hv=function(t,n){if(n==="__proto__")if(go.call(t,n)){if(ov)return ov(t,n).value}else return;return t[n]},MI=function e(){var t,n,r,i,s,l,o=arguments[0],c=1,u=arguments.length,h=!1;for(typeof o=="boolean"&&(h=o,o=arguments[1]||{},c=2),(o==null||typeof o!="object"&&typeof o!="function")&&(o={});cl.length;let c;o&&l.push(i);try{c=e.apply(this,l)}catch(u){const h=u;if(o&&n)throw h;return i(h)}o||(c&&c.then&&typeof c.then=="function"?c.then(s,i):c instanceof Error?i(c):s(c))}function i(l,...o){n||(n=!0,t(l,...o))}function s(l){i(null,l)}}const $n={basename:BI,dirname:zI,extname:FI,join:$I,sep:"/"};function BI(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');ra(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let l=-1,o=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else l<0&&(s=!0,l=i+1),o>-1&&(e.codePointAt(i)===t.codePointAt(o--)?o<0&&(r=i):(o=-1,r=l));return n===r?r=l:r<0&&(r=e.length),e.slice(n,r)}function zI(e){if(ra(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function FI(e){ra(e);let t=e.length,n=-1,r=0,i=-1,s=0,l;for(;t--;){const o=e.codePointAt(t);if(o===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),o===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function $I(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function HI(e,t){let n="",r=0,i=-1,s=0,l=-1,o,c;for(;++l<=e.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),i=l,s=0;continue}}else if(n.length>0){n="",r=0,i=l,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,l):n=e.slice(i+1,l),r=l-i-1;i=l,s=0}else o===46&&s>-1?s++:s=-1}return n}function ra(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const UI={cwd:qI};function qI(){return"/"}function Qh(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function VI(e){if(typeof e=="string")e=new URL(e);else if(!Qh(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return KI(e)}function KI(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[p,...m]=h;const x=r[f][1];Xh(x)&&Xh(p)&&(p=$u(!0,x,p)),r[f]=[u,p,...m]}}}}const QI=new Lp().freeze();function qu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Vu(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ku(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function pv(e){if(!Xh(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function mv(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Oa(e){return JI(e)?e:new fS(e)}function JI(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ZI(e){return typeof e=="string"||e3(e)}function e3(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const t3="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",gv=[],xv={allowDangerousHtml:!0},n3=/^(https?|ircs?|mailto|xmpp)$/i,r3=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function pS(e){const t=i3(e),n=s3(e);return l3(t.runSync(t.parse(n),n),e)}function i3(e){const t=e.rehypePlugins||gv,n=e.remarkPlugins||gv,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...xv}:xv;return QI().use(zM).use(n).use(RI,r).use(t)}function s3(e){const t=e.children||"",n=new fS;return typeof t=="string"&&(n.value=t),n}function l3(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||a3;for(const h of r3)Object.hasOwn(t,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+t3+h.id,void 0);return Tp(e,u),wD(e,{Fragment:a.Fragment,components:i,ignoreInvalidStyle:!0,jsx:a.jsx,jsxs:a.jsxs,passKeys:!0,passNode:!0});function u(h,d,f){if(h.type==="raw"&&f&&typeof d=="number")return l?f.children.splice(d,1):f.children[d]={type:"text",value:h.value},d;if(h.type==="element"){let p;for(p in Bu)if(Object.hasOwn(Bu,p)&&Object.hasOwn(h.properties,p)){const m=h.properties[p],x=Bu[p];(x===null||x.includes(h.tagName))&&(h.properties[p]=c(String(m||""),p,h))}}if(h.type==="element"){let p=n?!n.includes(h.tagName):s?s.includes(h.tagName):!1;if(!p&&r&&typeof d=="number"&&(p=!r(h,d,f)),p&&f&&typeof d=="number")return o&&h.children?f.children.splice(d,1,...h.children):f.children.splice(d,1),d}}}function a3(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||n3.test(e.slice(0,t))?e:""}function vv(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function o3(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function c3(e,t,n){const i=Pc((n||{}).ignore||[]),s=u3(t);let l=-1;for(;++l0?{type:"text",value:S}:void 0),S===!1?f.lastIndex=b+1:(m!==b&&_.push({type:"text",value:u.value.slice(m,b)}),Array.isArray(S)?_.push(...S):S&&_.push(S),m=b+y[0].length,v=!0),!f.global)break;y=f.exec(u.value)}return v?(m?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=vv(e,"(");let s=vv(e,")");for(;r!==-1&&i>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}function mS(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||ki(n)||jc(n))&&(!t||n!==47)}gS.peek=D3;function C3(){this.buffer()}function j3(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function N3(){this.buffer()}function E3(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function P3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Dn(this.sliceSerialize(e)).toLowerCase(),n.label=t}function A3(e){this.exit(e)}function T3(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Dn(this.sliceSerialize(e)).toLowerCase(),n.label=t}function L3(e){this.exit(e)}function D3(){return"["}function gS(e,t,n,r){const i=n.createTracker(r);let s=i.move("[^");const l=n.enter("footnoteReference"),o=n.enter("reference");return s+=i.move(n.safe(n.associationId(e),{after:"]",before:s})),o(),l(),s+=i.move("]"),s}function R3(){return{enter:{gfmFootnoteCallString:C3,gfmFootnoteCall:j3,gfmFootnoteDefinitionLabelString:N3,gfmFootnoteDefinition:E3},exit:{gfmFootnoteCallString:P3,gfmFootnoteCall:A3,gfmFootnoteDefinitionLabelString:T3,gfmFootnoteDefinition:L3}}}function M3(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:gS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,s,l){const o=s.createTracker(l);let c=o.move("[^");const u=s.enter("footnoteDefinition"),h=s.enter("label");return c+=o.move(s.safe(s.associationId(r),{before:c,after:"]"})),h(),c+=o.move("]:"),r.children&&r.children.length>0&&(o.shift(4),c+=o.move((t?` -`:" ")+s.indentLines(s.containerFlow(r,o.current()),t?xS:I3))),u(),c}}function I3(e,t,n){return t===0?e:xS(e,t,n)}function xS(e,t,n){return(n?"":" ")+e}const O3=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];vS.peek=W3;function B3(){return{canContainEols:["delete"],enter:{strikethrough:F3},exit:{strikethrough:$3}}}function z3(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:O3}],handlers:{delete:vS}}}function F3(e){this.enter({type:"delete",children:[]},e)}function $3(e){this.exit(e)}function vS(e,t,n,r){const i=n.createTracker(r),s=n.enter("strikethrough");let l=i.move("~~");return l+=n.containerPhrasing(e,{...i.current(),before:l,after:"~"}),l+=i.move("~~"),s(),l}function W3(){return"~"}function H3(e){return e.length}function U3(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||H3,s=[],l=[],o=[],c=[];let u=0,h=-1;for(;++hu&&(u=e[h].length);++vc[v])&&(c[v]=y)}x.push(_)}l[h]=x,o[h]=w}let d=-1;if(typeof r=="object"&&"length"in r)for(;++dc[d]&&(c[d]=_),p[d]=_),f[d]=y}l.splice(1,0,f),o.splice(1,0,p),h=-1;const m=[];for(;++h "),s.shift(2);const l=n.indentLines(n.containerFlow(e,s.current()),K3);return i(),l}function K3(e,t,n){return">"+(n?"":" ")+e}function G3(e,t){return yv(e,t.inConstruct,!0)&&!yv(e,t.notInConstruct,!1)}function yv(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++rl&&(l=s):s=1,i=r+t.length,r=n.indexOf(t,i);return l}function X3(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Q3(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function J3(e,t,n,r){const i=Q3(n),s=e.value||"",l=i==="`"?"GraveAccent":"Tilde";if(X3(e,n)){const d=n.enter("codeIndented"),f=n.indentLines(s,Z3);return d(),f}const o=n.createTracker(r),c=i.repeat(Math.max(Y3(s,i)+1,3)),u=n.enter("codeFenced");let h=o.move(c);if(e.lang){const d=n.enter(`codeFencedLang${l}`);h+=o.move(n.safe(e.lang,{before:h,after:" ",encode:["`"],...o.current()})),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${l}`);h+=o.move(" "),h+=o.move(n.safe(e.meta,{before:h,after:` -`,encode:["`"],...o.current()})),d()}return h+=o.move(` -`),s&&(h+=o.move(s+` -`)),h+=o.move(c),u(),h}function Z3(e,t,n){return(n?"":" ")+e}function Dp(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function e5(e,t,n,r){const i=Dp(n),s=i==='"'?"Quote":"Apostrophe",l=n.enter("definition");let o=n.enter("label");const c=n.createTracker(r);let u=c.move("[");return u+=c.move(n.safe(n.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(o=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":` -`,...c.current()}))),o(),e.title&&(o=n.enter(`title${s}`),u+=c.move(" "+i),u+=c.move(n.safe(e.title,{before:u,after:i,...c.current()})),u+=c.move(i),o()),l(),u}function t5(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ul(e){return"&#x"+e.toString(16).toUpperCase()+";"}function ic(e,t,n){const r=xs(e),i=xs(t);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}_S.peek=n5;function _S(e,t,n,r){const i=t5(n),s=n.enter("emphasis"),l=n.createTracker(r),o=l.move(i);let c=l.move(n.containerPhrasing(e,{after:i,before:o,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,i);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(i);return s(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},o+c+p}function n5(e,t,n){return n.options.emphasis||"*"}function r5(e,t){let n=!1;return Tp(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Gh}),!!((!e.depth||e.depth<3)&&kp(e)&&(t.options.setext||n))}function i5(e,t,n,r){const i=Math.max(Math.min(6,e.depth||1),1),s=n.createTracker(r);if(r5(e,n)){const h=n.enter("headingSetext"),d=n.enter("phrasing"),f=n.containerPhrasing(e,{...s.current(),before:` -`,after:` -`});return d(),h(),f+` -`+(i===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(` -`))+1))}const l="#".repeat(i),o=n.enter("headingAtx"),c=n.enter("phrasing");s.move(l+" ");let u=n.containerPhrasing(e,{before:"# ",after:` -`,...s.current()});return/^[\t ]/.test(u)&&(u=Ul(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,n.options.closeAtx&&(u+=" "+l),c(),o(),u}yS.peek=s5;function yS(e){return e.value||""}function s5(){return"<"}bS.peek=l5;function bS(e,t,n,r){const i=Dp(n),s=i==='"'?"Quote":"Apostrophe",l=n.enter("image");let o=n.enter("label");const c=n.createTracker(r);let u=c.move("![");return u+=c.move(n.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(o=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),o(),e.title&&(o=n.enter(`title${s}`),u+=c.move(" "+i),u+=c.move(n.safe(e.title,{before:u,after:i,...c.current()})),u+=c.move(i),o()),u+=c.move(")"),l(),u}function l5(){return"!"}wS.peek=a5;function wS(e,t,n,r){const i=e.referenceType,s=n.enter("imageReference");let l=n.enter("label");const o=n.createTracker(r);let c=o.move("![");const u=n.safe(e.alt,{before:c,after:"]",...o.current()});c+=o.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...o.current()});return l(),n.stack=h,s(),i==="full"||!u||u!==d?c+=o.move(d+"]"):i==="shortcut"?c=c.slice(0,-1):c+=o.move("]"),c}function a5(){return"!"}SS.peek=o5;function SS(e,t,n){let r=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++s\u007F]/.test(e.url))}CS.peek=c5;function CS(e,t,n,r){const i=Dp(n),s=i==='"'?"Quote":"Apostrophe",l=n.createTracker(r);let o,c;if(kS(e,n)){const h=n.stack;n.stack=[],o=n.enter("autolink");let d=l.move("<");return d+=l.move(n.containerPhrasing(e,{before:d,after:">",...l.current()})),d+=l.move(">"),o(),n.stack=h,d}o=n.enter("link"),c=n.enter("label");let u=l.move("[");return u+=l.move(n.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(c=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),c(),e.title&&(c=n.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(n.safe(e.title,{before:u,after:i,...l.current()})),u+=l.move(i),c()),u+=l.move(")"),o(),u}function c5(e,t,n){return kS(e,n)?"<":"["}jS.peek=u5;function jS(e,t,n,r){const i=e.referenceType,s=n.enter("linkReference");let l=n.enter("label");const o=n.createTracker(r);let c=o.move("[");const u=n.containerPhrasing(e,{before:c,after:"]",...o.current()});c+=o.move(u+"]["),l();const h=n.stack;n.stack=[],l=n.enter("reference");const d=n.safe(n.associationId(e),{before:c,after:"]",...o.current()});return l(),n.stack=h,s(),i==="full"||!u||u!==d?c+=o.move(d+"]"):i==="shortcut"?c=c.slice(0,-1):c+=o.move("]"),c}function u5(){return"["}function Rp(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function d5(e){const t=Rp(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function h5(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function NS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function f5(e,t,n,r){const i=n.enter("list"),s=n.bulletCurrent;let l=e.ordered?h5(n):Rp(n);const o=e.ordered?l==="."?")":".":d5(n);let c=t&&n.bulletLastUsed?l===n.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),NS(n)===l&&h){let d=-1;for(;++d-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let l=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(l=Math.ceil(l/4)*4);const o=n.createTracker(r);o.move(s+" ".repeat(l-s.length)),o.shift(l);const c=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,o.current()),h);return c(),u;function h(d,f,p){return f?(p?"":" ".repeat(l))+d:(p?s:s+" ".repeat(l-s.length))+d}}function g5(e,t,n,r){const i=n.enter("paragraph"),s=n.enter("phrasing"),l=n.containerPhrasing(e,r);return s(),i(),l}const x5=Pc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function v5(e,t,n,r){return(e.children.some(function(l){return x5(l)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function _5(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}ES.peek=y5;function ES(e,t,n,r){const i=_5(n),s=n.enter("strong"),l=n.createTracker(r),o=l.move(i+i);let c=l.move(n.containerPhrasing(e,{after:i,before:o,...l.current()}));const u=c.charCodeAt(0),h=ic(r.before.charCodeAt(r.before.length-1),u,i);h.inside&&(c=Ul(u)+c.slice(1));const d=c.charCodeAt(c.length-1),f=ic(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Ul(d));const p=l.move(i+i);return s(),n.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},o+c+p}function y5(e,t,n){return n.options.strong||"*"}function b5(e,t,n,r){return n.safe(e.value,r)}function w5(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function S5(e,t,n){const r=(NS(n)+(n.options.ruleSpaces?" ":"")).repeat(w5(n));return n.options.ruleSpaces?r.slice(0,-1):r}const PS={blockquote:V3,break:bv,code:J3,definition:e5,emphasis:_S,hardBreak:bv,heading:i5,html:yS,image:bS,imageReference:wS,inlineCode:SS,link:CS,linkReference:jS,list:f5,listItem:m5,paragraph:g5,root:v5,strong:ES,text:b5,thematicBreak:S5};function k5(){return{enter:{table:C5,tableData:wv,tableHeader:wv,tableRow:N5},exit:{codeText:E5,table:j5,tableData:Qu,tableHeader:Qu,tableRow:Qu}}}function C5(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function j5(e){this.exit(e),this.data.inTable=void 0}function N5(e){this.enter({type:"tableRow",children:[]},e)}function Qu(e){this.exit(e)}function wv(e){this.enter({type:"tableCell",children:[]},e)}function E5(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,P5));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function P5(e,t){return t==="|"?t:e}function A5(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,s=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:c,tableRow:o}};function l(p,m,x,w){return u(h(p,x,w),p.align)}function o(p,m,x,w){const v=d(p,x,w),_=u([v]);return _.slice(0,_.indexOf(` -`))}function c(p,m,x,w){const v=x.enter("tableCell"),_=x.enter("phrasing"),y=x.containerPhrasing(p,{...w,before:s,after:s});return _(),v(),y}function u(p,m){return U3(p,{align:m,alignDelimiters:r,padding:n,stringLength:i})}function h(p,m,x){const w=p.children;let v=-1;const _=[],y=m.enter("table");for(;++v0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const G5={tokenize:nO,partial:!0};function Y5(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Z5,continuation:{tokenize:eO},exit:tO}},text:{91:{name:"gfmFootnoteCall",tokenize:J5},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:X5,resolveTo:Q5}}}}function X5(e,t,n){const r=this;let i=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let l;for(;i--;){const c=r.events[i][1];if(c.type==="labelImage"){l=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return o;function o(c){if(!l||!l._balanced)return n(c);const u=Dn(r.sliceSerialize({start:l.end,end:r.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function Q5(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",l,t],["exit",l,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...o),e}function J5(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s=0,l;return o;function o(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),c}function c(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(s>999||d===93&&!l||d===null||d===91||Re(d))return n(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return i.includes(Dn(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return Re(d)||(l=!0),s++,e.consume(d),d===92?h:u}function h(d){return d===91||d===92||d===93?(e.consume(d),s++,u):u(d)}}function Z5(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,l=0,o;return c;function c(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):n(m)}function h(m){if(l>999||m===93&&!o||m===null||m===91||Re(m))return n(m);if(m===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return s=Dn(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Re(m)||(o=!0),l++,e.consume(m),m===92?d:h}function d(m){return m===91||m===92||m===93?(e.consume(m),l++,h):h(m)}function f(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),i.includes(s)||i.push(s),Ce(e,p,"gfmFootnoteDefinitionWhitespace")):n(m)}function p(m){return t(m)}}function eO(e,t,n){return e.check(na,t,e.attempt(G5,t,n))}function tO(e){e.exit("gfmFootnoteDefinition")}function nO(e,t,n){const r=this;return Ce(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const l=r.events[r.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?t(s):n(s)}}function rO(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:s,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(l,o){let c=-1;for(;++c1?c(m):(l.consume(m),d++,p);if(d<2&&!n)return c(m);const w=l.exit("strikethroughSequenceTemporary"),v=xs(m);return w._open=!v||v===2&&!!x,w._close=!x||x===2&&!!v,o(m)}}}class iO{constructor(){this.map=[]}add(t,n,r){sO(this,t,n,r)}consume(t){if(this.map.sort(function(s,l){return s[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const s of i)t.push(s);i=r.pop()}this.map.length=0}}function sO(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i-1;){const I=r.events[L][1].type;if(I==="lineEnding"||I==="linePrefix")L--;else break}const A=L>-1?r.events[L][1].type:null,P=A==="tableHead"||A==="tableRow"?S:c;return P===S&&r.parser.lazy[r.now().line]?n(k):P(k)}function c(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(l=!0,s+=1),h(k)}function h(k){return k===null?n(k):ue(k)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),p):n(k):ye(k)?Ce(e,h,"whitespace")(k):(s+=1,l&&(l=!1,i+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),d(k)))}function d(k){return k===null||k===124||Re(k)?(e.exit("data"),h(k)):(e.consume(k),k===92?f:d)}function f(k){return k===92||k===124?(e.consume(k),d):d(k)}function p(k){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(k):(e.enter("tableDelimiterRow"),l=!1,ye(k)?Ce(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):m(k))}function m(k){return k===45||k===58?w(k):k===124?(l=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),x):C(k)}function x(k){return ye(k)?Ce(e,w,"whitespace")(k):w(k)}function w(k){return k===58?(s+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),v):k===45?(s+=1,v(k)):k===null||ue(k)?b(k):C(k)}function v(k){return k===45?(e.enter("tableDelimiterFiller"),_(k)):C(k)}function _(k){return k===45?(e.consume(k),_):k===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),y):(e.exit("tableDelimiterFiller"),y(k))}function y(k){return ye(k)?Ce(e,b,"whitespace")(k):b(k)}function b(k){return k===124?m(k):k===null||ue(k)?!l||i!==s?C(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):C(k)}function C(k){return n(k)}function S(k){return e.enter("tableRow"),N(k)}function N(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),N):k===null||ue(k)?(e.exit("tableRow"),t(k)):ye(k)?Ce(e,N,"whitespace")(k):(e.enter("data"),R(k))}function R(k){return k===null||k===124||Re(k)?(e.exit("data"),N(k)):(e.consume(k),k===92?D:R)}function D(k){return k===92||k===124?(e.consume(k),R):R(k)}}function cO(e,t){let n=-1,r=!0,i=0,s=[0,0,0,0],l=[0,0,0,0],o=!1,c=0,u,h,d;const f=new iO;for(;++nn[2]+1){const m=n[2]+1,x=n[3]-n[2]-1;e.add(m,x,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return i!==void 0&&(s.end=Object.assign({},$i(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function kv(e,t,n,r,i){const s=[],l=$i(t.events,n);i&&(i.end=Object.assign({},l),s.push(["exit",i,t])),r.end=Object.assign({},l),s.push(["exit",r,t]),e.add(n+1,0,s)}function $i(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const uO={name:"tasklistCheck",tokenize:hO};function dO(){return{text:{91:uO}}}function hO(e,t,n){const r=this;return i;function i(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),s)}function s(c){return Re(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),l):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),l):n(c)}function l(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):n(c)}function o(c){return ue(c)?t(c):ye(c)?e.check({tokenize:fO},t,n)(c):n(c)}}function fO(e,t,n){return Ce(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function pO(e){return Vw([z5(),Y5(),rO(e),aO(),dO()])}const mO={};function BS(e){const t=this,n=e||mO,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),s=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),l=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(pO(n)),s.push(M5()),l.push(I5(n))}function gO({template:e,profiles:t,onSave:n,onClose:r,busy:i=!1}){const[s,l]=g.useState(e?.name??""),[o,c]=g.useState(e?.contentMd??""),[u,h]=g.useState(e?.defaultProfileId??""),[d,f]=g.useState("edit"),p=s.trim().length>0&&!i;async function m(x){x.preventDefault(),p&&await n(s.trim(),o,u)}return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"template editor",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:e?`Edit template — ${e.name}`:"New template"}),a.jsx(M,{type:"button",variant:"ghost","aria-label":"close template editor",onClick:r,disabled:i,children:"✕"})]}),a.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"te-name",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(oe,{id:"te-name","aria-label":"template name",placeholder:"My template",value:s,onChange:x=>l(x.target.value),disabled:i,className:"min-w-48"})]}),a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"te-profile",className:"text-xs font-medium text-muted",children:"Default profile"}),t.length>0?a.jsxs("select",{id:"te-profile","aria-label":"template default profile",value:u,onChange:x=>h(x.target.value),disabled:i,className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"",children:"— none —"}),t.map(x=>a.jsx("option",{value:x.id,children:x.name},x.id))]}):a.jsx(oe,{id:"te-profile","aria-label":"template default profile",placeholder:"profile-id (optional)",value:u,onChange:x=>h(x.target.value),disabled:i,className:"min-w-48"})]})]}),a.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>a.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":d===x,onClick:()=>f(x),className:q("px-4 py-2 text-sm font-medium capitalize transition-colors",d===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:d==="edit"?a.jsx("textarea",{"aria-label":"template content",value:o,onChange:x=>c(x.target.value),disabled:i,className:q("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Agent instructions - -...`}):a.jsx("div",{className:q("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:o.trim()?a.jsx(pS,{remarkPlugins:[BS],children:o}):a.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[a.jsx(M,{type:"button",variant:"ghost",onClick:r,disabled:i,children:"Cancel"}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"Save template",disabled:!p,loading:i,children:"Save"})]})]})]})}function Qs(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function xO(){const{template:e}=fe(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(!1),o=g.useCallback(async()=>{l(!0),i(null);try{const f=await e.listTemplates();n(f)}catch(f){i(Qs(f))}finally{l(!1)}},[e]);g.useEffect(()=>{o()},[o]);const c=g.useCallback(async f=>{l(!0),i(null);try{const p=await e.createTemplate(f);n(m=>[...m,p])}catch(p){i(Qs(p))}finally{l(!1)}},[e]),u=g.useCallback(async(f,p)=>{l(!0),i(null);try{const m=await e.updateTemplate(f,p);n(x=>x.map(w=>w.id===f?m:w))}catch(m){i(Qs(m))}finally{l(!1)}},[e]),h=g.useCallback(async f=>{l(!0),i(null);try{await e.deleteTemplate(f),n(p=>p.filter(m=>m.id!==f))}catch(p){i(Qs(p))}finally{l(!1)}},[e]),d=g.useCallback(async(f,p,m)=>{l(!0),i(null);try{await e.createAgentFromTemplate(f,p,m)}catch(x){i(Qs(x))}finally{l(!1)}},[e]);return{templates:t,error:r,busy:s,refresh:o,createTemplate:c,updateTemplate:u,deleteTemplate:h,createAgentFromTemplate:d}}function zS({projectId:e}){const t=xO(),{profile:n}=fe(),[r,i]=g.useState([]),[s,l]=g.useState(!1),[o,c]=g.useState(null),[u,h]=g.useState(!1);async function d(p){if(!s){try{const m=await n.listProfiles();i(m)}catch{}l(!0)}c(p)}async function f(p,m,x){if(o){h(!0);try{o.mode==="create"?await t.createTemplate({name:p,content:m,defaultProfileId:x}):await t.updateTemplate(o.template.id,m),c(null)}finally{h(!1)}}}return a.jsxs(a.Fragment,{children:[o!==null&&a.jsx(gO,{template:o.mode==="edit"?o.template:null,profiles:r,onSave:f,onClose:()=>c(null),busy:u}),a.jsxs(Se,{title:"Templates",className:"flex flex-col gap-0",children:[t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Templates"}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&a.jsx(Me,{size:14}),a.jsx(M,{type:"button",variant:"primary","aria-label":"create template",disabled:t.busy,onClick:()=>void d({mode:"create"}),children:"New template"})]})]}),a.jsx("div",{className:"p-4",children:t.templates.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No templates yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.templates.map(p=>a.jsx("li",{className:"flex flex-col gap-2 py-3 first:pt-0 last:pb-0",children:a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"font-medium text-content",children:p.name}),a.jsxs("span",{className:"text-xs text-muted",children:["v",p.version]})]}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit ${p.name}`,disabled:t.busy,onClick:()=>void d({mode:"edit",template:p}),children:"Edit"}),a.jsx(M,{size:"sm",variant:"primary","aria-label":`create agent from ${p.name}`,disabled:t.busy,onClick:()=>void t.createAgentFromTemplate(e,p.id),children:"Create agent"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete template ${p.name}`,disabled:t.busy,onClick:()=>void t.deleteTemplate(p.id),className:"text-danger hover:text-danger",children:"Delete"})]})]})},p.id))})})]})]})}function vO({skill:e,onSave:t,onClose:n,busy:r=!1}){const[i,s]=g.useState(e?.name??""),[l,o]=g.useState(e?.contentMd??""),[c,u]=g.useState(e?.scope??"project"),[h,d]=g.useState("edit"),f=e!=null,p=i.trim().length>0&&l.trim().length>0&&!r;async function m(x){x.preventDefault(),p&&await t(i.trim(),l,c)}return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"skill editor",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:f?`Edit skill — ${e.name}`:"New skill"}),a.jsx(M,{type:"button",variant:"ghost","aria-label":"close skill editor",onClick:n,disabled:r,children:"✕"})]}),a.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"se-name",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(oe,{id:"se-name","aria-label":"skill name",placeholder:"My skill",value:i,onChange:x=>s(x.target.value),disabled:r,className:"min-w-48"})]}),a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"se-scope",className:"text-xs font-medium text-muted",children:"Scope"}),a.jsxs("select",{id:"se-scope","aria-label":"skill scope",value:c,onChange:x=>u(x.target.value),disabled:r||f,className:q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"project",children:"Project"}),a.jsx("option",{value:"global",children:"Global"})]})]})]}),a.jsx("div",{className:"flex shrink-0 items-center gap-0 border-b border-border px-4",children:["edit","preview"].map(x=>a.jsx("button",{type:"button",role:"tab","aria-label":x==="edit"?"Edit":"Preview","aria-selected":h===x,onClick:()=>d(x),className:q("px-4 py-2 text-sm font-medium capitalize transition-colors",h===x?"border-b-2 border-primary text-content":"text-muted hover:text-content"),children:x==="edit"?"Edit":"Preview"},x))}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:h==="edit"?a.jsx("textarea",{"aria-label":"skill content",value:l,onChange:x=>o(x.target.value),disabled:r,className:q("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Skill workflow - -...`}):a.jsx("div",{className:q("flex-1 overflow-auto rounded-md border border-border bg-raised px-6 py-4","prose prose-sm prose-invert max-w-none","[&_h1]:text-content [&_h2]:text-content [&_h3]:text-content","[&_p]:text-content/90 [&_li]:text-content/90","[&_code]:bg-canvas [&_code]:text-primary [&_code]:rounded [&_code]:px-1","[&_pre]:bg-canvas [&_pre]:border [&_pre]:border-border [&_pre]:rounded-md","[&_a]:text-primary [&_a:hover]:underline","[&_blockquote]:border-l-2 [&_blockquote]:border-primary [&_blockquote]:text-muted","[&_hr]:border-border"),children:l.trim()?a.jsx(pS,{remarkPlugins:[BS],children:l}):a.jsx("p",{className:"text-sm text-muted italic",children:"Nothing to preview yet."})})}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[a.jsx(M,{type:"button",variant:"ghost",onClick:n,disabled:r,children:"Cancel"}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"Save skill",disabled:!p,loading:r,children:"Save"})]})]})]})}function za(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function _O(e){const{skill:t}=fe(),[n,r]=g.useState([]),[i,s]=g.useState([]),[l,o]=g.useState(null),[c,u]=g.useState(!1),h=g.useCallback(async()=>{if(e){u(!0),o(null);try{const[x,w]=await Promise.all([t.listSkills(e,"global"),t.listSkills(e,"project")]);r(x),s(w)}catch(x){o(za(x))}finally{u(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=x=>x==="global"?r:s,f=g.useCallback(async x=>{u(!0),o(null);try{const w=await t.createSkill({...x,projectId:e});d(x.scope)(v=>[...v,w])}catch(w){o(za(w))}finally{u(!1)}},[t,e]),p=g.useCallback(async(x,w,v)=>{u(!0),o(null);try{const _=await t.updateSkill(e,x,w,v);d(x)(y=>y.map(b=>b.id===w?_:b))}catch(_){o(za(_))}finally{u(!1)}},[t,e]),m=g.useCallback(async(x,w)=>{u(!0),o(null);try{await t.deleteSkill(e,x,w),d(x)(v=>v.filter(_=>_.id!==w))}catch(v){o(za(v))}finally{u(!1)}},[t,e]);return{globalSkills:n,projectSkills:i,error:l,busy:c,refresh:h,createSkill:f,updateSkill:p,deleteSkill:m}}function FS({projectId:e}){const t=_O(e),[n,r]=g.useState(null),[i,s]=g.useState(!1);async function l(c,u,h){if(n){s(!0);try{n.mode==="create"?await t.createSkill({name:c,content:u,scope:h}):await t.updateSkill(n.skill.scope,n.skill.id,u),r(null)}finally{s(!1)}}}function o(c,u){return a.jsx("div",{className:"p-4",children:u.length===0?a.jsxs("p",{className:"text-sm text-muted",children:["No ",c," skills yet."]}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.map(h=>a.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[a.jsx("span",{className:"min-w-0 font-medium text-content",children:h.name}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit skill ${h.name}`,disabled:t.busy,onClick:()=>r({mode:"edit",skill:h}),children:"Edit"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete skill ${h.name}`,disabled:t.busy,onClick:()=>void t.deleteSkill(h.scope,h.id),className:"text-danger hover:text-danger",children:"Delete"})]})]},h.id))})})}return a.jsxs(a.Fragment,{children:[n!==null&&a.jsx(vO,{skill:n.mode==="edit"?n.skill:null,onSave:l,onClose:()=>r(null),busy:i}),a.jsxs(Se,{title:"Skills",className:"flex flex-col gap-0",children:[t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Skills"}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&a.jsx(Me,{size:14}),a.jsx(M,{type:"button",variant:"primary","aria-label":"create skill",disabled:t.busy,onClick:()=>r({mode:"create"}),children:"New skill"})]})]}),a.jsx("div",{className:"border-b border-border px-4 pt-3",children:a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Project"})}),o("project",t.projectSkills),a.jsx("div",{className:"border-y border-border px-4 pt-3",children:a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Global"})}),o("global",t.globalSkills)]})]})}function Ju(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function $S(){const{embedder:e}=fe(),[t,n]=g.useState([]),[r,i]=g.useState(null),[s,l]=g.useState(null),[o,c]=g.useState(!1),u=g.useCallback(async()=>{c(!0),l(null);try{const[p,m]=await Promise.all([e.listEmbedderProfiles(),e.describeEmbedderEngines()]);n(p),i(m)}catch(p){l(Ju(p))}finally{c(!1)}},[e]);g.useEffect(()=>{u()},[u]);const h=g.useCallback(async p=>{c(!0),l(null);try{await e.saveEmbedderProfile(p),await u()}catch(m){l(Ju(m)),c(!1)}},[e,u]),d=g.useCallback(async p=>{c(!0),l(null);try{await e.deleteEmbedderProfile(p),await u()}catch(m){l(Ju(m)),c(!1)}},[e,u]),f=t.find(p=>p.strategy!=="none")??null;return{profiles:t,engines:r,active:f,error:s,busy:o,refresh:u,saveProfile:h,deleteProfile:d}}const WS="http://localhost:11434/api/embeddings",HS="https://api.openai.com/v1/embeddings",Zu=[{strategy:"none",key:"none",label:"None (naïve recall)"},{strategy:"localOnnx",key:"localOnnx",label:"Local ONNX"},{strategy:"localServer",key:"localServer",label:"Ollama (local server)"},{strategy:"api",key:"api",label:"API"},{strategy:"api",key:"custom",label:"Custom"}],Wi={id:"",name:"",model:"",endpoint:"",apiKeyEnv:"",dimension:"",onnxEngineId:""};function yO(e,t,n){if(n)return{id:n.id,name:n.name,model:n.model??"",endpoint:n.endpoint??"",apiKeyEnv:n.apiKeyEnv??"",dimension:String(n.dimension),onnxEngineId:e==="localOnnx"?t.find(r=>r.id===n.model)?.id??t[0]?.id??"":""};switch(e){case"localOnnx":{const r=t.find(i=>i.recommended)??t[0];return{...Wi,id:"onnx-local",name:r?.displayName??"Local ONNX",model:r?.id??"",dimension:r?String(r.dimension):"",onnxEngineId:r?.id??""}}case"localServer":return{...Wi,id:"ollama",name:"Ollama",endpoint:WS,model:"nomic-embed-text",dimension:"768"};case"api":return{...Wi,id:"api",name:"API embedder",endpoint:HS,apiKeyEnv:"OPENAI_API_KEY",model:"text-embedding-3-small",dimension:"1536"};case"custom":return{...Wi,id:"custom",name:"Custom embedder"};default:return{...Wi}}}function bO(e,t){switch(e){case"none":return!0;case"localOnnx":return t.vectorOnnxEnabled;case"localServer":case"api":return t.vectorHttpEnabled}}function US(){const e=$S(),[t,n]=g.useState("localOnnx"),[r,i]=g.useState(Wi),s=e.engines?.recommendedOnnx??[],l={vectorOnnxEnabled:e.engines?.vectorOnnxEnabled??!1,vectorHttpEnabled:e.engines?.vectorHttpEnabled??!1};g.useEffect(()=>{if(!e.engines)return;const _=Zu.find(b=>b.key===t),y=e.active&&_&&e.active.strategy===_.strategy?e.active:null;i(yO(t,e.engines.recommendedOnnx,y))},[e.engines,e.active,t]);const c=Zu.find(_=>_.key===t).strategy;function u(_){i(y=>({...y,..._}))}function h(_){const y=s.find(b=>b.id===_);u({onnxEngineId:_,model:y?.id??_,dimension:y?String(y.dimension):r.dimension})}const d=Number.parseInt(r.dimension,10),f=g.useMemo(()=>c==="none"?{ok:!0}:r.id.trim()?r.name.trim()?!Number.isFinite(d)||d<=0?{ok:!1,msg:"Dimension must be a positive number."}:(c==="localServer"||c==="api")&&!r.endpoint.trim()?{ok:!1,msg:"Endpoint is required."}:{ok:!0}:{ok:!1,msg:"Name is required."}:{ok:!1,msg:"Id is required."},[c,r,d]);function p(){return{id:r.id.trim(),name:r.name.trim(),strategy:c,dimension:d,model:r.model.trim()||void 0,endpoint:(c==="localServer"||c==="api")&&r.endpoint.trim()||void 0,apiKeyEnv:c==="api"&&r.apiKeyEnv.trim()||void 0}}async function m(){f.ok&&await e.saveProfile(p())}async function x(){for(const _ of e.profiles)await e.deleteProfile(_.id);n("none")}const w=q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),v=e.active!==null;return a.jsxs(Se,{title:"Memory / Embedder",className:"flex flex-col gap-0",children:[e.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),a.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[a.jsx("p",{className:"rounded-md border border-border bg-raised px-3 py-2 text-xs text-muted","data-testid":"embedder-restart-note",children:"The embedder change takes effect at the next app start."}),a.jsxs("p",{className:"text-xs text-faint","data-testid":"embedder-active",children:["Current:"," ",v?a.jsxs("span",{className:"text-content",children:["Vector — ",e.active.strategy,e.active.model?` ${e.active.model}`:""]}):a.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),a.jsxs("fieldset",{className:"flex flex-col gap-2","aria-label":"embedder strategy",children:[a.jsx("legend",{className:"mb-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Strategy"}),Zu.map(_=>{const y=bO(_.strategy,l),b=_.key==="localOnnx";return a.jsxs("label",{className:q("flex items-center gap-2 rounded-md border px-3 py-2 text-sm",t===_.key?"border-primary bg-raised":"border-border",!y&&"opacity-50"),"data-testid":`embedder-strategy-${_.key}`,children:[a.jsx("input",{type:"radio",name:"embedder-strategy",value:_.key,checked:t===_.key,disabled:!y,onChange:()=>n(_.key),"aria-label":_.label}),a.jsx("span",{className:"text-content",children:_.label}),b&&a.jsx("span",{className:"rounded border border-primary/40 bg-primary/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-primary",children:"Recommended"}),!y&&a.jsx("span",{className:"text-[11px] text-faint",children:"not available in this build"})]},_.key)})]}),c!=="none"&&a.jsxs("div",{className:"flex flex-col gap-3",children:[c==="localOnnx"&&a.jsx(qt,{label:"ONNX model",children:({id:_})=>a.jsx("select",{id:_,"aria-label":"onnx model",className:w,value:r.onnxEngineId,disabled:e.busy,onChange:y=>h(y.target.value),children:s.map(y=>a.jsxs("option",{value:y.id,children:[y.displayName,y.recommended?" — recommended":""," (dim"," ",y.dimension,", ~",y.approxSizeMb," MB)"]},y.id))})}),(c==="localServer"||c==="api")&&a.jsx(qt,{label:"Endpoint",children:({id:_})=>a.jsx(oe,{id:_,"aria-label":"endpoint",placeholder:c==="localServer"?WS:HS,value:r.endpoint,disabled:e.busy,onChange:y=>u({endpoint:y.target.value})})}),c==="api"&&a.jsx(qt,{label:"API key environment variable",hint:"Name of the env var holding the key — never the key itself.",children:({id:_,describedBy:y})=>a.jsx(oe,{id:_,"aria-label":"api key env var",placeholder:"OPENAI_API_KEY","aria-describedby":y,value:r.apiKeyEnv,disabled:e.busy,onChange:b=>u({apiKeyEnv:b.target.value})})}),c!=="localOnnx"&&a.jsx(qt,{label:"Model",children:({id:_})=>a.jsx(oe,{id:_,"aria-label":"model",placeholder:"model name",value:r.model,disabled:e.busy,onChange:y=>u({model:y.target.value})})}),a.jsx(qt,{label:"Dimension",error:f.ok?void 0:f.msg,children:({id:_,describedBy:y})=>a.jsx(oe,{id:_,"aria-label":"dimension",type:"number",min:1,value:r.dimension,"aria-describedby":y,disabled:e.busy,onChange:b=>u({dimension:b.target.value})})}),a.jsx(qt,{label:"Profile id",children:({id:_})=>a.jsx(oe,{id:_,"aria-label":"profile id",placeholder:"my-embedder",value:r.id,disabled:e.busy,onChange:y=>u({id:y.target.value})})}),a.jsx(qt,{label:"Profile name",children:({id:_})=>a.jsx(oe,{id:_,"aria-label":"profile name",placeholder:"My embedder",value:r.name,disabled:e.busy,onChange:y=>u({name:y.target.value})})})]}),a.jsxs("div",{className:"flex items-center gap-2 border-t border-border pt-3",children:[e.busy&&a.jsx(Me,{size:14}),c!=="none"&&a.jsx(M,{type:"button",variant:"primary","aria-label":"save embedder",disabled:e.busy||!f.ok,onClick:()=>void m(),children:"Save"}),a.jsx(M,{type:"button","aria-label":"back to none",disabled:e.busy,onClick:()=>void x(),children:"Back to None"})]})]})]})}const wO=["user","feedback","project","reference"];function SO({entry:e,loadContent:t,resolveLinks:n,onCreate:r,onUpdate:i,onClose:s,busy:l=!1}){const o=e!=null,[c,u]=g.useState(e?.title??""),[h,d]=g.useState(e?.hook??""),[f,p]=g.useState(e?.type??"project"),[m,x]=g.useState(""),[w,v]=g.useState([]);g.useEffect(()=>{if(!e)return;let C=!1;return(async()=>{try{if(t){const S=await t(e.slug);C||x(S)}if(n){const S=await n(e.slug);C||v(S)}}catch{}})(),()=>{C=!0}},[e,t,n]);const _=h.trim().length>0&&m.trim().length>0&&!l&&(o||c.trim().length>0);async function y(C){C.preventDefault(),_&&(o?await i(e.slug,h.trim(),f,m):await r(c.trim(),h.trim(),f,m))}const b=q("h-9 w-full rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"memory editor",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border bg-surface px-4 py-3",children:[a.jsx("h2",{className:"text-sm font-semibold text-content",children:o?`Edit note — ${e.title}`:"New note"}),a.jsx(M,{type:"button",variant:"ghost","aria-label":"close memory editor",onClick:s,disabled:l,children:"✕"})]}),a.jsxs("form",{onSubmit:C=>void y(C),className:"flex flex-1 flex-col gap-0 overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-3 border-b border-border px-4 py-3",children:[o?a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Slug"}),a.jsx("code",{className:"truncate rounded-md border border-border bg-raised px-3 py-2 text-sm text-muted",children:e.slug})]}):a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[a.jsx("label",{htmlFor:"me-name",className:"text-xs font-medium text-muted",children:"Name"}),a.jsx(oe,{id:"me-name","aria-label":"memory name",placeholder:"My note",value:c,onChange:C=>u(C.target.value),disabled:l,className:"min-w-48"})]}),a.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[a.jsx("label",{htmlFor:"me-type",className:"text-xs font-medium text-muted",children:"Type"}),a.jsx("select",{id:"me-type","aria-label":"memory type",value:f,onChange:C=>p(C.target.value),disabled:l,className:b,children:wO.map(C=>a.jsx("option",{value:C,children:C},C))})]})]}),a.jsxs("div",{className:"flex shrink-0 flex-col gap-1 border-b border-border px-4 py-3",children:[a.jsx("label",{htmlFor:"me-description",className:"text-xs font-medium text-muted",children:"Description"}),a.jsx(oe,{id:"me-description","aria-label":"memory description",placeholder:"One-line hook",value:h,onChange:C=>d(C.target.value),disabled:l})]}),a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden px-4 py-3",children:[a.jsx("label",{htmlFor:"me-content",className:"mb-1 text-xs font-medium text-muted",children:"Content"}),a.jsx("textarea",{id:"me-content","aria-label":"memory content",value:m,onChange:C=>x(C.target.value),disabled:l,className:q("flex-1 w-full rounded-md bg-raised px-3 py-2 text-sm text-content font-mono","border border-border outline-none transition-colors resize-none","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50"),placeholder:`# Note - -Use [[other-slug]] to link…`}),o&&a.jsxs("div",{className:"mt-3 shrink-0",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Links"}),w.length===0?a.jsx("p",{className:"mt-1 text-sm text-muted",children:"No resolved links."}):a.jsx("ul",{className:"mt-1 flex flex-wrap gap-1.5",children:w.map(C=>a.jsx("li",{className:"rounded-md border border-border bg-raised px-2 py-0.5 text-xs text-muted",children:C},C))})]})]}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3",children:[a.jsx(M,{type:"button",variant:"ghost",onClick:s,disabled:l,children:"Cancel"}),a.jsx(M,{type:"submit",variant:"primary","aria-label":"Save note",disabled:!_,loading:l,children:"Save"})]})]})]})}function Fa(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function kO(e){const{memory:t,system:n}=fe(),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(!1),u=g.useCallback(async()=>{if(e){c(!0),l(null);try{i(await t.readIndex(e))}catch(m){l(Fa(m))}finally{c(!1)}}},[t,e]);g.useEffect(()=>{u()},[u]),g.useEffect(()=>{if(!n)return;let m,x=!1;return n.onDomainEvent(w=>{w.type==="memorySaved"&&u()}).then(w=>{x?w():m=w}),()=>{x=!0,m?.()}},[u,n]);const h=g.useCallback(async m=>{c(!0),l(null);try{await t.createMemory({...m,projectId:e}),await u()}catch(x){l(Fa(x)),c(!1)}},[t,e,u]),d=g.useCallback(async(m,x,w,v)=>{c(!0),l(null);try{await t.updateMemory(e,m,x,w,v),await u()}catch(_){l(Fa(_)),c(!1)}},[t,e,u]),f=g.useCallback(async m=>{c(!0),l(null);try{await t.deleteMemory(e,m),await u()}catch(x){l(Fa(x)),c(!1)}},[t,e,u]),p=g.useCallback(m=>t.resolveLinks(e,m),[t,e]);return{entries:r,error:s,busy:o,refresh:u,createMemory:h,updateMemory:d,deleteMemory:f,resolveLinks:p}}function qS({projectId:e}){const t=kO(e),n=$S(),{memory:r}=fe(),[i,s]=g.useState(null),[l,o]=g.useState(!1),c=g.useCallback(async d=>(await r.getMemory(e,d)).content,[r,e]);async function u(d,f,p,m){o(!0);try{await t.createMemory({name:d,description:f,type:p,content:m}),s(null)}finally{o(!1)}}async function h(d,f,p,m){o(!0);try{await t.updateMemory(d,f,p,m),s(null)}finally{o(!1)}}return a.jsxs(a.Fragment,{children:[i!==null&&a.jsx(SO,{entry:i.mode==="edit"?i.entry:null,loadContent:c,resolveLinks:t.resolveLinks,onCreate:u,onUpdate:h,onClose:()=>s(null),busy:l}),a.jsxs(Se,{title:"Memory",className:"flex flex-col gap-0",children:[a.jsxs("p",{className:"border-b border-border px-4 py-2 text-xs text-faint","data-testid":"memory-tier",children:["Tier:"," ",n.active?a.jsxs("span",{className:"text-content",children:["Vector — ",n.active.strategy,n.active.model?` ${n.active.model}`:""]}):a.jsx("span",{className:"text-content",children:"Naïve (None)"})]}),t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Notes"}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.busy&&a.jsx(Me,{size:14}),a.jsx(M,{type:"button",variant:"primary","aria-label":"create memory",disabled:t.busy,onClick:()=>s({mode:"create"}),children:"New note"})]})]}),a.jsx("div",{className:"p-4",children:t.entries.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No memory notes yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.entries.map(d=>a.jsxs("li",{className:"flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0",children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"min-w-0 truncate font-medium text-content",children:d.title}),a.jsx("span",{className:"shrink-0 rounded border border-border bg-raised px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted",children:d.type})]}),a.jsx("span",{className:"truncate text-xs text-muted",children:d.hook})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`edit memory ${d.title}`,disabled:t.busy,onClick:()=>s({mode:"edit",entry:d}),children:"Edit"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete memory ${d.title}`,disabled:t.busy,onClick:()=>void t.deleteMemory(d.slug),className:"text-danger hover:text-danger",children:"Delete"})]})]},d.slug))})})]})]})}const Cv=[{id:"readProject",label:"Lecture projet",tools:["idea_list_agents","idea_context_read","idea_memory_read","idea_skill_read","idea_workstate_read"]},{id:"readTickets",label:"Lecture tickets",tools:["idea_ticket_read","idea_ticket_list","idea_ticket_read_carnet","idea_sprint_list"]},{id:"delegation",label:"Délégation agents",tools:["idea_ask_agent","idea_launch_agent","idea_stop_agent"]},{id:"contextMemory",label:"Contexte et mémoire",tools:["idea_update_context","idea_context_propose","idea_memory_write"]},{id:"tickets",label:"Tickets",tools:["idea_ticket_create","idea_ticket_update","idea_ticket_update_status","idea_ticket_update_priority","idea_ticket_update_carnet","idea_ticket_link","idea_ticket_unlink"]},{id:"work",label:"Travail et exécution",tools:["idea_run_in_background","idea_workstate_set"]},{id:"skills",label:"Skills",tools:["idea_create_skill"]}],CO={idea_list_agents:"Lister les agents",idea_context_read:"Lire le contexte d'un agent",idea_memory_read:"Lire la mémoire projet",idea_skill_read:"Lire un skill",idea_workstate_read:"Lire l'état de travail",idea_ticket_read:"Lire un ticket",idea_ticket_list:"Lister les tickets",idea_ticket_read_carnet:"Lire le carnet d'un ticket",idea_sprint_list:"Lister les sprints",idea_ask_agent:"Déléguer à un agent",idea_launch_agent:"Lancer un agent",idea_stop_agent:"Arrêter un agent",idea_update_context:"Modifier le contexte d'un agent",idea_context_propose:"Proposer un contexte",idea_memory_write:"Écrire la mémoire projet",idea_workstate_set:"Écrire l'état de travail",idea_create_skill:"Créer un skill",idea_ticket_create:"Créer un ticket",idea_ticket_update:"Modifier un ticket",idea_ticket_update_status:"Modifier le statut d'un ticket",idea_ticket_update_priority:"Modifier la priorité d'un ticket",idea_ticket_update_carnet:"Modifier le carnet d'un ticket",idea_ticket_link:"Lier des tickets",idea_ticket_unlink:"Délier des tickets",idea_run_in_background:"Exécuter une commande en arrière-plan"};function jO(e){return CO[e]??e}function $a(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function NO(e){const{permission:t}=fe(),[n,r]=g.useState(null),[i,s]=g.useState(!1),[l,o]=g.useState(!1),[c,u]=g.useState(null),h=g.useCallback(async()=>{if(t){s(!0),u(null);try{r(await t.getMcpToolPermissions(e))}catch(m){u($a(m))}finally{s(!1)}}},[t,e]);g.useEffect(()=>{h()},[h]);const d=g.useCallback(async m=>{if(t){o(!0),u(null);try{r(await t.updateProjectMcpToolPermissions(e,m))}catch(x){throw u($a(x)),x}finally{o(!1)}}},[t,e]),f=g.useCallback(async(m,x)=>{if(t){o(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,x))}catch(w){throw u($a(w)),w}finally{o(!1)}}},[t,e]),p=g.useCallback(async m=>{if(t){o(!0),u(null);try{r(await t.updateAgentMcpToolPermissions(e,m,null))}catch(x){throw u($a(x)),x}finally{o(!1)}}},[t,e]);return{doc:n,loading:i,busy:l,error:c,refresh:h,saveProjectDefault:d,saveAgentOverride:f,resetAgentOverride:p}}const EO=new Set(["readProject","readTickets"]);function PO(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function AO(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(r=>n.has(r))}function TO({projectId:e,agents:t}){const n=NO(e),[r,i]=g.useState({type:"project"}),s=g.useRef(!1);function l(u){s.current&&!window.confirm("Des modifications non enregistrées seront perdues. Continuer ?")||(s.current=!1,i(u))}if(n.loading&&!n.doc)return a.jsxs("div",{"data-testid":"mcp-tool-permissions-skeleton",className:"flex flex-col gap-3 p-4",children:[a.jsx("div",{className:"h-4 w-40 animate-pulse rounded bg-raised"}),a.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),a.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-raised"}),a.jsx("div",{className:"h-32 w-full animate-pulse rounded bg-raised"})]});if(n.error&&!n.doc)return a.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[a.jsx("p",{role:"alert",className:"text-sm text-danger",children:n.error}),a.jsx(M,{size:"sm",onClick:()=>void n.refresh(),children:"Réessayer"})]});if(!n.doc)return null;const o=n.doc,c=r.type==="agent"?o.agents.find(u=>u.agentId===r.agentId)??null:null;return a.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4 md:flex-row",children:[a.jsxs("nav",{"aria-label":"cibles des permissions MCP",className:"flex w-full shrink-0 flex-col gap-2 md:w-56",children:[a.jsxs("button",{type:"button","aria-pressed":r.type==="project",onClick:()=>l({type:"project"}),className:q("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",r.type==="project"?"border-primary bg-raised":"border-border bg-surface"),children:[a.jsx("span",{className:"font-medium text-content",children:"Défaut projet"}),a.jsx("span",{className:"text-xs text-muted",children:o.projectDefault?"Personnalisé":"Lecture seule"})]}),a.jsx("h4",{className:"mt-1 text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun agent dans ce projet."}):a.jsx("ul",{className:"flex flex-col gap-1.5",children:t.map(u=>{const h=o.agents.some(f=>f.agentId===u.id),d=r.type==="agent"&&r.agentId===u.id;return a.jsx("li",{children:a.jsxs("button",{type:"button","aria-pressed":d,onClick:()=>l({type:"agent",agentId:u.id,agentName:u.name}),className:q("flex min-h-[32px] w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-sm","transition-colors hover:border-border-strong hover:bg-raised",d?"border-primary bg-raised":"border-border bg-surface"),children:[a.jsx("span",{className:"truncate font-medium text-content",children:u.name}),a.jsx("span",{className:q("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",h?"bg-warning/15 text-warning":"bg-primary/10 text-muted"),children:h?"Override":"Hérité"})]})},u.id)})})]}),a.jsx("div",{className:"min-w-0 flex-1",children:r.type==="project"?a.jsx(jv,{targetKind:"project",title:"Tools MCP IdeA — Défaut projet",catalogue:o.catalogue,storedAllowed:o.projectDefault?.allowedTools??null,comparisonBaseline:o.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{s.current=u},onSaveProjectDefault:async u=>{await n.saveProjectDefault({allowedTools:u})}},"project"):a.jsx(jv,{targetKind:"agent",title:`Tools MCP IdeA — ${r.agentName}`,catalogue:o.catalogue,storedAllowed:c?.policy.allowedTools??null,comparisonBaseline:o.projectDefault?.allowedTools??o.catalogue.readOnlyTools,busy:n.busy,onDirtyChange:u=>{s.current=u},onSaveAgentOverride:async u=>{await n.saveAgentOverride(r.agentId,{allowedTools:u})},onResetOverride:async()=>{await n.resetAgentOverride(r.agentId)}},r.agentId)})]})}function jv({targetKind:e,title:t,catalogue:n,storedAllowed:r,comparisonBaseline:i,busy:s,onDirtyChange:l,onSaveProjectDefault:o,onSaveAgentOverride:c,onResetOverride:u}){const h=r??i,[d,f]=g.useState(e==="project"||r!=null),[p,m]=g.useState(r!=null),[x,w]=g.useState(h),[v,_]=g.useState(h),[y,b]=g.useState(!1),[C,S]=g.useState(!1),[N,R]=g.useState(null),[D,k]=g.useState(()=>Object.fromEntries(Cv.map(ie=>[ie.id,EO.has(ie.id)?e==="project":!0]))),L=e==="project"||d,A=L?x:i,P=L&&!AO(x,v);g.useEffect(()=>{l(P)},[P]),g.useEffect(()=>{if(!C)return;const ie=window.setTimeout(()=>S(!1),2e3);return()=>window.clearTimeout(ie)},[C]);const I=n.readOnlyTools.filter(ie=>A.includes(ie)).length,O=n.writeActionTools.filter(ie=>A.includes(ie)).length,U=g.useMemo(()=>new Set([...n.readOnlyTools,...n.writeActionTools]),[n]),K=g.useMemo(()=>Array.from(new Set([...A,...i])).filter(ie=>!U.has(ie)),[A,i,U]);function E(ie){R(null),w(ee=>PO(ee,ie))}function F(ie){k(ee=>({...ee,[ie]:!ee[ie]}))}function j(){f(!0),w(i),_(i)}function re(){w(v),b(!1),R(null)}async function V(){if(R(null),e==="project"){if(x.some(ee=>n.writeActionTools.includes(ee)&&!v.includes(ee))&&!y){b(!0);return}b(!1);try{await o?.(x),_(x),S(!0)}catch(ee){R(ed(ee))}return}try{await c?.(x),_(x),m(!0),S(!0)}catch(ie){R(ed(ie))}}async function T(){R(null);try{await u?.(),f(!1),m(!1),w(i),_(i),S(!0)}catch(ie){R(ed(ie))}}return a.jsx(Se,{title:t,className:"flex h-full flex-col",flush:!0,children:a.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e==="agent"&&a.jsx("p",{className:"text-xs text-muted",children:d?"Override personnalisé":"Hérite du défaut projet"}),e==="agent"&&!d&&a.jsx(M,{size:"sm",onClick:j,disabled:s,children:"Créer un override"}),a.jsxs("div",{children:[a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Résumé effectif"}),a.jsxs("p",{className:"text-sm text-content",children:[I," lecture autorisés · ",O," écriture autorisé",O>1?"s":""]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Détail des tools"}),Cv.map(ie=>a.jsx(Nv,{group:ie,expanded:D[ie.id]??!0,onToggle:()=>F(ie.id),catalogue:n,editable:L,targetKind:e,draftSet:x,displaySet:A,comparisonBaseline:i,onToggleTool:E},ie.id)),K.length>0&&a.jsx(Nv,{group:{id:"unknown",label:"Tools inconnus",tools:K},expanded:D.unknown??!0,onToggle:()=>F("unknown"),catalogue:n,editable:!1,targetKind:e,draftSet:x,displaySet:A,comparisonBaseline:i,onToggleTool:E,unknown:!0})]}),y&&a.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning",children:[a.jsx("p",{children:"Ce tool sera autorisé pour tous les agents sans override. Confirmer cette modification ?"}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>b(!1),children:"Annuler"}),a.jsx(M,{size:"sm",variant:"primary",onClick:()=>void V(),children:"Confirmer"})]})]}),N&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:N}),C&&a.jsx("p",{role:"status",className:"text-sm text-success",children:"Permissions enregistrées"}),a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[a.jsx("div",{children:P&&a.jsx("span",{className:"text-xs text-warning",children:"Modifications non enregistrées"})}),a.jsxs("div",{className:"flex gap-2",children:[e==="agent"&&p&&a.jsx(M,{size:"sm",variant:"ghost",disabled:s,onClick:()=>void T(),children:"Réinitialiser l'override"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:s||!P,onClick:re,children:"Annuler"}),a.jsx(M,{size:"sm",variant:"primary",disabled:s||!L||!P,loading:s&&P,onClick:()=>void V(),children:"Enregistrer"})]})]})]})})}function Nv({group:e,expanded:t,onToggle:n,catalogue:r,editable:i,targetKind:s,displaySet:l,comparisonBaseline:o,onToggleTool:c,unknown:u}){const h=e.tools.filter(f=>l.includes(f)).length,d=e.tools.length;return a.jsxs("div",{className:"rounded-md border border-border",children:[a.jsxs("button",{type:"button","aria-expanded":t,"aria-label":`${e.label}, ${h} sur ${d} autorisé${d>1?"s":""}`,onClick:n,className:"flex min-h-[32px] w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-raised",children:[a.jsx("span",{className:"font-medium text-content",children:e.label}),a.jsxs("span",{className:"text-xs text-muted",children:[h,"/",d," autorisés"]})]}),t&&a.jsx("ul",{className:"flex flex-col divide-y divide-border border-t border-border",children:e.tools.map(f=>a.jsx(RO,{tool:f,isRead:r.readOnlyTools.includes(f),unknown:u,editable:i,checked:l.includes(f),status:LO(f,i,s,l,o,u),onToggle:()=>c(f)},f))})]})}function LO(e,t,n,r,i,s){if(s)return"unknown";if(n==="agent"&&!t)return"inherited";if(n==="agent"&&t){const l=r.includes(e),o=i.includes(e);return l&&!o?"added":!l&&o?"removed":l?"allowed":"denied"}return r.includes(e)?"allowed":"denied"}const DO={allowed:"Autorisé",denied:"Refusé",inherited:"Hérité",added:"Ajouté",removed:"Retiré",unknown:"Inconnu"};function RO({tool:e,isRead:t,unknown:n,editable:r,checked:i,status:s,onToggle:l}){const o=jO(e),c=`mcp-tool-${e}`;return a.jsxs("li",{className:"flex min-h-[32px] items-center gap-2 px-3 py-1.5",children:[a.jsx("input",{id:c,type:"checkbox",checked:i,disabled:!r||n,onChange:l,"aria-label":`${o}, ${e}`}),a.jsxs("label",{htmlFor:c,className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("code",{className:"font-mono text-xs text-content",children:e}),!n&&a.jsx("span",{className:q("rounded-full px-1.5 py-0.5 text-[10px] font-medium",t?"bg-primary/10 text-primary":"bg-warning/15 text-warning"),children:t?"Lecture":"Écriture"})]}),a.jsx("span",{className:"text-xs text-muted",children:o})]}),a.jsx("span",{className:q("shrink-0 rounded-full px-2 py-0.5 text-xs font-medium",s==="allowed"||s==="added"?"bg-success/15 text-success":s==="denied"||s==="removed"?"bg-danger/10 text-muted":s==="unknown"?"bg-danger/15 text-danger":"bg-primary/10 text-muted"),children:DO[s]})]})}function ed(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Ev={fallback:"ask",read:"none",write:"none",delete:"none",executeBash:"none"},VS=["read","write","delete","executeBash"];function Js(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function KS(e){if(!e)return{...Ev};const t={...Ev,fallback:e.fallback};for(const n of VS)t[n]=MO(e.rules,n);return t}function MO(e,t){const n=e.filter(r=>r.capability===t);return n.some(r=>r.effect==="deny")?"deny":n.some(r=>r.effect==="allow")?"allow":"none"}function Pv(e){const t=[];for(const n of VS){const r=e[n];r!=="none"&&t.push(IO(n,r))}return{fallback:e.fallback,rules:t}}function IO(e,t){return e==="executeBash"?{capability:e,effect:t,commands:[]}:{capability:e,effect:t,paths:["**"]}}function Wa(e){return e?e.rules.some(t=>{if(t.capability==="executeBash")return(t.commands??[]).length>0;const n=t.paths??[];return n.length!==1||n[0]!=="**"}):!1}function OO(e){const{agent:t,permission:n}=fe(),[r,i]=g.useState([]),[s,l]=g.useState(null),[o,c]=g.useState(!1),[u,h]=g.useState(null),d=g.useCallback(async()=>{c(!0),h(null);try{const[_,y]=await Promise.all([t.listAgents(e),n.getProjectPermissions(e)]);i(_),l(y)}catch(_){h(Js(_))}finally{c(!1)}},[t,n,e]);g.useEffect(()=>{d()},[d]);const f=g.useMemo(()=>{const _=new Map((s?.agents??[]).map(y=>[y.agentId,y.permissions]));return r.map(y=>({agent:y,override:_.get(y.id)??null}))},[r,s]),p=g.useMemo(()=>KS(s?.projectDefaults??null),[s]),m=g.useCallback(async _=>{c(!0),h(null);try{l(await n.updateProjectPermissions(e,Pv(_)))}catch(y){h(Js(y))}finally{c(!1)}},[n,e]),x=g.useCallback(async()=>{c(!0),h(null);try{l(await n.updateProjectPermissions(e,null))}catch(_){h(Js(_))}finally{c(!1)}},[n,e]),w=g.useCallback(async(_,y)=>{c(!0),h(null);try{l(await n.updateAgentPermissions(e,_,Pv(y)))}catch(b){h(Js(b))}finally{c(!1)}},[n,e]),v=g.useCallback(async _=>{c(!0),h(null);try{l(await n.updateAgentPermissions(e,_,null))}catch(y){h(Js(y))}finally{c(!1)}},[n,e]);return{agents:r,rows:f,document:s,projectDraft:p,busy:o,error:u,refresh:d,saveProjectDefaults:m,clearProjectDefaults:x,saveAgentOverride:w,clearAgentOverride:v}}const Bi=[{id:"system",label:"Système"},{id:"mcpTools",label:"Tools MCP IdeA"}],BO=[{key:"read",label:"Read"},{key:"write",label:"Write"},{key:"delete",label:"Delete"},{key:"executeBash",label:"Bash"}],zO={ask:"Ask",allow:"Allow",deny:"Deny"};function GS({projectId:e}){const t=OO(e),[n,r]=g.useState({type:"project"}),[i,s]=g.useState("system"),l=n.type==="agent"?t.rows.find(p=>p.agent.id===n.agentId)??null:null,o=l?.override??t.document?.projectDefaults??null,c=n.type==="project"?t.projectDraft:KS(l?.override??t.document?.projectDefaults??null),u=n.type==="project"?Wa(t.document?.projectDefaults):Wa(l?.override),h=t.document?.projectDefaults!=null;async function d(p){n.type==="project"?await t.saveProjectDefaults(p):await t.saveAgentOverride(n.agentId,p)}async function f(){n.type==="project"?await t.clearProjectDefaults():await t.clearAgentOverride(n.agentId)}return a.jsxs(Se,{title:"Permissions",actions:a.jsx(M,{size:"sm",variant:"ghost",disabled:t.busy,onClick:()=>void t.refresh(),children:"Refresh"}),className:"flex min-h-0 flex-1 flex-col",flush:!0,children:[a.jsx("div",{role:"tablist","aria-label":"Permissions",className:"flex gap-1 border-b border-border px-4 pt-2",children:Bi.map(p=>a.jsx("button",{type:"button",role:"tab",id:`permissions-tab-${p.id}`,"aria-selected":i===p.id,"aria-controls":`permissions-tabpanel-${p.id}`,tabIndex:i===p.id?0:-1,onClick:()=>s(p.id),onKeyDown:m=>{if(m.key!=="ArrowRight"&&m.key!=="ArrowLeft")return;m.preventDefault();const x=Bi.findIndex(v=>v.id===i),w=m.key==="ArrowRight"?(x+1)%Bi.length:(x-1+Bi.length)%Bi.length;s(Bi[w].id)},className:q("min-h-[32px] rounded-t-md border-b-2 px-3 py-1.5 text-sm font-medium transition-colors",i===p.id?"border-primary text-content":"border-transparent text-muted hover:text-content"),children:p.label},p.id))}),t.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{role:"tabpanel",id:"permissions-tabpanel-system","aria-labelledby":"permissions-tab-system",hidden:i!=="system",className:"flex flex-col gap-4 p-4",children:[a.jsx(Av,{title:"Project defaults",subtitle:h?"Configured":"Native CLI behavior",active:n.type==="project",custom:Wa(t.document?.projectDefaults),onSelect:()=>r({type:"project"}),policy:t.document?.projectDefaults??null}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"Agents"}),t.busy&&a.jsx(Me,{size:14})]}),t.rows.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No agents yet."}):a.jsx("ul",{className:"flex flex-col gap-2",children:t.rows.map(p=>{const m=n.type==="agent"&&n.agentId===p.agent.id;return a.jsx("li",{children:a.jsx(Av,{title:p.agent.name,subtitle:p.override?"Override":"Inherited",active:m,custom:Wa(p.override),onSelect:()=>r({type:"agent",agentId:p.agent.id,agentName:p.agent.name}),policy:p.override})},p.agent.id)})})]}),a.jsx(FO,{title:n.type==="project"?"Project defaults":`Override — ${n.agentName}`,draft:c,sourcePolicy:o,custom:u,canClear:n.type==="project"?t.document?.projectDefaults!=null:l?.override!=null,busy:t.busy,onSave:p=>void d(p),onClear:()=>void f()},n.type==="project"?"project":n.agentId)]}),a.jsx("div",{role:"tabpanel",id:"permissions-tabpanel-mcpTools","aria-labelledby":"permissions-tab-mcpTools",hidden:i!=="mcpTools",className:"flex min-h-0 flex-1 flex-col",children:i==="mcpTools"&&a.jsx(TO,{projectId:e,agents:t.agents})})]})}function Av({title:e,subtitle:t,active:n,custom:r,policy:i,onSelect:s}){return a.jsxs("button",{type:"button",onClick:s,"aria-pressed":n,className:q("flex w-full min-w-0 items-center justify-between gap-3 rounded-md border px-3 py-2 text-left","transition-colors hover:border-border-strong hover:bg-raised",n?"border-primary bg-raised":"border-border bg-surface"),children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:e}),a.jsx("span",{className:"text-xs text-muted",children:t})]}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[r&&a.jsx("span",{className:"rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Custom"}),i&&a.jsx("span",{className:"rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary",children:zO[i.fallback]})]})]})}function FO({title:e,draft:t,sourcePolicy:n,custom:r,canClear:i,busy:s,onSave:l,onClear:o}){const[c,u]=g.useState(t),h=g.useRef(t);g.useEffect(()=>{u(p=>JSON.stringify(p)===JSON.stringify(h.current)?t:p),h.current=t},[t]);const d=g.useMemo(()=>JSON.stringify(c)!==JSON.stringify(t),[t,c]);function f(p,m){u(x=>({...x,[p]:m}))}return a.jsxs("section",{className:"rounded-md border border-border bg-surface",children:[a.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-3 py-2.5",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx("h4",{className:"truncate text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"text-xs text-muted",children:n?`${n.rules.length} rules`:"Not configured"})]}),r&&a.jsx("span",{className:"shrink-0 rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning",children:"Advanced"})]}),a.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Fallback"}),a.jsxs("select",{"aria-label":`${e} fallback`,value:c.fallback,disabled:s,onChange:p=>u(m=>({...m,fallback:p.target.value})),className:q("h-9 rounded-md border border-border bg-raised px-3 text-sm text-content","outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),children:[a.jsx("option",{value:"ask",children:"Ask"}),a.jsx("option",{value:"allow",children:"Allow"}),a.jsx("option",{value:"deny",children:"Deny"})]})]}),a.jsx("div",{className:"grid grid-cols-1 gap-2",children:BO.map(p=>a.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] items-center gap-2",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:p.label}),a.jsx($O,{value:c[p.key],disabled:s,label:p.label,onChange:m=>f(p.key,m)})]},p.key))}),a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2 pt-1",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:s||!i,onClick:o,children:"Clear"}),a.jsx(M,{size:"sm",variant:"primary",disabled:s||!d,loading:s&&d,onClick:()=>l(c),children:"Save"})]})]})]})}function $O({value:e,disabled:t,label:n,onChange:r}){const i=[{value:"none",label:"None"},{value:"allow",label:"Allow"},{value:"deny",label:"Deny"}];return a.jsx("div",{role:"group","aria-label":`${n} permission`,className:"grid grid-cols-3 overflow-hidden rounded-md border border-border",children:i.map(s=>a.jsx("button",{type:"button",disabled:t,"aria-pressed":e===s.value,onClick:()=>r(s.value),className:q("h-8 min-w-0 border-r border-border px-2 text-xs font-medium last:border-r-0","transition-colors disabled:cursor-not-allowed disabled:opacity-50",e===s.value?s.value==="deny"?"bg-danger/20 text-danger":s.value==="allow"?"bg-success/20 text-success":"bg-raised text-content":"bg-surface text-muted hover:bg-raised hover:text-content"),children:s.label},s.value))})}function Ip(e){return e.type.startsWith("issue")}function YS(e){return e.type.startsWith("sprint")}function WO(e){return e.replace(/[\s-]+/g,"").toUpperCase()}const HO=["open","inProgress","QA","closed"],UO=["low","medium","high","critical"],qO=["number","priority","status","title"],VO=["asc","desc"];function XS(e){return`tickets:listFilters:${e}`}function KO(e){return`tickets:pickerFilters:${e}`}function QS(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tv(e,t){if(!Array.isArray(e))return;const n=new Set(t),r=[];for(const i of e)typeof i=="string"&&n.has(i)&&!r.includes(i)&&r.push(i);return r.length>0?r:void 0}function GO(e){if(!QS(e))return;const{field:t,direction:n}=e;if(typeof t=="string"&&qO.includes(t)&&typeof n=="string"&&VO.includes(n))return{field:t,direction:n}}function JS(e,t={}){if(!QS(e))return{};const n={};typeof e.text=="string"&&e.text.length>0&&(n.text=e.text);const r=Tv(e.statuses,HO);r&&(n.statuses=r);const i=Tv(e.priorities,UO);if(i&&(n.priorities=i),typeof e.assignedAgentId=="string"&&e.assignedAgentId){const{validAgentIds:l}=t;(!l||l.has(e.assignedAgentId))&&(n.assignedAgentId=e.assignedAgentId)}const s=GO(e.sort);return s&&(n.sort=s),typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0&&(n.limit=e.limit),n}function YO(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.assignedAgentId&&(t.assignedAgentId=e.assignedAgentId),e.sort&&(t.sort=e.sort),typeof e.limit=="number"&&(t.limit=e.limit),Object.keys(t).length>0?t:null}function XO(e){const t={};return e.text&&(t.text=e.text),e.statuses&&e.statuses.length>0&&(t.statuses=e.statuses),e.priorities&&e.priorities.length>0&&(t.priorities=e.priorities),e.sort&&(t.sort=e.sort),Object.keys(t).length>0?t:null}function Lv(e,t,n){return e?JS(e.read(XS(t)),n):{}}function QO(e,t,n){if(!e)return;const r=YO(n),i=XS(t);r?e.write(i,r):e.remove(i)}function kr(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Op(e){const{ticket:t,system:n,uiPreferences:r}=fe(),[i,s]=g.useState(null),[l,o]=g.useState([]),[c,u]=g.useState(null),[h,d]=g.useState(!1),[f,p]=g.useState(()=>Lv(r,e)),m=g.useRef(e);g.useEffect(()=>{m.current!==e&&(m.current=e,p(Lv(r,e)))},[e,r]),g.useEffect(()=>{QO(r,e,f)},[r,e,f]);const x=g.useMemo(()=>JSON.stringify(f),[f]),w=g.useCallback(async()=>{d(!0),u(null);try{s(await t.list(e,f))}catch(L){u(kr(L))}finally{d(!1)}},[e,t,x]),v=g.useCallback(L=>{p(A=>{const P=A.statuses??[],I=P.includes(L)?P.filter(K=>K!==L):[...P,L],{statuses:O,...U}=A;return I.length>0?{...U,statuses:I}:U})},[]),_=g.useCallback(L=>{p(A=>{const P=A.priorities??[],I=P.includes(L)?P.filter(K=>K!==L):[...P,L],{priorities:O,...U}=A;return I.length>0?{...U,priorities:I}:U})},[]),y=g.useCallback(()=>{p(({statuses:L,priorities:A,...P})=>P)},[]),b=g.useCallback(async()=>{try{o(await t.listSprints(e))}catch(L){u(kr(L))}},[e,t]),C=g.useCallback(async L=>{u(null);try{const A=await t.create(e,L);return await w(),A}catch(A){return u(kr(A)),null}},[e,t,w]),S=g.useCallback(async(L,A)=>{u(null);try{const P=await t.read(e,L);return await t.setTicketSprint(e,L,A,P.version),await Promise.all([w(),b()]),!0}catch(P){return u(kr(P)),!1}},[e,t,w,b]),N=g.useCallback(async L=>{u(null);try{const A=await t.createSprint(e,L);return await b(),A}catch(A){return u(kr(A)),null}},[e,t,b]),R=g.useCallback(async(L,A)=>{u(null);try{const P=l.find(I=>I.id===L);return P?(await t.renameSprint(e,L,A,P.version),await b(),!0):!1}catch(P){return u(kr(P)),!1}},[e,t,l,b]),D=g.useCallback(async(L,A)=>{u(null);const P=[...l].sort((K,E)=>K.order-E.order),I=P.findIndex(K=>K.id===L),O=A==="up"?I-1:I+1;if(I===-1||O<0||O>=P.length)return!1;const U=[...P];[U[I],U[O]]=[U[O],U[I]];try{return await t.reorderSprints(e,U.map(K=>K.id)),await b(),!0}catch(K){return u(kr(K)),!1}},[e,t,l,b]),k=g.useCallback(async L=>{u(null);try{return await t.deleteSprint(e,L),await Promise.all([w(),b()]),!0}catch(A){return u(kr(A)),!1}},[e,t,w,b]);return g.useEffect(()=>{w()},[w]),g.useEffect(()=>{b()},[b]),g.useEffect(()=>{if(!n)return;let L,A=!1;return n.onDomainEvent(P=>{Ip(P)&&w(),(YS(P)||P.type==="issueSprintChanged")&&b()}).then(P=>{A?P():L=P}),()=>{A=!0,L?.()}},[w,b,n]),{list:i,sprints:l,error:c,busy:h,query:f,setQuery:p,toggleStatus:v,togglePriority:_,clearFacets:y,refresh:w,create:C,assignSprint:S,createSprint:N,renameSprint:R,moveSprint:D,deleteSprint:k}}function ZS(e){const{agent:t}=fe(),[n,r]=g.useState([]),[i,s]=g.useState(!1);g.useEffect(()=>{let c=!1;return s(!1),t.listAgents(e).then(u=>{c||(r(u),s(!0))}).catch(()=>{c||(r([]),s(!0))}),()=>{c=!0}},[e,t]);const l=g.useMemo(()=>new Map(n.map(c=>[c.id,c.name])),[n]);return{agents:n,nameOf:c=>l.get(c)??`${c.slice(0,8)}…`,loaded:i}}const Tc=["open","inProgress","QA","closed"],js=["low","medium","high","critical"],e0=["relatesTo","blocks","blockedBy","duplicates","dependsOn"];function Bp(e){switch(e){case"open":return"Open";case"inProgress":return"In progress";case"QA":return"QA";case"closed":return"Closed"}}function Lc(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Dv(e){switch(e){case"relatesTo":return"relates to";case"blocks":return"blocks";case"blockedBy":return"blocked by";case"duplicates":return"duplicates";case"dependsOn":return"depends on"}}function JO(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function ZO(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function t0(e){return q("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function ia({status:e}){return a.jsx("span",{className:t0(JO(e)),children:Bp(e)})}function sa({priority:e}){return a.jsx("span",{className:t0(ZO(e)),children:Lc(e)})}function vs({ticketRef:e,onOpen:t,className:n}){const r=q("inline-flex shrink-0 items-center rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",n);return t?a.jsx("button",{type:"button","aria-label":`open ticket ${e}`,className:q(r,"transition-colors hover:bg-primary/15 hover:text-primary"),onClick:()=>t(e),children:e}):a.jsx("code",{className:r,children:e})}const eB=/#\d+/g;function tB(e,t){const n=[];let r=0,i=0;for(const s of e.matchAll(eB)){const l=s.index??0;l>r&&n.push(e.slice(r,l)),n.push(a.jsx(vs,{ticketRef:s[0],onOpen:t},`ref-${i++}-${l}`)),r=l+s[0].length}return r0||r.length>0;return a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(oe,{"aria-label":"search tickets",placeholder:o,value:e,onChange:d=>t(d.target.value)}),a.jsxs("fieldset",{"aria-label":"filter by status",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[a.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Statut"}),Tc.map(d=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[a.jsx("input",{type:"checkbox","aria-label":`filter status ${Bp(d)}`,className:"accent-primary",checked:n.includes(d),onChange:()=>i(d)}),a.jsx(ia,{status:d})]},d))]}),a.jsxs("fieldset",{"aria-label":"filter by priority",className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[a.jsx("legend",{className:"mr-1 text-xs font-medium text-muted",children:"Priorité"}),js.map(d=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs",children:[a.jsx("input",{type:"checkbox","aria-label":`filter priority ${Lc(d)}`,className:"accent-primary",checked:r.includes(d),onChange:()=>s(d)}),a.jsx(sa,{priority:d})]},d))]}),u&&a.jsxs("div",{"aria-label":"sort tickets",className:"flex flex-wrap items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted",children:["Trier par",a.jsxs("select",{"aria-label":"sort tickets by",className:nB,value:c?.field??"",onChange:d=>{const f=d.target.value;u(f===""?void 0:{field:f,direction:c?.direction??"asc"})},children:[a.jsx("option",{value:"",children:"Par défaut"}),rB.map(d=>a.jsx("option",{value:d,children:n0[d]},d))]})]}),c&&a.jsx(M,{size:"sm",variant:"ghost","aria-label":`sort direction ${c.direction==="asc"?"ascending":"descending"}`,onClick:()=>u({field:c.field,direction:c.direction==="asc"?"desc":"asc"}),children:c.direction==="asc"?"Croissant ↑":"Décroissant ↓"})]}),l&&h&&a.jsx("div",{children:a.jsx(M,{size:"sm",variant:"ghost","aria-label":"clear filters",onClick:l,children:"Effacer"})})]})}function Rv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function Dc(e,t={}){const{initialQuery:n,excludeRefs:r,debounceMs:i=200,refreshOnEvents:s,persistenceKey:l}=t,{ticket:o,system:c,uiPreferences:u}=fe(),h=g.useRef(null);if(h.current===null){const W=l&&u?JS(u.read(l)):{};h.current={statuses:n?.statuses??W.statuses,priorities:n?.priorities??W.priorities,assignedAgentId:n?.assignedAgentId??W.assignedAgentId,text:n?.text??W.text,sort:n?.sort??W.sort}}const d=h.current,[f,p]=g.useState({statuses:d.statuses,priorities:d.priorities,assignedAgentId:d.assignedAgentId}),[m,x]=g.useState(d.text??""),[w,v]=g.useState(m),[_,y]=g.useState(d.sort),[b,C]=g.useState([]),[S,N]=g.useState(void 0),[R,D]=g.useState(!1),[k,L]=g.useState(null),[A,P]=g.useState(0),I=g.useCallback(()=>P(W=>W+1),[]),O=n?.limit,U=(r??[]).join(","),K=g.useMemo(()=>new Set(r??[]),[U]);g.useEffect(()=>{const W=setTimeout(()=>v(m),i);return()=>clearTimeout(W)},[m,i]),g.useEffect(()=>{if(!l||!u)return;const W=w.trim(),Y=XO({...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...W?{text:W}:{},..._?{sort:_}:{}});Y?u.write(l,Y):u.remove(l)},[l,u,f,w,_]);const E=g.useMemo(()=>JSON.stringify({facets:f,text:w.trim(),sort:_,limit:O}),[f,w,_,O]),F=g.useRef(0),j=g.useCallback(W=>{const Y=w.trim();return{...f.statuses&&f.statuses.length>0?{statuses:f.statuses}:{},...f.priorities&&f.priorities.length>0?{priorities:f.priorities}:{},...f.assignedAgentId?{assignedAgentId:f.assignedAgentId}:{},...Y?{text:Y}:{},..._?{sort:_}:{},...O?{limit:O}:{},...W?{cursor:W}:{}}},[f,w,_,O]);g.useEffect(()=>{const W=++F.current;D(!0),L(null),o.list(e,j()).then(Y=>{W===F.current&&(C(Y.items),N(Y.nextCursor))}).catch(Y=>{W===F.current&&(L(Rv(Y)),C([]),N(void 0))}).finally(()=>{W===F.current&&D(!1)})},[E,e,o,A]),g.useEffect(()=>{if(!s||!c)return;let W,Y=!1;return c.onDomainEvent(z=>{(Ip(z)||YS(z))&&P(ce=>ce+1)}).then(z=>{Y?z():W=z}),()=>{Y=!0,W?.()}},[s,c]);const re=g.useCallback(()=>{if(R||!S)return;const W=++F.current;D(!0),L(null),o.list(e,j(S)).then(Y=>{W===F.current&&(C(z=>[...z,...Y.items]),N(Y.nextCursor))}).catch(Y=>{W===F.current&&L(Rv(Y))}).finally(()=>{W===F.current&&D(!1)})},[R,S,o,e,j]),V=g.useCallback(W=>{p(Y=>{const z=Y.statuses??[],ce=z.includes(W)?z.filter(we=>we!==W):[...z,W];return{...Y,statuses:ce.length>0?ce:void 0}})},[]),T=g.useCallback(W=>{p(Y=>{const z=Y.priorities??[],ce=z.includes(W)?z.filter(we=>we!==W):[...z,W];return{...Y,priorities:ce.length>0?ce:void 0}})},[]),ie=g.useCallback(()=>{p(W=>({...W,statuses:void 0,priorities:void 0}))},[]),ee=g.useCallback(async W=>{const Y=await o.read(e,W);return{ref:Y.ref,id:Y.id,number:Y.number,title:Y.title,status:Y.status,priority:Y.priority}},[o,e]);return{rows:g.useMemo(()=>K.size===0?b:b.filter(W=>!K.has(W.ref)),[b,K]),busy:R,error:k,text:m,setText:x,statuses:f.statuses??[],priorities:f.priorities??[],toggleStatus:V,togglePriority:T,clearFacets:ie,sort:_,setSort:y,hasMore:S!==void 0,loadMore:re,refresh:I,resolve:ee}}const Mv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function r0({open:e,projectId:t,title:n="Sélectionner un ticket",confirmLabel:r="Sélectionner",selectionMode:i="single",excludeRefs:s,initialQuery:l,persistFilters:o=!0,onSelect:c,onClose:u}){return e?a.jsx(iB,{projectId:t,title:n,confirmLabel:r,selectionMode:i,excludeRefs:s,initialQuery:l,persistFilters:o,onSelect:c,onClose:u}):null}function iB({projectId:e,title:t,confirmLabel:n,selectionMode:r,excludeRefs:i,initialQuery:s,persistFilters:l,onSelect:o,onClose:c}){const u=Dc(e,{initialQuery:s,excludeRefs:i,persistenceKey:l?KO(e):void 0}),h=g.useRef(null),[d,f]=g.useState(!1),[p,m]=g.useState(null),[x,w]=g.useState(()=>new Set),v=r==="multi";g.useEffect(()=>{const S=document.activeElement,N=h.current;N?.querySelector(Mv)?.focus();function D(k){if(k.key==="Escape"){k.preventDefault(),c();return}if(k.key!=="Tab"||!N)return;const L=Array.from(N.querySelectorAll(Mv)).filter(O=>O.offsetParent!==null||O===document.activeElement);if(L.length===0)return;const A=L[0],P=L[L.length-1],I=document.activeElement;k.shiftKey&&I===A?(k.preventDefault(),P.focus()):!k.shiftKey&&I===P&&(k.preventDefault(),A.focus())}return document.addEventListener("keydown",D),()=>{document.removeEventListener("keydown",D),S?.focus?.()}},[c]);function _(S){return S&&typeof S=="object"&&"message"in S?String(S.message):String(S)}function y(S){w(N=>{const R=new Set(N);return R.has(S)?R.delete(S):R.add(S),R})}async function b(S){if(!d){f(!0),m(null);try{const N=await u.resolve(S);o(N),c()}catch(N){m(_(N)),f(!1)}}}async function C(){if(!(d||x.size===0)){f(!0),m(null);try{const S=await Promise.all(Array.from(x).map(N=>u.resolve(N)));o(S),c()}catch(S){m(_(S)),f(!1)}}}return a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:kn.floatingWindowNested},onMouseDown:S=>{S.target===S.currentTarget&&c()},children:a.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-label":t,className:"flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:t}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"close ticket picker",onClick:c,children:"Close"})]}),a.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:a.jsx(zp,{text:u.text,onTextChange:u.setText,statuses:u.statuses,priorities:u.priorities,onToggleStatus:u.toggleStatus,onTogglePriority:u.togglePriority,onClearFacets:u.clearFacets,sort:u.sort,onSortChange:u.setSort})}),(u.error||p)&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??u.error}),a.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[u.busy&&u.rows.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Loading tickets…"})]}):u.rows.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No matching tickets."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:u.rows.map(S=>{const N=x.has(S.ref);return a.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:a.jsxs("button",{type:"button","aria-label":`select ticket ${S.ref}`,...v?{role:"checkbox","aria-checked":N}:{},disabled:d,onClick:()=>v?y(S.ref):void b(S.ref),className:q("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none","disabled:cursor-not-allowed disabled:opacity-60",v&&N&&"bg-raised"),children:[v&&a.jsx("span",{"aria-hidden":"true",className:q("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",N?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),a.jsx(vs,{ticketRef:S.ref,className:"mt-0.5"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:S.title}),a.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[a.jsx(ia,{status:S.status}),a.jsx(sa,{priority:S.priority})]})]})},S.ref)})}),u.hasMore&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:u.busy,onClick:()=>u.loadMore(),children:"Load more"})})]}),v&&a.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3",children:[a.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[x.size," sélectionné",x.size>1?"s":""]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel ticket selection",onClick:c,children:"Annuler"}),a.jsx(M,{size:"sm","aria-label":"confirm ticket selection",loading:d,disabled:x.size===0||d,onClick:()=>void C(),children:x.size>0?`${n} (${x.size})`:n})]})]})]})})}function sB({projectId:e,vm:t,onClose:n}){const r=Dc(e,{refreshOnEvents:!0}),i=r.rows,s=[...t.sprints].sort((x,w)=>x.order-w.order),[l,o]=g.useState(""),[c,u]=g.useState({}),[h,d]=g.useState(null),[f,p]=g.useState(null);async function m(x){x.preventDefault();const w=l.trim()||`Sprint ${s.length+1}`;await t.createSprint(w)&&o("")}return a.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":"manage sprints",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:"Manage sprints"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:n,children:"Close"})]}),t.error&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-5 py-2 text-sm text-danger",children:t.error}),a.jsxs("div",{className:"flex-1 overflow-auto p-5",children:[a.jsxs("form",{onSubmit:m,className:"mb-5 flex items-center gap-2 rounded-md border border-border bg-raised/50 p-2",children:[a.jsx(oe,{"aria-label":"new sprint name",placeholder:"Sprint name (optional)",value:l,onChange:x=>o(x.target.value),className:"max-w-xs"}),a.jsx(M,{type:"submit",size:"sm",disabled:t.busy,children:"Create sprint"})]}),a.jsx("div",{className:"mb-5",children:a.jsx(zp,{text:r.text,onTextChange:r.setText,statuses:r.statuses,priorities:r.priorities,onToggleStatus:r.toggleStatus,onTogglePriority:r.togglePriority,onClearFacets:r.clearFacets,sort:r.sort,onSortChange:r.setSort})}),r.error&&a.jsx("p",{role:"alert",className:"mb-4 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:r.error}),s.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No sprints yet."}):a.jsx("ul",{className:"flex flex-col gap-4",children:s.map((x,w)=>{const v=i.filter(y=>y.sprintId===x.id),_=c[x.id]??x.name;return a.jsxs("li",{"aria-label":`sprint row ${x.name}`,className:"rounded-md border border-border p-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",x.order]}),a.jsx(oe,{"aria-label":`rename sprint ${x.name}`,value:_,disabled:t.busy,onChange:y=>u(b=>({...b,[x.id]:y.target.value})),className:"max-w-xs"}),a.jsx(M,{size:"sm","aria-label":`save sprint ${x.name}`,disabled:t.busy||_.trim()===""||_.trim()===x.name,onClick:async()=>{await t.renameSprint(x.id,_.trim())&&u(b=>{const{[x.id]:C,...S}=b;return S})},children:"Save"}),a.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} up`,disabled:t.busy||w===0,onClick:()=>void t.moveSprint(x.id,"up"),children:"↑"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`move sprint ${x.name} down`,disabled:t.busy||w===s.length-1,onClick:()=>void t.moveSprint(x.id,"down"),children:"↓"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`delete sprint ${x.name}`,disabled:t.busy,className:"text-danger hover:text-danger",onClick:()=>d({id:x.id,name:x.name}),children:"Delete"})]})]}),a.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[v.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No tickets in this sprint."}):a.jsx("ul",{className:"flex flex-col gap-1",children:v.map(y=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx(vs,{ticketRef:y.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:y.title}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[a.jsx(ia,{status:y.status}),a.jsx(sa,{priority:y.priority})]}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`remove ${y.ref} from sprint`,disabled:t.busy,onClick:()=>void t.assignSprint(y.ref,null),children:"Remove"})]},y.ref))}),a.jsx("div",{className:"mt-1",children:a.jsx(M,{size:"sm",variant:"ghost","aria-label":`add ticket to sprint ${x.name}`,disabled:t.busy,onClick:()=>p({id:x.id,name:x.name}),children:"Ajouter des tickets"})})]})]},x.id)})}),r.hasMore&&a.jsx("div",{className:"mt-4 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:r.busy,onClick:()=>r.loadMore(),children:"Load more tickets"})})]}),h&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"delete sprint confirmation",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsxs("h4",{className:"text-sm font-semibold text-content",children:["Supprimer le sprint « ",h.name," » ?"]}),a.jsx("p",{className:"mt-2 text-sm text-muted",children:"Les tickets de ce sprint ne seront pas supprimés : ils seront simplement désassignés et retourneront au backlog « Sans sprint »."}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete sprint",disabled:t.busy,onClick:()=>d(null),children:"Annuler"}),a.jsx(M,{size:"sm","aria-label":"confirm delete sprint",className:"text-danger hover:text-danger",disabled:t.busy,onClick:async()=>{await t.deleteSprint(h.id),d(null)},children:"Supprimer"})]})]})}),a.jsx(r0,{open:f!==null,projectId:e,title:f?`Ajouter des tickets au sprint « ${f.name} »`:"Ajouter des tickets",confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:i.filter(x=>x.sprintId===f?.id).map(x=>x.ref),onSelect:x=>{const w=Array.isArray(x)?x:[x];if(f)for(const v of w)t.assignSprint(v.ref,f.id)},onClose:()=>p(null)})]})}const Iv='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';function lB({open:e,projectId:t,selectedSprintId:n,title:r="Sélectionner un sprint",onSelect:i,onClose:s}){return e?a.jsx(oB,{projectId:t,selectedSprintId:n??null,title:r,onSelect:i,onClose:s}):null}function aB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function oB({projectId:e,selectedSprintId:t,title:n,onSelect:r,onClose:i}){const{ticket:s}=fe(),l=g.useRef(null),[o,c]=g.useState(null),[u,h]=g.useState(null);g.useEffect(()=>{let p=!1;return h(null),s.listSprints(e).then(m=>{p||c(m)}).catch(m=>{p||(h(aB(m)),c([]))}),()=>{p=!0}},[s,e]),g.useEffect(()=>{const p=document.activeElement,m=l.current;m?.querySelector(Iv)?.focus();function w(v){if(v.key==="Escape"){v.preventDefault(),i();return}if(v.key!=="Tab"||!m)return;const _=Array.from(m.querySelectorAll(Iv)).filter(S=>S.offsetParent!==null||S===document.activeElement);if(_.length===0)return;const y=_[0],b=_[_.length-1],C=document.activeElement;v.shiftKey&&C===y?(v.preventDefault(),b.focus()):!v.shiftKey&&C===b&&(v.preventDefault(),y.focus())}return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w),p?.focus?.()}},[i]);const d=o?[...o].sort((p,m)=>p.order-m.order):[];function f(p){r(p),i()}return a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/55 p-4",style:{zIndex:kn.floatingWindowNested},onMouseDown:p=>{p.target===p.currentTarget&&i()},children:a.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-label":n,className:"flex max-h-[80vh] w-full max-w-sm flex-col overflow-hidden rounded-lg border border-border bg-surface shadow-xl",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:n}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"close sprint picker",onClick:i,children:"Close"})]}),u&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:u}),a.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[a.jsxs("ul",{className:"flex flex-col divide-y divide-border",children:[a.jsx("li",{className:"py-1.5 first:pt-0",children:a.jsx(Ov,{label:"Sans sprint",ariaLabel:"select no sprint",selected:t===null,onClick:()=>f(null)})}),o===null?a.jsxs("li",{className:"flex items-center gap-2 py-2 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Loading sprints…"})]}):d.map(p=>a.jsx("li",{className:"py-1.5 last:pb-0",children:a.jsx(Ov,{label:p.name,ariaLabel:`select sprint ${p.name}`,count:p.ticketCount,selected:t===p.id,onClick:()=>f(p)})},p.id))]}),o!==null&&d.length===0&&!u&&a.jsx("p",{className:"mt-2 text-sm text-muted",children:"No sprints yet."})]})]})})}function Ov({label:e,ariaLabel:t,count:n,selected:r,onClick:i}){return a.jsxs("button",{type:"button",role:"option","aria-selected":r,"aria-label":t,onClick:i,className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none",r&&"bg-raised"),children:[a.jsx("span",{"aria-hidden":"true",className:q("flex h-4 w-4 shrink-0 items-center justify-center text-[10px] font-bold",r?"text-primary":"text-transparent"),children:"✓"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e}),n!==void 0&&a.jsx("span",{className:"shrink-0 rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:n})]})}const Zh=q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function cB({projectId:e,onOpen:t}){const n=Op(e),{agents:r,nameOf:i,loaded:s}=ZS(e);g.useEffect(()=>{if(!s)return;const N=n.query.assignedAgentId;if(N&&!r.some(R=>R.id===N)){const{assignedAgentId:R,...D}=n.query;n.setQuery(D)}},[s,r,n.query,n.setQuery]);const[l,o]=g.useState(!1),[c,u]=g.useState(!1),[h,d]=g.useState(""),[f,p]=g.useState("medium"),[m,x]=g.useState(null),[w,v]=g.useState(!1),_=n.list?.items??[],y=new Set(n.sprints.map(N=>N.id)),b=n.sprints.map(N=>({sprint:N,tickets:_.filter(R=>R.sprintId===N.id)})).filter(N=>N.tickets.length>0),C=_.filter(N=>!N.sprintId||!y.has(N.sprintId));async function S(N){if(N.preventDefault(),!h.trim())return;const R=await n.create({title:h.trim(),priority:f});R&&(m&&await n.assignSprint(R.ref,m.id),d(""),p("medium"),x(null),o(!1),t(R.ref))}return a.jsxs(Se,{title:"Tickets",actions:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>o(N=>!N),children:l?"Cancel":"New"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"manage sprints",onClick:()=>u(!0),children:"Sprints"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),loading:n.busy,children:"Refresh"})]}),children:[n.error&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),l&&a.jsxs("form",{onSubmit:S,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[a.jsx(oe,{"aria-label":"new ticket title",placeholder:"Ticket title",value:h,onChange:N=>d(N.target.value)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("select",{"aria-label":"new ticket priority",className:Zh,value:f,onChange:N=>p(N.target.value),children:js.map(N=>a.jsx("option",{value:N,children:Lc(N)},N))}),a.jsx(M,{type:"submit",size:"sm",disabled:!h.trim()||n.busy,children:"Create"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-muted",children:"Sprint"}),a.jsx(M,{type:"button",size:"sm",variant:"ghost","aria-label":"choose sprint for new ticket",disabled:n.busy,onClick:()=>v(!0),className:"border border-border",children:m?m.name:"Sans sprint"})]})]}),a.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[a.jsx(zp,{text:n.query.text??"",onTextChange:N=>n.setQuery({...n.query,text:N||void 0}),statuses:n.query.statuses??[],priorities:n.query.priorities??[],onToggleStatus:n.toggleStatus,onTogglePriority:n.togglePriority,onClearFacets:n.clearFacets,sort:n.query.sort,onSortChange:N=>{const{sort:R,...D}=n.query;n.setQuery(N?{...D,sort:N}:D)}}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:a.jsxs("select",{"aria-label":"filter by assignee",className:Zh,value:n.query.assignedAgentId??"",onChange:N=>n.setQuery({...n.query,assignedAgentId:N.target.value||void 0}),children:[a.jsx("option",{value:"",children:"All assignees"}),r.map(N=>a.jsx("option",{value:N.id,children:N.name},N.id))]})})]}),n.busy&&n.list===null?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Loading tickets…"})]}):_.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No tickets."}):a.jsxs("div",{className:"flex flex-col gap-4",children:[b.map(N=>a.jsx(Bv,{heading:N.sprint.name,count:N.tickets.length,tickets:N.tickets,sprints:n.sprints,onOpen:t,nameOf:i,onAssignSprint:n.assignSprint},N.sprint.id)),C.length>0&&a.jsx(Bv,{heading:"Sans sprint",count:C.length,tickets:C,sprints:n.sprints,onOpen:t,nameOf:i,onAssignSprint:n.assignSprint})]}),n.list?.nextCursor&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Load more"})}),c&&a.jsx(sB,{projectId:e,vm:n,onClose:()=>u(!1)}),a.jsx(lB,{open:w,projectId:e,selectedSprintId:m?.id??null,title:"Sprint du nouveau ticket",onSelect:N=>x(N),onClose:()=>v(!1)})]})}function Bv({heading:e,count:t,tickets:n,sprints:r,onOpen:i,nameOf:s,onAssignSprint:l}){return a.jsxs("section",{"aria-label":`sprint section ${e}`,children:[a.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,a.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t})]}),a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:n.map(o=>a.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(vs,{ticketRef:o.ref,onOpen:i,className:"mt-0.5"}),a.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>i(o.ref),children:[a.jsx("span",{className:"block truncate text-sm font-medium text-content hover:underline",children:o.title}),o.assignedAgentIds.length>0&&a.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted",children:o.assignedAgentIds.map(s).join(", ")})]}),a.jsxs("span",{className:"flex shrink-0 flex-col items-end gap-1",children:[a.jsx(ia,{status:o.status}),a.jsx(sa,{priority:o.priority})]})]}),a.jsx("div",{className:"mt-1 pl-6",children:a.jsxs("select",{"aria-label":`sprint for ${o.ref}`,className:Zh,value:o.sprintId??"",onChange:c=>l(o.ref,c.target.value||null),children:[a.jsx("option",{value:"",children:"— No sprint —"}),r.map(c=>a.jsx("option",{value:c.id,children:c.name},c.id))]})})]},o.ref))})]})}function Ha(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function uB(e){return!!e&&typeof e=="object"&&typeof e.message=="string"&&e.message.includes("version conflict")}function i0(e,t){const{ticket:n,system:r}=fe(),[i,s]=g.useState(null),[l,o]=g.useState(null),[c,u]=g.useState(!1),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(0),w=g.useCallback(async()=>{p(!0),o(null);try{s(await n.read(e,t,!0)),u(!1),x(D=>D+1)}catch(D){o(Ha(D))}finally{p(!1)}},[e,t,n]);g.useEffect(()=>{w()},[w]),g.useEffect(()=>{if(!r)return;let D,k=!1;return r.onDomainEvent(L=>{if(L.type==="issueDeleted"&&L.issueRef===t){d(!0);return}Ip(L)&&L.issueRef===t&&w()}).then(L=>{k?L():D=L}),()=>{k=!0,D?.()}},[w,r,t]);const v=g.useCallback(async(D,k)=>{if(!i)return!1;p(!0),o(null);try{const L=await D(i.version);return s({...L,carnet:k!==void 0?k:i.carnet}),u(!1),!0}catch(L){if(uB(L)){o("This ticket was modified elsewhere. It has been reloaded — re-apply your change.");try{s(await n.read(e,t,!0))}catch(A){o(Ha(A))}u(!0),x(A=>A+1)}else o(Ha(L));return!1}finally{p(!1)}},[i,n,e,t]),_=g.useCallback(D=>v(k=>n.update(e,t,{...D,expectedVersion:k})),[v,n,e,t]),y=g.useCallback(D=>v(k=>n.updateCarnet(e,t,D,k),D),[v,n,e,t]),b=g.useCallback((D,k)=>v(L=>n.link(e,t,D,k,L)),[v,n,e,t]),C=g.useCallback((D,k)=>v(L=>n.unlink(e,t,D,L,k)),[v,n,e,t]),S=g.useCallback((D,k)=>v(L=>n.assign(e,t,D,k,L)),[v,n,e,t]),N=g.useCallback(D=>v(k=>n.setTicketSprint(e,t,D,k)),[v,n,e,t]),R=g.useCallback(async()=>{p(!0),o(null);try{return await n.delete(e,t),!0}catch(D){return o(Ha(D)),!1}finally{p(!1)}},[n,e,t]);return{ticket:i,error:l,conflict:c,deleted:h,busy:f,reloadCount:m,refresh:w,updateFields:_,saveCarnet:y,link:b,unlink:C,assign:S,setSprint:N,remove:R}}function Ua(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function dB(e,t){const{ticket:n,profile:r}=fe(),[i,s]=g.useState([]),[l,o]=g.useState(null),[c,u]=g.useState([]),[h,d]=g.useState(!1),[f,p]=g.useState(!1),[m,x]=g.useState(null),w=g.useRef(null);w.current=l,g.useEffect(()=>{let b=!1;return(async()=>{try{const C=await r?.listProfiles()??[];b||s(C)}catch(C){b||x(Ua(C))}})(),()=>{b=!0}},[r]);const v=g.useCallback(async b=>{if(b){d(!0),x(null);try{const C=await n.openTicketChat(e,t,b);o(C.sessionId),u([])}catch(C){x(Ua(C))}finally{d(!1)}}},[n,e,t]),_=g.useCallback(async()=>{if(w.current){o(null),u([]);try{await n.closeTicketChat(e,t)}catch(b){x(Ua(b))}}},[n,e,t]),y=g.useCallback(async b=>{const C=b.trim();if(!l||!C||f)return;x(null),p(!0),u(N=>[...N,{role:"user",text:C},{role:"assistant",text:"",pending:!0}]);const S=N=>{u(R=>{const D=[...R],k=D.length-1;return k<0||D[k].role!=="assistant"?R:(N.kind==="textDelta"?D[k]={...D[k],text:D[k].text+N.text}:N.kind==="toolActivity"?D[k]={...D[k],text:`${D[k].text} -· ${N.label}`}:N.kind==="error"?D[k]={role:"assistant",text:`⚠️ ${N.message}`,pending:!1}:D[k]={role:"assistant",text:N.content,pending:!1},D)}),(N.kind==="final"||N.kind==="error")&&p(!1)};try{await n.sendTicketChat(l,C,S)}catch(N){x(Ua(N)),u(R=>{const D=[...R],k=D.length-1;return k>=0&&D[k].role==="assistant"&&D[k].pending&&(D[k]={...D[k],pending:!1}),D}),p(!1)}},[n,l,f]);return g.useEffect(()=>()=>{w.current&&n.closeTicketChat(e,t).catch(()=>{})},[n,e,t]),{profiles:i,sessionId:l,turns:c,opening:h,busy:f,error:m,open:v,close:_,send:y}}const hB=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function fB({projectId:e,ticketRef:t}){const n=dB(e,t),[r,i]=g.useState(""),[s,l]=g.useState(""),o=g.useRef(null);g.useEffect(()=>{const h=o.current;h&&(h.scrollTop=h.scrollHeight)},[n.turns]);const c=n.sessionId!==null;function u(){const h=s.trim();!h||n.busy||(n.send(h),l(""))}return a.jsxs("div",{className:"flex flex-col gap-3",children:[c?a.jsxs("div",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-xs text-muted",children:"Conversation ouverte — l'assistant peut lire le projet et éditer ce ticket."}),a.jsx(M,{size:"sm",variant:"ghost",disabled:n.busy,onClick:()=>void n.close(),children:"Fermer la conversation"})]}),a.jsx("div",{ref:o,className:"flex max-h-96 min-h-32 flex-col gap-2 overflow-auto rounded-md border border-border bg-raised/40 p-3",children:n.turns.length===0?a.jsx("p",{className:"m-auto text-xs text-muted",children:"Démarrez la conversation en décrivant ce que l'assistant doit faire sur ce ticket."}):n.turns.map((h,d)=>a.jsx("div",{className:q("flex",h.role==="user"?"justify-end":"justify-start"),children:a.jsxs("div",{className:q("max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm",h.role==="user"?"bg-primary/15 text-content":"bg-surface text-content"),children:[h.text,h.pending&&a.jsx("span",{className:"ml-1 inline-flex items-center align-middle text-muted",children:a.jsx(Me,{size:12})})]})},d))}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsx("textarea",{"aria-label":"message à l'assistant",className:q("min-h-10 flex-1 resize-none rounded-md bg-raised p-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),rows:2,placeholder:"Votre message…",value:s,disabled:n.busy,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),u())}}),a.jsx(M,{size:"sm",disabled:!s.trim()||n.busy,loading:n.busy,onClick:u,children:"Envoyer"})]})]}):a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("select",{"aria-label":"profil de l'assistant",className:hB,value:r,disabled:n.opening||n.profiles.length===0,onChange:h=>i(h.target.value),children:[a.jsx("option",{value:"",children:n.profiles.length===0?"Aucun profil disponible":"Choisir un profil IA…"}),n.profiles.map(h=>a.jsx("option",{value:h.id,children:h.name},h.id))]}),a.jsx(M,{size:"sm",disabled:!r||n.opening,loading:n.opening,onClick:()=>void n.open(r),children:"Ouvrir la conversation"})]}),n.error&&a.jsx("p",{role:"alert",className:"text-xs text-danger",children:n.error})]})}const qa=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),zv=q("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");async function pB(e){return typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):!1}function Zs({title:e,hint:t,children:n}){return a.jsxs("section",{className:"flex flex-col gap-2 border-b border-border px-5 py-4",children:[a.jsxs("div",{children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:e}),t&&a.jsx("p",{className:"mt-0.5 text-xs text-muted",children:t})]}),n]})}function mB({projectId:e,ticketRef:t,onClose:n,onOpenRef:r}){const i=i0(e,t),{agents:s,nameOf:l}=ZS(e),o=i.ticket,[c,u]=g.useState(""),[h,d]=g.useState(""),[f,p]=g.useState(""),[m,x]=g.useState("relatesTo"),[w,v]=g.useState(""),[_,y]=g.useState(!1),[b,C]=g.useState(!1),[S,N]=g.useState(!1),[R,D]=g.useState(!1),[k,L]=g.useState(!1);g.useEffect(()=>{i.deleted&&n()},[i.deleted,n]);const A=i.reloadCount,P=g.useRef(-1),I=g.useRef(null);g.useEffect(()=>{if(!o||P.current===A)return;P.current=A;const V=o.carnet??"",T=I.current;T===null||i.conflict?(u(o.title),d(o.description),p(V)):(u(ee=>ee===T.title?o.title:ee),d(ee=>ee===T.description?o.description:ee),p(ee=>ee===T.carnet?V:ee)),I.current={title:o.title,description:o.description,carnet:V}},[o,A,i.conflict]);const O=!!o&&(c!==o.title||h!==o.description),U=!!o&&f!==(o.carnet??""),K=O||U,E=s.filter(V=>!o?.assignedAgentIds.includes(V.id));function F(){K?C(!0):n()}async function j(){let V=!0;O&&(V=await i.updateFields({title:c,description:h})&&V),V&&U&&(V=await i.saveCarnet(f)&&V),C(!1),V&&n()}async function re(){if(!o)return;await pB(`Travaille sur le ticket ${o.ref} : ${o.title}`)&&(y(!0),window.setTimeout(()=>y(!1),1200))}return a.jsxs(Bh,{open:!0,title:`ticket ${t}`,size:"xl",onClose:F,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(vs,{ticketRef:t}),o&&a.jsx(ia,{status:o.status}),o&&a.jsx(sa,{priority:o.priority}),a.jsx("span",{className:"truncate text-sm font-medium text-content",children:o?.title??t})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:!o,onClick:()=>void re(),title:"Copy a delegation prompt to hand this ticket to an agent",children:_?"Copied":"Delegation context"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!o||i.busy,onClick:()=>N(!0),className:"text-danger hover:text-danger",title:"Supprimer définitivement ce ticket",children:"Supprimer"})]})]}),i.conflict&&a.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-1 py-2 text-sm text-warning",children:"This ticket was modified elsewhere and reloaded. Re-apply your change."}),i.error&&!i.conflict&&a.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-1 py-2 text-sm text-danger",children:i.error}),i.busy&&!o?a.jsxs("div",{className:"flex items-center gap-2 py-5 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Loading ticket…"})]}):o?a.jsxs("div",{className:"-mx-4",children:[a.jsxs(Zs,{title:"Details",children:[a.jsx("label",{className:"text-xs font-medium text-muted",htmlFor:"td-title",children:"Title"}),a.jsx(oe,{id:"td-title",value:c,onChange:V=>u(V.target.value),disabled:i.busy}),a.jsx("label",{className:"mt-2 text-xs font-medium text-muted",htmlFor:"td-desc",children:"Description"}),a.jsx("textarea",{id:"td-desc",className:q(zv,"min-h-24"),value:h,onChange:V=>d(V.target.value),disabled:i.busy}),h.trim()&&a.jsx("p",{className:"whitespace-pre-wrap break-words rounded-md bg-raised/40 px-3 py-2 text-xs text-muted",children:tB(h,r)}),a.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[a.jsx(M,{size:"sm",disabled:!O||i.busy,loading:i.busy&&O,onClick:()=>void i.updateFields({title:c,description:h}),children:"Save changes"}),O&&a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:()=>{u(o.title),d(o.description)},children:"Reset"})]})]}),a.jsx(Zs,{title:"Status & priority",children:a.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[a.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Status",a.jsx("select",{"aria-label":"ticket status",className:qa,value:o.status,disabled:i.busy,onChange:V=>void i.updateFields({status:V.target.value}),children:Tc.map(V=>a.jsx("option",{value:V,children:Bp(V)},V))})]}),a.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted",children:["Priority",a.jsx("select",{"aria-label":"ticket priority",className:qa,value:o.priority,disabled:i.busy,onChange:V=>void i.updateFields({priority:V.target.value}),children:js.map(V=>a.jsx("option",{value:V,children:Lc(V)},V))})]})]})}),a.jsxs(Zs,{title:"Carnet",hint:"Markdown notebook scoped to this ticket only — separate from project memory. Saving replaces the whole carnet.",children:[a.jsx("textarea",{"aria-label":"ticket carnet",className:q(zv,"min-h-40 font-mono"),value:f,onChange:V=>p(V.target.value),disabled:i.busy}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(M,{size:"sm",disabled:!U||i.busy,loading:i.busy&&U,onClick:()=>void i.saveCarnet(f),children:"Save carnet"}),U&&a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:()=>p(o.carnet??""),children:"Reset"})]})]}),a.jsxs(Zs,{title:"Linked tickets",children:[o.links.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No linked tickets."}):a.jsx("ul",{className:"flex flex-col gap-1",children:o.links.map(V=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-xs text-muted",children:Dv(V.kind)}),a.jsx(vs,{ticketRef:V.targetRef,onOpen:r}),a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:()=>void i.unlink(V.targetRef,V.kind),children:"Remove"})]},`${V.kind}-${V.targetRef}`))}),a.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[a.jsx("select",{"aria-label":"link kind",className:qa,value:m,disabled:i.busy,onChange:V=>x(V.target.value),children:e0.map(V=>a.jsx("option",{value:V,children:Dv(V)},V))}),a.jsx(M,{size:"sm","aria-label":"add link",disabled:i.busy,onClick:()=>D(!0),children:"Add link"})]})]}),a.jsxs(Zs,{title:"Assigned agents",hint:"Only agents known to this project can be assigned.",children:[o.assignedAgentIds.length===0?a.jsx("p",{className:"text-xs text-muted",children:"No agents assigned."}):a.jsx("ul",{className:"flex flex-wrap gap-2",children:o.assignedAgentIds.map(V=>a.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[l(V),a.jsx("button",{type:"button","aria-label":`unassign ${l(V)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:i.busy,onClick:()=>void i.assign(V,!1),children:"×"})]},V))}),a.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[a.jsxs("select",{"aria-label":"assign agent",className:qa,value:w,disabled:i.busy||E.length===0,onChange:V=>v(V.target.value),children:[a.jsx("option",{value:"",children:E.length===0?"No more agents":"Select an agent…"}),E.map(V=>a.jsx("option",{value:V.id,children:V.name},V.id))]}),a.jsx(M,{size:"sm",disabled:!w||i.busy,onClick:async()=>{await i.assign(w,!0)&&v("")},children:"Assign"})]})]}),a.jsx(r0,{open:R,projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...o.links.map(V=>V.targetRef)],onSelect:V=>{const T=Array.isArray(V)?V[0]:V;T&&i.link(T.ref,m),D(!1)},onClose:()=>D(!1)})]}):a.jsx("div",{className:"flex items-center justify-center py-10 text-sm text-muted",children:"Ticket not found."}),o&&a.jsx("div",{className:"pointer-events-none sticky bottom-0 z-10 -mx-4 -mb-4 flex justify-end px-4 pb-4 pt-2",children:a.jsx(M,{"aria-label":"ouvrir l'assistant IA",className:"pointer-events-auto shadow-lg",onClick:()=>L(!0),children:"🤖 Assistant IA"})}),a.jsx(Bh,{open:k,title:`Assistant IA — ${t}`,size:"lg",onClose:()=>L(!1),children:a.jsx(fB,{projectId:e,ticketRef:t})}),b&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"unsaved changes",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsx("h4",{className:"text-sm font-semibold text-content",children:"Modifications non sauvegardées"}),a.jsx("p",{className:"mt-2 text-sm text-muted",children:"Vous avez des modifications non sauvegardées. Voulez-vous les sauvegarder avant de fermer ?"}),a.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel close",disabled:i.busy,onClick:()=>C(!1),children:"Annuler"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":"close without saving",disabled:i.busy,onClick:n,className:"text-danger hover:text-danger",children:"Fermer sans sauvegarder"}),a.jsx(M,{size:"sm","aria-label":"save and close",loading:i.busy,disabled:i.busy,onClick:()=>void j(),children:"Sauvegarder"})]})]})}),S&&a.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"confirmer la suppression",className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/55 p-4",children:a.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl",children:[a.jsx("h4",{className:"text-sm font-semibold text-content",children:"Supprimer le ticket"}),a.jsxs("p",{className:"mt-2 text-sm text-muted",children:["Supprimer définitivement le ticket ",t," ? Cette action est irréversible."]}),a.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost","aria-label":"cancel delete",disabled:i.busy,onClick:()=>N(!1),children:"Annuler"}),a.jsx(M,{size:"sm",variant:"danger","aria-label":"confirm delete",loading:i.busy,disabled:i.busy,onClick:async()=>{await i.remove()&&N(!1)},children:"Supprimer"})]})]})})]})}function gB({projectId:e}){const[t,n]=g.useState(null);return a.jsxs(a.Fragment,{children:[a.jsx(cB,{projectId:e,onOpen:n}),t&&a.jsx(mB,{projectId:e,ticketRef:t,onClose:()=>n(null),onOpenRef:n},`${e}-${t}`)]})}function Fv(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function s0({projectId:e}){const{project:t}=fe(),[n,r]=g.useState(""),[i,s]=g.useState(""),[l,o]=g.useState(!1),[c,u]=g.useState(null);g.useEffect(()=>{let f=!1;return o(!0),u(null),t.readProjectContext(e).then(p=>{f||(r(p),s(p))}).catch(p=>{f||u(Fv(p))}).finally(()=>{f||o(!1)}),()=>{f=!0}},[t,e]);async function h(){o(!0),u(null);try{await t.updateProjectContext(e,n),s(n)}catch(f){u(Fv(f))}finally{o(!1)}}const d=n!==i;return a.jsxs(Se,{title:"Project Context",className:"flex flex-col gap-0",children:[c&&a.jsx("p",{role:"alert",className:"mx-4 mt-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:c}),a.jsx("div",{className:"border-b border-border px-4 py-2",children:a.jsx("code",{className:"text-xs text-muted",children:".ideai/CONTEXT.md"})}),a.jsxs("div",{className:"flex flex-col gap-3 p-4",children:[a.jsx("textarea",{"aria-label":"project context",value:n,onChange:f=>r(f.target.value),rows:18,className:q("w-full rounded-md bg-raised px-3 py-2 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary placeholder:text-faint","disabled:cursor-not-allowed disabled:opacity-50 resize-y font-mono"),disabled:l}),a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l&&a.jsx(Me,{size:14}),a.jsx(M,{variant:"primary",disabled:l||!d,onClick:()=>void h(),children:"Save"})]})]})]})}function l0({panel:e,projectId:t,projectRoot:n,onOpenConversation:r}){switch(e){case"context":return a.jsx(s0,{projectId:t});case"work":return a.jsx(nT,{projectId:t,onOpenConversation:r});case"tickets":return a.jsx(gB,{projectId:t});case"agents":return a.jsx(xw,{projectId:t,projectRoot:n});case"templates":return a.jsx(zS,{projectId:t});case"skills":return a.jsx(FS,{projectId:t});case"permissions":return a.jsx(GS,{projectId:t});case"memory":return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx(qS,{projectId:t}),a.jsx(US,{})]});case"git":return a.jsx(Tw,{projectId:t})}}const Hn={projects:"Projects",context:"Project context",work:"Work state",tickets:"Tickets",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Memory",git:"Git"};function Tr(e,t){return e[t]??"closed"}function li(e,t){return typeof e=="object"&&e.dock===t}function $v(e,t){return Object.keys(Hn).filter(n=>li(Tr(e,n),t))}function xB(e){return Object.keys(Hn).filter(t=>Tr(e,t)==="floating")}function td(e){return e==="detached"}function vB(e){return e!=="projects"&&e in Hn}function _B(e,t){let n=!1;const r={...e};for(const i of t){if(!i.visible||!vB(i.panel))continue;const s=i.panel;Tr(e,s)==="closed"&&(r[s]="detached",n=!0)}return n?r:e}const yB={projects:"md",context:"lg",work:"lg",tickets:"lg",agents:"lg",templates:"lg",skills:"lg",permissions:"md",memory:"lg",git:"lg"};function bB(e){return e.type==="backgroundTaskChanged"&&(e.state==="completed"||e.state==="failed"||e.state==="cancelled"||e.state==="delivered")}function wB(){const e=kL(),{system:t,window:n,focusedProject:r,git:i}=fe(),[s,l]=g.useState(""),[o,c]=g.useState(""),[u,h]=g.useState({}),[d,f]=g.useState(340),[p,m]=g.useState(340),[x,w]=g.useState(null),[v,_]=g.useState(null),[y,b]=g.useState(null),[C,S]=g.useState([]),N=e.openTabs.find(B=>B.id===e.activeTabId)??null,[R,D]=g.useState(!1);g.useEffect(()=>{if(!N){D(!1);return}let B=!1;return i.branches(N.id).then(()=>{B||D(!0)}).catch(()=>{B||D(!1)}),()=>{B=!0}},[i,N?.id]);const{registry:k}=pp(),A=pA(k,{projectOpen:N!==null,gitRepository:R,agentSelected:!1,terminalFocused:!1,layoutCellFocused:!1});g.useEffect(()=>{_(null),b(null)},[N?.id]),g.useEffect(()=>{r?.setFocusedProject(N?{id:N.id,name:N.name,root:N.root}:null)},[r,N?.id,N?.name,N?.root]),g.useEffect(()=>{let B,de=!1;return t.onDomainEvent(he=>{if(!bB(he))return;const Ne={id:`${he.taskId}-${he.state}-${Date.now()}`,projectId:he.projectId,agentId:he.agentId,taskId:he.taskId,state:he.state};S(_t=>[..._t.slice(-2),Ne]),window.setTimeout(()=>{S(_t=>_t.filter(Xr=>Xr.id!==Ne.id))},7e3)}).then(he=>{de?he():B=he}),()=>{de=!0,B?.()}},[t]);const P=v?.kind??"terminal",I=s.trim().length>0&&o.trim().length>0&&!e.busy;async function O(B){B.preventDefault(),I&&(await e.createProject(s.trim(),o.trim()),l(""),c(""))}async function U(){const B=await t.pickFolder();B!==null&&c(B)}function K(B,de){h(he=>{const Ne={...he};if(de==="floating")for(const _t of Object.keys(Ne))_t!==B&&Ne[_t]==="floating"&&delete Ne[_t];return Ne[B]=de,Ne})}function E(B){h(de=>{if(!(B in de))return de;const he={...de};return delete he[B],he})}function F(){h(B=>{let de=!1;const he={...B};for(const Ne of Object.keys(he))he[Ne]==="floating"&&(delete he[Ne],de=!0);return de?he:B})}function j(B){N&&n.openViewWindow(B).then(()=>K(B,"detached")).catch(()=>{})}g.useEffect(()=>{let B,de=!1;return n.onViewWindowClosed(({panel:he})=>{h(Ne=>Ne[he]==="detached"?(()=>{const _t={...Ne};return delete _t[he],_t})():Ne)}).then(he=>{de?he():B=he}),()=>{de=!0,B?.()}},[n]),g.useEffect(()=>{let B=!1;return n.listOpenViewWindows().then(de=>{B||h(he=>_B(he,de))}).catch(()=>{}),()=>{B=!0}},[n]);function re(B){b(B),F()}const V=["context","work","tickets","agents","templates","skills","permissions","memory","git","projects"];function T(B){const de=Tr(u,B),he=[{id:"closed",label:"Fermé",active:de==="closed",onSelect:()=>E(B)},{id:"floating",label:"Flottant",active:de==="floating",onSelect:()=>K(B,"floating")},{id:"dock-left",label:"Ancré à gauche",active:li(de,"left"),onSelect:()=>K(B,{dock:"left"})},{id:"dock-right",label:"Ancré à droite",active:li(de,"right"),onSelect:()=>K(B,{dock:"right"})}];return B!=="projects"&&he.push({id:"detached",label:"Fenêtre détachée",active:td(de),disabled:!N,onSelect:()=>j(B)}),he}const ie=[{id:"panels",label:"Panneaux",items:[...V.map(B=>({id:B,label:Hn[B],active:Tr(u,B)!=="closed",onSelect:()=>{},submenu:T(B)})),...A.itemsFor("panels")]},...A.topLevelMenus,{id:"settings",label:"Paramètres",items:[...Pw.map(B=>({id:B,label:Ew[B],active:x===B,onSelect:()=>{w(B),F()}})),...A.itemsFor("settings")]}],ee=a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("form",{onSubmit:O,className:"flex flex-col gap-2",children:[a.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-faint",children:"New project"}),a.jsx(oe,{"aria-label":"project name",placeholder:"Project name",value:s,onChange:B=>l(B.target.value)}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(oe,{"aria-label":"project root",placeholder:"/absolute/project/root",value:o,onChange:B=>c(B.target.value),className:"flex-1"}),a.jsx(M,{type:"button","aria-label":"browse project folder",onClick:()=>void U(),disabled:e.busy,children:"Browse…"})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(M,{type:"submit",variant:"primary",disabled:!I,className:"flex-1",children:"Create project"}),a.jsx(M,{type:"button",onClick:()=>void e.refresh(),disabled:e.busy,children:"Refresh"})]})]}),a.jsx(Se,{title:"Known projects",children:e.projects.length===0?a.jsx("p",{className:"text-sm text-muted",children:"No projects yet."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:e.projects.map(B=>a.jsxs("li",{className:"flex items-center justify-between gap-2 py-2 first:pt-0 last:pb-0",children:[a.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[a.jsx("span",{className:"font-medium text-content",children:B.name}),a.jsx("code",{className:"truncate text-xs text-muted",children:B.root})]}),a.jsx(M,{size:"sm",onClick:()=>void e.openProject(B.id),children:"Open"})]},B.id))})})]});function J(B){return B==="projects"?ee:N?a.jsx(l0,{panel:B,projectId:N.id,projectRoot:N.root,onOpenConversation:re}):a.jsx("p",{className:"text-sm text-muted",children:"Open a project to use this panel."})}const W=!N&&Tr(u,"projects")==="closed",Y=$v(u,"left"),z=$v(u,"right"),ce=xB(u);function we({panel:B}){const de=Tr(u,B),he=Hn[B],Ne="bg-raised text-content ring-1 ring-border-strong";return a.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[a.jsx(ir,{size:"sm",title:"Ancré à gauche","aria-label":`Ancré à gauche — ${he}`,"aria-pressed":li(de,"left"),className:q(li(de,"left")&&Ne),onClick:()=>K(B,{dock:"left"}),children:"⇤"}),a.jsx(ir,{size:"sm",title:"Ancré à droite","aria-label":`Ancré à droite — ${he}`,"aria-pressed":li(de,"right"),className:q(li(de,"right")&&Ne),onClick:()=>K(B,{dock:"right"}),children:"⇥"}),a.jsx(ir,{size:"sm",title:"Flottant","aria-label":`Flottant — ${he}`,"aria-pressed":de==="floating",className:q(de==="floating"&&Ne),onClick:()=>K(B,"floating"),children:"□"}),B!=="projects"&&a.jsx(ir,{size:"sm",title:"Fenêtre détachée","aria-label":`Fenêtre détachée — ${he}`,"aria-pressed":td(de),disabled:!N,className:q(td(de)&&Ne),onClick:()=>j(B),children:"↗"}),a.jsx(ir,{size:"sm",title:"Fermé","aria-label":`Fermé — ${he}`,onClick:()=>E(B),children:"×"})]})}function Pe(B){return a.jsxs("section",{"aria-label":`${Hn[B]} panel`,className:"flex min-h-0 flex-1 flex-col border-b border-border last:border-b-0",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2",children:[a.jsx("span",{className:"truncate text-sm font-medium text-content",children:Hn[B]}),a.jsx(we,{panel:B})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3",children:J(B)})]},B)}return a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.error&&a.jsx("p",{role:"alert",className:"mx-4 mt-2 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:e.error}),a.jsx(CL,{items:e.openTabs.map(B=>({id:B.id,label:B.name})),activeTabId:e.activeTabId,onSelect:B=>e.activateTab(B),onClose:B=>void e.closeTab(B),projectsPanelOpen:Tr(u,"projects")!=="closed",onOpenProjectsPanel:()=>{w(null),K("projects","floating")}}),a.jsx(UP,{menus:ie}),a.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[Y.length>0&&a.jsx(cx,{side:"left",width:d,onResize:f,"aria-label":"left dock",children:Y.map(Pe)}),a.jsx("main",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:x?a.jsx(fL,{section:x,onSectionChange:w,onClose:()=>w(null)}):N&&y?a.jsx(aT,{projectId:N.id,conversationId:y,onClose:()=>b(null)},`${N.id}-${y}`):N?a.jsxs(a.Fragment,{children:[a.jsx(FA,{projectId:N.id,onActiveLayoutChange:_}),P==="gitGraph"?a.jsx(SL,{projectId:N.id},`${N.id}-${v?.id??"default"}-graph`):a.jsx(DA,{projectId:N.id,cwd:N.root,layoutId:v?.id,onOpenConversation:re,onOpenPluginsSettings:()=>{w("plugins"),F()}},`${N.id}-${v?.id??"default"}`)]}):a.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:a.jsx("div",{className:"w-full max-w-xl",children:W?ee:a.jsx("p",{className:"text-sm text-muted",children:"Select or create a project to get started."})})})}),z.length>0&&a.jsx(cx,{side:"right",width:p,onResize:m,"aria-label":"right dock",children:z.map(Pe)})]}),ce.map(B=>a.jsxs(Bh,{open:!0,title:Hn[B],size:yB[B],onClose:()=>E(B),children:[a.jsx("div",{className:"mb-3 flex justify-end border-b border-border pb-3",children:a.jsx(we,{panel:B})}),J(B)]},B)),C.length>0&&a.jsx("div",{className:"fixed bottom-4 right-4 flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2",style:{zIndex:kn.toast},children:C.map(B=>a.jsxs("button",{type:"button",className:"rounded-md border border-border bg-surface px-3 py-2 text-left shadow-lg hover:border-border-strong",onClick:()=>{e.openTabs.some(he=>he.id===B.projectId)&&e.activateTab(B.projectId),w(null),b(null),K("work","floating"),S(he=>he.filter(Ne=>Ne.id!==B.id))},children:[a.jsxs("span",{className:"block text-sm font-medium text-content",children:["Background task ",B.state]}),a.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted",children:[B.agentId.slice(0,8)," · ",B.taskId.slice(0,8)]})]},B.id))})]})}const SB=5;function kB(e){if(e.totalWorkCount===1)return"1 travail actif sera interrompu si vous quittez IdeA maintenant.";const t=[];return e.busyAgentCount>0&&t.push(e.busyAgentCount===1?"1 agent travaille encore":`${e.busyAgentCount} agents travaillent encore`),e.activeBackgroundTaskCount>0&&t.push(e.activeBackgroundTaskCount===1?"1 tâche de fond est encore active":`${e.activeBackgroundTaskCount} tâches de fond sont encore actives`),`${t.join(" et ")}. Ces travaux seront interrompus si vous quittez IdeA maintenant.`}function CB(e){return e.kind==="busyAgent"?`Agent ${e.agentName} — ${e.projectName}`:`Tâche de fond ${e.taskId.slice(0,8)} — ${e.projectName}`}function jB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const Wv="app-exit-confirm-title",Hv="app-exit-confirm-desc";function NB(){const{system:e}=fe(),[t,n]=g.useState(null),[r,i]=g.useState(!1),[s,l]=g.useState(null),o=g.useRef(null),c=g.useRef(null);g.useEffect(()=>{let p=!1,m;return e.onAppExitWorkGuard(x=>{n(x)}).then(x=>{p?x():m=x}).catch(()=>{}),()=>{p=!0,m?.()}},[e]),g.useEffect(()=>{t&&o.current?.focus()},[t!=null]);function u(){r||(n(null),l(null))}async function h(){i(!0),l(null);try{await e.confirmAppExit()}catch(p){l(jB(p))}finally{i(!1)}}if(g.useEffect(()=>{if(!t)return;function p(m){if(m.key==="Escape"){m.preventDefault(),u();return}if(m.key!=="Tab")return;const x=c.current?.querySelectorAll('button:not(:disabled), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(!x||x.length===0)return;const w=x[0],v=x[x.length-1];m.shiftKey&&document.activeElement===w?(m.preventDefault(),v.focus()):!m.shiftKey&&document.activeElement===v&&(m.preventDefault(),w.focus())}return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[t!=null,r]),!t)return null;const d=t.details.slice(0,SB),f=t.details.length-d.length;return a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.toast},children:a.jsxs("div",{ref:c,role:"alertdialog","aria-modal":"true","aria-labelledby":Wv,"aria-describedby":Hv,onClick:p=>p.stopPropagation(),className:"flex w-full max-w-[520px] min-w-[440px] flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{id:Wv,className:"text-sm font-semibold text-content",children:"Du travail est encore en cours"}),a.jsx("p",{id:Hv,className:"text-sm text-content",children:kB(t)}),a.jsx("p",{className:"text-sm text-muted",children:"Annulez la fermeture pour laisser les agents et les tâches se terminer."}),d.length>0&&a.jsxs("ul",{className:"flex flex-col gap-1 rounded-md bg-canvas p-2 text-xs text-muted",children:[d.map((p,m)=>a.jsx("li",{children:`• ${CB(p)}`},m)),f>0&&a.jsxs("li",{children:["+ ",f," autre",f>1?"s":""]})]}),s&&a.jsx("p",{role:"alert",className:"text-sm text-danger",children:"IdeA n'a pas pu quitter correctement. Réessayez ou consultez les logs."}),a.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[a.jsx(M,{ref:o,size:"sm",variant:"ghost",disabled:r,onClick:u,children:"Annuler"}),a.jsx(M,{size:"sm",variant:"danger",disabled:r,loading:r,onClick:()=>void h(),children:r?"Fermeture…":"Quitter quand même"})]})]})})}function EB(){const{system:e,profile:t}=fe(),[n,r]=g.useState(null),[i,s]=g.useState(null),[l,o]=g.useState([]),[c,u]=g.useState(null);return g.useEffect(()=>{let h,d=!1;return e.onDomainEvent(f=>o(p=>[...p,f])).then(f=>{d?f():h=f}).catch(()=>{}),e.health("ui-boot").then(f=>r(f)).catch(f=>s(PB(f))),()=>{d=!0,h?.()}},[e]),g.useEffect(()=>{let h=!1;return t.firstRunState().then(d=>{h||u(d.isFirstRun)}).catch(()=>{h||u(!1)}),()=>{h=!0}},[t]),a.jsx(LP,{children:a.jsxs(aA,{children:[a.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between border-b border-border px-6 py-3",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"IdeA"}),a.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"tauri"})]}),a.jsx(pw,{justify:"end",children:a.jsx("span",{className:"text-xs text-faint",children:n?a.jsxs(a.Fragment,{children:["backend ",a.jsx("span",{className:"text-success",children:"●"})," v",n.version," ·"," ",l.length," events"]}):i?a.jsx("span",{className:"text-danger",children:"backend unavailable"}):a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[a.jsx(Me,{size:12})," checking…"]})})})]}),a.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[i&&a.jsx(Se,{className:"mx-4 mt-4 border-danger/40",children:a.jsxs("p",{className:"text-sm text-danger",children:["Error: ",i]})}),c?a.jsx("div",{className:"flex flex-1 justify-center overflow-y-auto p-6",children:a.jsx("div",{className:"w-full max-w-xl",children:a.jsx(Sw,{onDone:()=>u(!1)})})}):a.jsx(wB,{})]})]}),a.jsx(NB,{})]})})}function PB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const AB=new Set(Object.keys(Hn).filter(e=>e!=="projects"));function TB(e){const n=new URLSearchParams(e).get("panel");return!n||!AB.has(n)?null:{panel:n}}function LB({panel:e}){const{focusedProject:t}=fe(),[n,r]=g.useState(void 0);return g.useEffect(()=>{let i=!1,s;return t.getFocusedProject().then(l=>{i||r(l)}).catch(()=>{i||r(null)}),t.onFocusedProjectChanged(l=>{i||r(l)}).then(l=>{i?l():s=l}),()=>{i=!0,s?.()}},[t]),a.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[a.jsxs("header",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5",children:[a.jsx("h1",{className:"text-sm font-semibold text-content",children:Hn[e]}),n&&a.jsxs("span",{className:"truncate text-xs text-muted",children:["· ",n.name]})]}),a.jsx("main",{className:"min-h-0 flex-1 overflow-auto p-4",children:n?a.jsx(l0,{panel:e,projectId:n.id,projectRoot:n.root}):a.jsx(Se,{children:a.jsx("p",{className:"text-sm text-muted",children:"Ouvrez un projet dans la fenêtre principale pour afficher ce panneau."})})})]})}function DB(e){if(e&&typeof e=="object"&&"message"in e){const t=e;return{code:String(t.code??"ERROR"),message:String(t.message)}}return{code:"ERROR",message:String(e)}}function RB({session:e,onPaired:t}){const[n,r]=g.useState(""),[i,s]=g.useState(()=>Sx(nL())),[l,o]=g.useState(null),[c,u]=g.useState(!1),h=WO(n),d=i.trim(),f=h.length>0&&d.length>0,p=l?.code==="invalidName"?l.message:null,m=l&&!p?l.message:null;async function x(w){if(w.preventDefault(),!(!f||c)){u(!0),o(null);try{await e.pair(h,Sx(d)),t()}catch(v){o(DB(v))}finally{u(!1)}}}return a.jsx("div",{className:"flex h-full items-center justify-center overflow-y-auto bg-canvas p-4 sm:p-6",children:a.jsx(Se,{className:"w-full max-w-sm",children:a.jsxs("form",{onSubmit:x,className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("h1",{className:"text-lg font-semibold tracking-tight",children:"Appairer cet appareil"}),a.jsx("p",{className:"text-sm text-muted",children:"Saisissez le code affiché par le serveur IdeA pour connecter ce navigateur."})]}),a.jsx(qt,{label:"Code d'appairage",hint:"8 caractères : chiffres et lettres A-F",children:({id:w,describedBy:v})=>a.jsx(oe,{id:w,"aria-describedby":v,value:n,onChange:_=>r(_.target.value),placeholder:"p. ex. AB12CD34",autoFocus:!0,autoComplete:"one-time-code",inputMode:"text",autoCapitalize:"characters",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!m})}),a.jsx(qt,{label:"Nom de cet appareil",hint:"Pour le reconnaître dans la liste des appareils.",error:p??void 0,children:({id:w,describedBy:v})=>a.jsx(oe,{id:w,"aria-describedby":v,value:i,onChange:_=>s(_.target.value),maxLength:gp,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:c,invalid:!!p})}),m&&a.jsx("p",{role:"alert","data-testid":"pairing-error",className:"text-sm text-danger",children:m}),a.jsx(M,{type:"submit",disabled:c||!f,children:c?"Appairage…":"Appairer"})]})})})}const MB=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Ctrl-C",aria:"Ctrl-C (interrompre)",data:""},{label:"Ctrl-D",aria:"Ctrl-D (fin de saisie)",data:""},{label:"↑",aria:"Flèche haut",data:"\x1B[A"},{label:"↓",aria:"Flèche bas",data:"\x1B[B"},{label:"←",aria:"Flèche gauche",data:"\x1B[D"},{label:"→",aria:"Flèche droite",data:"\x1B[C"}];function IB({api:e,className:t}){return a.jsx("div",{role:"toolbar","aria-label":"Touches du terminal","data-testid":"terminal-key-bar",className:q("flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-raised/40 px-2 py-1.5",t),children:MB.map(n=>a.jsx(M,{size:"sm",variant:"secondary","aria-label":n.aria??n.label,disabled:!e,onPointerDown:r=>r.preventDefault(),onClick:()=>{e?.send(n.data),e?.focus()},className:"min-h-11 shrink-0 font-mono",children:n.label},n.label))})}function OB({projectId:e,agentId:t,cwd:n,nodeId:r,refitSignal:i}){const{agent:s}=fe(),[l,o]=g.useState(null),[c,u]=g.useState(null),h=g.useCallback((f,p)=>s.launchAgent(e,t,r?{...f,nodeId:r}:f,p),[s,e,t,r]),d=g.useCallback((f,p)=>s.reattach(f,p),[s]);return a.jsxs("div",{"data-testid":"web-agent-cell",className:"flex h-[60dvh] min-h-64 w-full flex-col overflow-hidden rounded-md border border-border sm:h-80",children:[a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(up,{cwd:n,agentMode:!0,open:h,reattach:d,sessionId:l,onSessionId:o,onReady:u,refitSignal:i})}),a.jsx(IB,{api:c})]})}function BB(e){g.useEffect(()=>{const t=Ih();if(!t)return;let n=t.getConnectionState();return t.onConnectionStateChange(r=>{r==="connected"&&n==="reconnecting"&&e(),n=r})},[e])}function zB(){const[e,t]=g.useState(()=>Ih()?.getConnectionState()??null);return g.useEffect(()=>{const n=Ih();if(n)return t(n.getConnectionState()),n.onConnectionStateChange(t)},[]),e}function Rc(e){switch(e){case"open":return"Ouvert";case"inProgress":return"En cours";case"QA":return"QA";case"closed":return"Fermé"}}function la(e){switch(e){case"low":return"Faible";case"medium":return"Moyenne";case"high":return"Haute";case"critical":return"Critique"}}function Uv(e){switch(e){case"relatesTo":return"en relation avec";case"blocks":return"bloque";case"blockedBy":return"bloqué par";case"duplicates":return"duplique";case"dependsOn":return"dépend de"}}function FB(e){switch(e){case"open":return"bg-raised text-muted";case"inProgress":return"bg-warning/15 text-warning";case"QA":return"bg-primary/15 text-primary";case"closed":return"bg-success/15 text-success"}}function $B(e){switch(e){case"low":return"bg-raised text-muted";case"medium":return"bg-primary/10 text-primary";case"high":return"bg-warning/15 text-warning";case"critical":return"bg-danger/15 text-danger"}}function a0(e){return q("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium",e)}function Fp({status:e}){return a.jsx("span",{className:a0(FB(e)),children:Rc(e)})}function $p({priority:e}){return a.jsx("span",{className:a0($B(e)),children:la(e)})}const qv=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),WB=q("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function HB({sprints:e,busy:t,error:n,onCancel:r,onCreate:i}){const[s,l]=g.useState(""),[o,c]=g.useState(""),[u,h]=g.useState("medium"),[d,f]=g.useState("");async function p(m){m.preventDefault();const x=s.trim();x&&await i({title:x,priority:u,...o.trim()?{description:o.trim()}:{}},d||null)}return a.jsxs(Se,{title:"Nouveau ticket",actions:a.jsx(M,{size:"sm",variant:"ghost",onClick:r,children:"Annuler"}),children:[n&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n}),a.jsxs("form",{onSubmit:p,className:"flex flex-col gap-3",children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),a.jsx(oe,{"aria-label":"Titre",value:s,onChange:m=>l(m.target.value),disabled:t,autoFocus:!0})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Priorité"}),a.jsx("select",{"aria-label":"Priorité",className:qv,value:u,disabled:t,onChange:m=>h(m.target.value),children:js.map(m=>a.jsx("option",{value:m,children:la(m)},m))})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Sprint"}),a.jsxs("select",{"aria-label":"Sprint",className:qv,value:d,disabled:t,onChange:m=>f(m.target.value),children:[a.jsx("option",{value:"",children:"Sans sprint"}),e.map(m=>a.jsx("option",{value:m.id,children:m.name},m.id))]})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),a.jsx("textarea",{"aria-label":"Description",className:q(WB,"min-h-20"),value:o,onChange:m=>c(m.target.value),disabled:t})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[a.jsx(M,{type:"button",variant:"ghost",size:"sm",disabled:t,onClick:r,children:"Annuler"}),a.jsx(M,{type:"submit",size:"sm",disabled:!s.trim()||t,loading:t,children:"Créer"})]})]})]})}function o0({title:e,body:t,confirmLabel:n,busy:r=!1,onConfirm:i,onCancel:s}){const l=g.useRef(null);return g.useEffect(()=>{l.current?.focus()},[]),g.useEffect(()=>{function o(c){c.key==="Escape"&&s()}return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[s]),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",style:{zIndex:kn.toast},children:a.jsxs("div",{role:"alertdialog","aria-modal":"true","aria-label":e,onClick:o=>o.stopPropagation(),className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:e}),a.jsx("p",{className:"text-sm text-muted",children:t}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{ref:l,size:"sm",variant:"ghost",disabled:r,onClick:s,children:"Annuler"}),a.jsx(M,{size:"sm",variant:"danger",loading:r,disabled:r,onClick:()=>void i(),children:n})]})]})})}function c0({projectId:e,title:t,confirmLabel:n="Ajouter",selectionMode:r,excludeRefs:i,onSelect:s,onClose:l}){const o=Dc(e,{excludeRefs:i}),c=r==="multi",[u,h]=g.useState(()=>new Set),[d,f]=g.useState(!1),[p,m]=g.useState(null),x=g.useRef(null);g.useEffect(()=>{x.current?.focus()},[]),g.useEffect(()=>{function b(C){C.key==="Escape"&&l()}return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[l]);function w(b){return b&&typeof b=="object"&&"message"in b?String(b.message):String(b)}function v(b){h(C=>{const S=new Set(C);return S.has(b)?S.delete(b):S.add(b),S})}async function _(b){if(!d){f(!0),m(null);try{s(await o.resolve(b)),l()}catch(C){m(w(C)),f(!1)}}}async function y(){if(!(d||u.size===0)){f(!0),m(null);try{const b=await Promise.all(Array.from(u).map(C=>o.resolve(C)));s(b),l()}catch(b){m(w(b)),f(!1)}}}return a.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":t,style:{zIndex:kn.floatingWindowNested},children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[a.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:t}),a.jsx(M,{ref:x,size:"sm",variant:"ghost",onClick:l,children:"Fermer"})]}),a.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:a.jsx(oe,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:o.text,onChange:b=>o.setText(b.target.value),autoFocus:!0})}),(o.error||p)&&a.jsx("p",{role:"alert",className:"shrink-0 border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:p??o.error}),a.jsxs("div",{className:"min-h-0 flex-1 overflow-auto px-4 py-3",children:[o.busy&&o.rows.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Chargement des tickets…"})]}):o.rows.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:o.rows.map(b=>{const C=u.has(b.ref);return a.jsx("li",{className:"py-1.5 first:pt-0 last:pb-0",children:a.jsxs("button",{type:"button","aria-label":`${b.ref}, ${b.title}`,...c?{role:"checkbox","aria-checked":C}:{},disabled:d,onClick:()=>c?v(b.ref):void _(b.ref),className:q("flex min-h-[40px] w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-60",c&&C&&"bg-raised"),children:[c&&a.jsx("span",{"aria-hidden":"true",className:q("flex h-4 w-4 shrink-0 items-center justify-center rounded border text-[10px] font-bold",C?"border-primary bg-primary text-on-primary":"border-border text-transparent"),children:"✓"}),a.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:b.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-content",children:b.title}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[a.jsx(Fp,{status:b.status}),a.jsx($p,{priority:b.priority})]})]})},b.ref)})}),o.hasMore&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:o.busy,onClick:()=>o.loadMore(),children:"Charger plus"})})]}),c&&a.jsxs("footer",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]",children:[a.jsxs("span",{className:"text-xs text-muted","aria-live":"polite",children:[u.size," sélectionné",u.size>1?"s":""]}),a.jsxs(M,{size:"sm",loading:d,disabled:u.size===0||d,onClick:()=>void y(),children:[n," ",u.size>0?`(${u.size})`:""]})]})]})}const zi=q("h-9 rounded-md bg-raised px-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Vv=q("w-full rounded-md bg-raised p-3 text-sm text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50");function Fi({title:e,defaultOpen:t,children:n}){const[r,i]=g.useState(t);return a.jsxs("section",{className:"border-b border-border py-2 last:border-b-0",children:[a.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>i(s=>!s),className:"flex min-h-[32px] w-full items-center justify-between text-left text-xs font-semibold uppercase tracking-wide text-muted",children:[e,a.jsx("span",{"aria-hidden":"true",children:r?"▾":"▸"})]}),r&&a.jsx("div",{className:"mt-2 flex flex-col gap-2",children:n})]})}function UB({projectId:e,ticketRef:t,nameOf:n,assignableAgents:r,sprints:i,onBack:s,onOpenRef:l}){const o=i0(e,t),c=o.ticket,[u,h]=g.useState(""),[d,f]=g.useState(""),[p,m]=g.useState(""),[x,w]=g.useState("relatesTo"),[v,_]=g.useState(""),[y,b]=g.useState(!1),[C,S]=g.useState(!1),[N,R]=g.useState(!1);g.useEffect(()=>{o.deleted&&s()},[o.deleted,s]);const D=o.reloadCount,k=g.useRef(-1),L=g.useRef(null);g.useEffect(()=>{if(!c||k.current===D)return;k.current=D;const E=c.carnet??"",F=L.current;F===null||o.conflict?(h(c.title),f(c.description),m(E)):(h(re=>re===F.title?c.title:re),f(re=>re===F.description?c.description:re),m(re=>re===F.carnet?E:re)),L.current={title:c.title,description:c.description,carnet:E}},[c,D,o.conflict]);const A=!!c&&(u!==c.title||d!==c.description),P=!!c&&p!==(c.carnet??""),I=A||P,O=r.filter(E=>!c?.assignedAgentIds.includes(E.id));function U(){I?S(!0):s()}async function K(){let E=!0;A&&(E=await o.updateFields({title:u,description:d})&&E),E&&P&&(E=await o.saveCarnet(p)&&E),S(!1),E&&s()}return a.jsxs(Se,{className:"flex flex-col",flush:!0,children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:U,children:"← Tickets"}),a.jsx("code",{className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:t})]}),o.conflict&&a.jsx("p",{role:"alert",className:"border-b border-warning/40 bg-warning/10 px-4 py-2 text-sm text-warning",children:"Ce ticket a été modifié ailleurs et rechargé. Réappliquez votre modification."}),o.error&&!o.conflict&&a.jsx("p",{role:"alert",className:"border-b border-danger/40 bg-danger/10 px-4 py-2 text-sm text-danger",children:o.error}),o.busy&&!c?a.jsxs("div",{className:"flex items-center gap-2 px-4 py-5 text-sm text-muted",children:[a.jsx(Me,{size:14}),a.jsx("span",{children:"Chargement du ticket…"})]}):c?a.jsxs("div",{className:"flex flex-col px-4 py-2",children:[a.jsxs("div",{className:"flex flex-col gap-1 border-b border-border pb-3",children:[a.jsx("span",{className:"text-sm font-semibold text-content",children:c.title}),a.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[a.jsx(Fp,{status:c.status}),a.jsx($p,{priority:c.priority}),c.sprintId&&a.jsxs("span",{children:["· ",i.find(E=>E.id===c.sprintId)?.name??"Sprint"]})]})]}),a.jsxs(Fi,{title:"Résumé",defaultOpen:!0,children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Titre"}),a.jsx("input",{"aria-label":"Titre",className:q(zi,"w-full"),value:u,onChange:E=>h(E.target.value),disabled:o.busy})]}),a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Description"}),a.jsx("textarea",{"aria-label":"Description",className:q(Vv,"min-h-24"),value:d,onChange:E=>f(E.target.value),disabled:o.busy})]}),a.jsx("div",{children:a.jsx(M,{size:"sm",disabled:!A||o.busy,loading:o.busy&&A,onClick:()=>void o.updateFields({title:u,description:d}),children:"Enregistrer"})})]}),a.jsxs(Fi,{title:"Statut et priorité",defaultOpen:!0,children:[a.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[a.jsx("span",{className:"text-muted",children:"Statut"}),a.jsx("select",{"aria-label":"Statut",className:zi,value:c.status,disabled:o.busy,onChange:E=>void o.updateFields({status:E.target.value}),children:Tc.map(E=>a.jsx("option",{value:E,children:Rc(E)},E))})]}),a.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[a.jsx("span",{className:"text-muted",children:"Priorité"}),a.jsx("select",{"aria-label":"Priorité",className:zi,value:c.priority,disabled:o.busy,onChange:E=>void o.updateFields({priority:E.target.value}),children:js.map(E=>a.jsx("option",{value:E,children:la(E)},E))})]}),a.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[a.jsx("span",{className:"text-muted",children:"Sprint"}),a.jsxs("select",{"aria-label":"Sprint",className:zi,value:c.sprintId??"",disabled:o.busy,onChange:E=>void o.setSprint(E.target.value||null),children:[a.jsx("option",{value:"",children:"Sans sprint"}),i.map(E=>a.jsx("option",{value:E.id,children:E.name},E.id))]})]}),o.busy&&a.jsx(Me,{size:12})]}),a.jsxs(Fi,{title:"Carnet",defaultOpen:!0,children:[a.jsx("textarea",{"aria-label":"Carnet",className:q(Vv,"min-h-32 font-mono"),value:p,onChange:E=>m(E.target.value),disabled:o.busy}),a.jsx("div",{children:a.jsx(M,{size:"sm",disabled:!P||o.busy,loading:o.busy&&P,onClick:()=>void o.saveCarnet(p),children:"Enregistrer le carnet"})})]}),a.jsxs(Fi,{title:"Agents assignés",defaultOpen:!1,children:[c.assignedAgentIds.length===0?a.jsx("p",{className:"text-xs text-muted",children:"Aucun agent assigné."}):a.jsx("ul",{className:"flex flex-wrap gap-2",children:c.assignedAgentIds.map(E=>a.jsxs("li",{className:"flex items-center gap-1 rounded-full bg-raised px-2 py-0.5 text-xs text-content",children:[n(E),a.jsx("button",{type:"button","aria-label":`Désassigner ${n(E)}`,className:"text-muted hover:text-danger disabled:opacity-50",disabled:o.busy,onClick:()=>void o.assign(E,!1),children:"×"})]},E))}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{"aria-label":"Assigner un agent",className:zi,value:v,disabled:o.busy||O.length===0,onChange:E=>_(E.target.value),children:[a.jsx("option",{value:"",children:O.length===0?"Aucun autre agent":"Choisir un agent…"}),O.map(E=>a.jsx("option",{value:E.id,children:E.name},E.id))]}),a.jsx(M,{size:"sm",disabled:!v||o.busy,onClick:async()=>{await o.assign(v,!0)&&_("")},children:"Assigner"})]})]}),a.jsxs(Fi,{title:"Liens",defaultOpen:!1,children:[c.links.length===0?a.jsx("p",{className:"text-xs text-muted",children:"Aucun ticket lié."}):a.jsx("ul",{className:"flex flex-col gap-1",children:c.links.map(E=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-xs text-muted",children:Uv(E.kind)}),a.jsx("button",{type:"button",className:"rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content hover:text-primary",onClick:()=>l(E.targetRef),children:E.targetRef}),a.jsx(M,{size:"sm",variant:"ghost",disabled:o.busy,onClick:()=>void o.unlink(E.targetRef,E.kind),children:"Retirer"})]},`${E.kind}-${E.targetRef}`))}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("select",{"aria-label":"Type de lien",className:zi,value:x,disabled:o.busy,onChange:E=>w(E.target.value),children:e0.map(E=>a.jsx("option",{value:E,children:Uv(E)},E))}),a.jsx(M,{size:"sm",disabled:o.busy,onClick:()=>R(!0),children:"+ Lier"})]})]}),a.jsxs(Fi,{title:"Zone dangereuse",defaultOpen:!1,children:[a.jsxs("p",{className:"text-xs text-muted",children:["Le ticket ",t," sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés."]}),a.jsx("div",{children:a.jsx(M,{size:"sm",variant:"danger",disabled:o.busy,onClick:()=>b(!0),children:"Supprimer"})})]})]}):a.jsx("p",{className:"px-4 py-5 text-sm text-muted",children:"Ticket introuvable."}),N&&c&&a.jsx(c0,{projectId:e,title:"Lier un ticket",selectionMode:"single",excludeRefs:[t,...c.links.map(E=>E.targetRef)],onSelect:E=>{const F=Array.isArray(E)?E[0]:E;F&&o.link(F.ref,x)},onClose:()=>R(!1)}),y&&a.jsx(o0,{title:"Supprimer ce ticket ?",body:`Le ticket ${t} sera supprimé définitivement. Cette action ne supprime pas les sprints ni les agents assignés.`,confirmLabel:"Supprimer",busy:o.busy,onCancel:()=>b(!1),onConfirm:async()=>{await o.remove()&&b(!1)}}),C&&a.jsx("div",{role:"alertdialog","aria-modal":"true","aria-label":"Modifications non enregistrées",className:"fixed inset-0 flex items-center justify-center bg-black/50 p-4",children:a.jsxs("div",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-raised p-4 shadow-xl",children:[a.jsx("h3",{className:"text-sm font-semibold text-content",children:"Des modifications ne sont pas enregistrées."}),a.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:o.busy,onClick:()=>S(!1),children:"Continuer l'édition"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:o.busy,onClick:s,children:"Ignorer"}),a.jsx(M,{size:"sm",loading:o.busy,disabled:o.busy,onClick:()=>void K(),children:"Enregistrer et quitter"})]})]})})]})}function qB(e){const t=ea(e),n=g.useMemo(()=>(t.state?.agents??[]).map(s=>({id:s.agentId,name:s.name})),[t.state]),r=g.useMemo(()=>new Map(n.map(s=>[s.id,s.name])),[n]);return{agents:n,nameOf:s=>r.get(s)??`${s.slice(0,8)}…`,loaded:t.state!==null}}const Va=q("h-8 rounded-md bg-raised px-2 text-xs text-content","border border-border outline-none transition-colors","focus:border-primary disabled:cursor-not-allowed disabled:opacity-50"),Kv={number:"Numéro",priority:"Priorité",status:"Statut",title:"Titre"};function VB({projectId:e,focusSprintId:t=null}){const n=Op(e),r=qB(e),[i,s]=g.useState({type:"list"}),[l,o]=g.useState(t);if(i.type==="detail")return a.jsx(UB,{projectId:e,ticketRef:i.ref,nameOf:r.nameOf,assignableAgents:r.agents,sprints:n.sprints,onBack:()=>s({type:"list"}),onOpenRef:x=>s({type:"detail",ref:x})},i.ref);if(i.type==="create")return a.jsx(HB,{sprints:n.sprints,busy:n.busy,error:n.error,onCancel:()=>s({type:"list"}),onCreate:async(x,w)=>{const v=await n.create(x);v&&(w&&await n.assignSprint(v.ref,w),s({type:"detail",ref:v.ref}))}});const c=n.list?.items??[],u=!!n.query.text||(n.query.statuses?.length??0)>0||(n.query.priorities?.length??0)>0||!!n.query.assignedAgentId||!!l,h=new Set(n.sprints.map(x=>x.id)),f=(l?n.sprints.filter(x=>x.id===l):n.sprints).map(x=>({sprint:x,tickets:c.filter(w=>w.sprintId===x.id)})).filter(x=>x.tickets.length>0),p=l?[]:c.filter(x=>!x.sprintId||!h.has(x.sprintId));function m(){n.setQuery({}),o(null)}return a.jsxs(Se,{className:"flex flex-col",title:"Tickets",actions:a.jsx(M,{size:"sm",onClick:()=>s({type:"create"}),children:"+ Ticket"}),children:[n.error&&a.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:[a.jsx("span",{children:n.error}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>void n.refresh(),children:"Réessayer"})]}),l&&a.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 rounded-md border border-border bg-raised/50 px-3 py-2 text-xs text-muted",children:[a.jsxs("span",{children:["Filtré sur le sprint « ",n.sprints.find(x=>x.id===l)?.name??l," »"]}),a.jsx(M,{size:"sm",variant:"ghost",onClick:()=>o(null),children:"Voir tous les tickets"})]}),a.jsxs("div",{className:"mb-3 flex flex-col gap-2",children:[a.jsx(oe,{"aria-label":"Rechercher des tickets",placeholder:"Recherche…",value:n.query.text??"",onChange:x=>n.setQuery({...n.query,text:x.target.value||void 0})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("select",{"aria-label":"Filtrer par statut",className:Va,value:n.query.statuses?.[0]??"",onChange:x=>n.setQuery({...n.query,statuses:x.target.value?[x.target.value]:void 0}),children:[a.jsx("option",{value:"",children:"Tous les statuts"}),Tc.map(x=>a.jsx("option",{value:x,children:Rc(x)},x))]}),a.jsxs("select",{"aria-label":"Filtrer par priorité",className:Va,value:n.query.priorities?.[0]??"",onChange:x=>n.setQuery({...n.query,priorities:x.target.value?[x.target.value]:void 0}),children:[a.jsx("option",{value:"",children:"Toutes les priorités"}),js.map(x=>a.jsx("option",{value:x,children:la(x)},x))]}),a.jsxs("select",{"aria-label":"Filtrer par agent assigné",className:Va,value:n.query.assignedAgentId??"",onChange:x=>n.setQuery({...n.query,assignedAgentId:x.target.value||void 0}),children:[a.jsx("option",{value:"",children:"Tous les agents"}),r.agents.map(x=>a.jsx("option",{value:x.id,children:x.name},x.id))]}),a.jsxs("select",{"aria-label":"Trier les tickets",className:Va,value:n.query.sort?.field??"",onChange:x=>{const w=x.target.value,{sort:v,..._}=n.query;n.setQuery(w?{..._,sort:{field:w,direction:"asc"}}:_)},children:[a.jsx("option",{value:"",children:"Tri par défaut"}),Object.keys(Kv).map(x=>a.jsx("option",{value:x,children:Kv[x]},x))]})]})]}),n.busy&&n.list===null?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Me,{size:12})," Chargement des tickets…"]}):c.length===0&&!u?a.jsxs("div",{className:"flex flex-col items-start gap-2",children:[a.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket dans ce projet."}),a.jsx(M,{size:"sm",onClick:()=>s({type:"create"}),children:"Créer un ticket"})]}):c.length===0?a.jsxs("div",{className:"flex flex-col items-start gap-2",children:[a.jsx("p",{className:"text-sm text-muted",children:"Aucun ticket ne correspond aux filtres."}),a.jsx(M,{size:"sm",variant:"ghost",onClick:m,children:"Réinitialiser les filtres"})]}):a.jsxs("div",{className:"flex flex-col gap-4","data-testid":"web-ticket-list",children:[f.map(x=>a.jsx(Gv,{heading:x.sprint.name,tickets:x.tickets,sprints:n.sprints,nameOf:r.nameOf,onOpen:w=>s({type:"detail",ref:w})},x.sprint.id)),p.length>0&&a.jsx(Gv,{heading:"Sans sprint",tickets:p,sprints:n.sprints,nameOf:r.nameOf,onOpen:x=>s({type:"detail",ref:x})})]}),n.list?.nextCursor&&a.jsx("div",{className:"mt-3 flex justify-center",children:a.jsx(M,{size:"sm",variant:"ghost",loading:n.busy,onClick:()=>n.setQuery({...n.query,limit:(n.query.limit??100)+100}),children:"Charger plus"})})]})}function Gv({heading:e,tickets:t,sprints:n,nameOf:r,onOpen:i}){const s=l=>l?n.find(o=>o.id===l)?.name:void 0;return a.jsxs("section",{"aria-label":`Tickets — ${e}`,children:[a.jsxs("h3",{className:"mb-1 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted",children:[e,a.jsx("span",{className:"rounded-full bg-raised px-1.5 text-[10px] font-medium text-muted",children:t.length})]}),a.jsx("ul",{className:"flex flex-col divide-y divide-border",children:t.map(l=>{const o=s(l.sprintId),c=l.assignedAgentIds.map(r).join(", ");return a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>i(l.ref),"aria-label":`${l.ref}, ${l.title}, statut ${Rc(l.status)}, priorité ${la(l.priority)}`,className:"flex w-full min-w-0 flex-col items-start gap-0.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-raised",children:[a.jsxs("span",{className:"flex w-full min-w-0 items-baseline gap-2",children:[a.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:l.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:l.title})]}),a.jsxs("span",{className:"flex flex-wrap items-center gap-1.5 text-xs text-muted",children:[a.jsx(Fp,{status:l.status}),a.jsx($p,{priority:l.priority}),o&&a.jsxs("span",{children:["· ",o]}),c&&a.jsxs("span",{children:["· ",c]})]})]})},l.ref)})})]})}function KB({projectId:e,onViewSprintTickets:t}){const n=Op(e),r=Dc(e,{refreshOnEvents:!0}),[i,s]=g.useState(!1),[l,o]=g.useState(""),[c,u]=g.useState(null),[h,d]=g.useState(""),[f,p]=g.useState(null),[m,x]=g.useState(null),w=[...n.sprints].sort((_,y)=>_.order-y.order);async function v(_){_.preventDefault();const y=l.trim();if(!y)return;await n.createSprint(y)&&(o(""),s(!1))}return a.jsxs(Se,{title:"Sprints",actions:a.jsx(M,{size:"sm",onClick:()=>s(_=>!_),children:"+ Sprint"}),children:[n.error&&a.jsx("p",{role:"alert",className:"mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-sm text-danger",children:n.error}),i&&a.jsxs("form",{onSubmit:v,className:"mb-3 flex flex-col gap-2 rounded-md border border-border bg-raised/50 p-2",children:[a.jsxs("label",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-xs font-medium text-muted",children:"Nom du sprint"}),a.jsx(oe,{"aria-label":"Nom du sprint",value:l,onChange:_=>o(_.target.value),autoFocus:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{type:"button",size:"sm",variant:"ghost",onClick:()=>s(!1),children:"Annuler"}),a.jsx(M,{type:"submit",size:"sm",disabled:!l.trim()||n.busy,children:"Créer"})]})]}),n.busy&&n.sprints.length===0?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Me,{size:12})," Chargement des sprints…"]}):w.length===0?a.jsxs("div",{className:"flex flex-col items-start gap-2",children:[a.jsx("p",{className:"text-sm text-muted",children:"Aucun sprint."}),a.jsx(M,{size:"sm",onClick:()=>s(!0),children:"Créer un sprint"})]}):a.jsx("ul",{className:"flex flex-col gap-3",children:w.map((_,y)=>a.jsx(GB,{sprint:_,index:y,lastIndex:w.length-1,tickets:r.rows.filter(b=>b.sprintId===_.id),vm:n,renaming:c===_.id,renameDraft:h,onStartRename:()=>{u(_.id),d(_.name)},onRenameDraftChange:d,onCancelRename:()=>u(null),onSaveRename:async()=>{await n.renameSprint(_.id,h.trim())&&u(null)},onViewTickets:()=>t(_.id),onAddTickets:()=>x({id:_.id,name:_.name}),onRequestDelete:()=>p({id:_.id,name:_.name})},_.id))}),f&&a.jsx(o0,{title:`Supprimer le sprint « ${f.name} » ?`,body:"Les tickets de ce sprint seront conservés et passeront en « Sans sprint ».",confirmLabel:"Supprimer",busy:n.busy,onCancel:()=>p(null),onConfirm:async()=>{await n.deleteSprint(f.id),p(null)}}),m&&a.jsx(c0,{projectId:e,title:`Ajouter des tickets au sprint « ${m.name} »`,confirmLabel:"Ajouter au sprint",selectionMode:"multi",excludeRefs:r.rows.filter(_=>_.sprintId===m.id).map(_=>_.ref),onSelect:_=>{const y=Array.isArray(_)?_:[_];for(const b of y)n.assignSprint(b.ref,m.id)},onClose:()=>x(null)})]})}function GB({sprint:e,index:t,lastIndex:n,tickets:r,vm:i,renaming:s,renameDraft:l,onStartRename:o,onRenameDraftChange:c,onCancelRename:u,onSaveRename:h,onViewTickets:d,onAddTickets:f,onRequestDelete:p}){return a.jsxs("li",{className:"rounded-md border border-border p-3",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("span",{className:"text-xs font-semibold text-muted",children:["#",e.order]}),!s&&a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-content",children:e.name})]}),s?a.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[a.jsx(oe,{"aria-label":`Renommer le sprint ${e.name}`,value:l,onChange:m=>c(m.target.value),disabled:i.busy}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:i.busy,onClick:u,children:"Annuler"}),a.jsx(M,{size:"sm",disabled:i.busy||!l.trim()||l.trim()===e.name,onClick:()=>void h(),children:"Enregistrer"})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:"mt-1 text-xs text-muted",children:[e.ticketCount," ticket",e.ticketCount>1?"s":""]}),r.length>0&&a.jsx("ul",{className:"mt-2 flex flex-col gap-1",children:r.map(m=>a.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[a.jsx("code",{className:"shrink-0 rounded bg-raised px-1.5 py-0.5 font-mono text-xs text-content",children:m.ref}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:m.title}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Retirer ${m.ref} du sprint ${e.name}`,disabled:i.busy,onClick:()=>void i.assignSprint(m.ref,null),children:"Retirer du sprint"})]},m.ref))}),a.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[a.jsx(M,{size:"sm",variant:"ghost",onClick:d,children:"Voir tickets"}),a.jsx(M,{size:"sm",variant:"ghost",onClick:f,children:"Ajouter tickets"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Renommer ${e.name}`,disabled:i.busy,onClick:o,children:"Renommer"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Monter ${e.name}`,disabled:i.busy||t===0,onClick:()=>void i.moveSprint(e.id,"up"),children:"Monter"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Descendre ${e.name}`,disabled:i.busy||t===n,onClick:()=>void i.moveSprint(e.id,"down"),children:"Descendre"}),a.jsx(M,{size:"sm",variant:"ghost","aria-label":`Supprimer ${e.name}`,disabled:i.busy,className:"text-danger hover:text-danger",onClick:p,children:"Supprimer"})]})]})]})}function YB(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}function XB({projects:e,openId:t,onOpen:n,onCreate:r,onRefresh:i}){const[s,l]=g.useState(""),[o,c]=g.useState(""),[u,h]=g.useState(!1),[d,f]=g.useState(null),p=s.trim().length>0&&o.trim().length>0&&!u;async function m(x){if(x.preventDefault(),!!p){h(!0),f(null);try{const w=await r(s.trim(),o.trim());l(""),c(""),n(w.id)}catch(w){f(YB(w))}finally{h(!1)}}}return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Projets"}),a.jsx(M,{variant:"ghost",size:"sm",onClick:i,children:"Rafraîchir"})]}),a.jsx(Se,{title:"Nouveau projet",children:a.jsxs("form",{onSubmit:x=>void m(x),className:"flex flex-col gap-2",children:[a.jsx(oe,{"aria-label":"Nom du projet",placeholder:"Nom du projet",value:s,onChange:x=>l(x.target.value)}),a.jsx(oe,{"aria-label":"Chemin du projet",placeholder:"/chemin/absolu/du/projet",value:o,onChange:x=>c(x.target.value)}),a.jsx("p",{className:"text-xs text-muted",children:"Saisir un chemin absolu accessible depuis le serveur IdeA."}),d&&a.jsx("p",{role:"alert",className:"text-xs text-danger",children:d}),a.jsx(M,{type:"submit",variant:"primary",disabled:!p,loading:u,children:"Créer le projet"})]})}),e===null?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted",children:[a.jsx(Me,{size:12})," Chargement des projets…"]}):e.length===0?a.jsx("p",{className:"text-sm text-muted",children:"Aucun projet."}):a.jsx("ul",{className:"flex flex-col gap-2","data-testid":"web-project-list",children:e.map(x=>a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>n(x.id),"aria-pressed":t===x.id,className:"flex w-full flex-col items-start rounded-md border border-border bg-raised px-3 py-2 text-left transition-colors hover:border-primary aria-pressed:border-primary",children:[a.jsx("span",{className:"text-sm font-medium text-content",children:x.name}),a.jsx("span",{className:"text-xs text-faint",children:x.root})]})},x.id))})]})}function u0({title:e,entries:t,note:n,onClose:r}){const i=g.useRef(null);return g.useEffect(()=>{i.current?.focus()},[]),g.useEffect(()=>{function s(l){l.key==="Escape"&&r()}return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[r]),a.jsxs("div",{className:"fixed inset-0 flex flex-col bg-canvas",role:"dialog","aria-modal":"true","aria-label":e,style:{zIndex:kn.floatingWindowNested},children:[a.jsxs("header",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))]",children:[a.jsx("span",{className:"min-w-0 truncate text-sm font-medium text-content",children:e}),a.jsx(M,{ref:i,size:"sm",variant:"ghost",onClick:r,children:"Fermer"})]}),n&&a.jsx("p",{className:"shrink-0 border-b border-border px-4 py-2 text-xs text-muted",children:n}),a.jsx("ul",{className:"min-h-0 flex-1 overflow-auto px-2 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:t.map(s=>a.jsx("li",{children:a.jsxs("button",{type:"button",disabled:s.disabled,title:s.hint,"aria-current":s.active?"true":void 0,onClick:()=>{s.disabled||s.onSelect()},className:q("flex min-h-[44px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors","hover:bg-raised focus:bg-raised focus:outline-none disabled:opacity-50 disabled:hover:bg-transparent",s.active&&"bg-raised font-medium text-content"),children:[a.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-primary",children:s.active?"●":""}),a.jsx("span",{className:"min-w-0 flex-1 truncate",children:s.label}),s.secondaryLabel&&a.jsx("span",{className:"shrink-0 text-xs text-muted",children:s.secondaryLabel})]})},s.id))})]})}function xo(e){return e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}const QB=["context","work","tickets","sprints","agents","templates","skills","permissions","memory","git","projects"],Yv={context:"Contexte projet",work:"Travail",tickets:"Tickets",sprints:"Sprints",agents:"Agents",templates:"Templates",skills:"Skills",permissions:"Permissions",memory:"Mémoire",git:"Git",projects:"Projets"};function JB(){const{project:e}=fe(),[t,n]=g.useState(null),[r,i]=g.useState(null),[s,l]=g.useState(null),[o,c]=g.useState("projects"),[u,h]=g.useState(null),d=t?.find(x=>x.id===s)?.root??null,f=g.useCallback(async()=>{i(null);try{n(await e.listProjects())}catch(x){i(xo(x))}},[e]);g.useEffect(()=>{f()},[f]);const p=g.useCallback(async x=>{i(null),l(null);try{await e.openProject(x),l(x),c("work")}catch(w){i(xo(w))}},[e]),m=g.useCallback(async(x,w)=>{i(null);try{const v=await e.createProject(x,w);return await f(),v}catch(v){throw i(xo(v)),v}},[e,f]);return a.jsxs("div",{"data-testid":"web-workspace",className:"flex h-full flex-col gap-4 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:[a.jsx(t4,{}),a.jsx(ZB,{activePanel:o,hasProject:!!s,onSelect:c}),r&&a.jsx(Se,{className:"border-danger/40",children:a.jsx("p",{className:"text-sm text-danger",children:r})}),o==="projects"?a.jsx(XB,{projects:t,openId:s,onOpen:x=>void p(x),onCreate:m,onRefresh:()=>void f()}):s?a.jsx(e4,{panel:o,projectId:s,root:d,focusSprintId:u,onViewSprintTickets:x=>{h(x),c("tickets")}}):a.jsx("p",{className:"text-sm text-muted",children:"Ouvrir un projet pour utiliser ce panneau."})]})}function ZB({activePanel:e,hasProject:t,onSelect:n}){const[r,i]=g.useState(!1);return a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>i(!0),children:["Panneaux : ",Yv[e]]}),r&&a.jsx(u0,{title:"Panneaux",note:t?void 0:"Ouvrir un projet pour utiliser ce panneau.",onClose:()=>i(!1),entries:QB.map(s=>{const l=s!=="projects"&&!t;return{id:s,label:Yv[s],active:s===e,disabled:l,hint:l?"Ouvrir un projet pour utiliser ce panneau.":void 0,onSelect:()=>{n(s),i(!1)}}})})]})}function e4({panel:e,projectId:t,root:n,focusSprintId:r,onViewSprintTickets:i}){switch(e){case"context":return a.jsx(s0,{projectId:t});case"work":return a.jsx(n4,{projectId:t,root:n});case"tickets":return a.jsx(VB,{projectId:t,focusSprintId:r});case"sprints":return a.jsx(KB,{projectId:t,onViewSprintTickets:i});case"agents":return a.jsx(xw,{projectId:t,projectRoot:n??""});case"templates":return a.jsx(zS,{projectId:t});case"skills":return a.jsx(FS,{projectId:t});case"permissions":return a.jsx(GS,{projectId:t});case"memory":return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx(qS,{projectId:t}),a.jsx(US,{})]});case"git":return a.jsx(Tw,{projectId:t})}}function t4(){return zB()!=="reconnecting"?null:a.jsxs("div",{role:"status","data-testid":"web-reconnect-banner",className:"flex items-center gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning",children:[a.jsx(Me,{size:12}),"Connexion perdue — reconnexion en cours…"]})}function n4({projectId:e,root:t}){const n=ea(e);BB(n.refresh);const[r,i]=g.useState(null),[s,l]=g.useState(0),o=g.useCallback(()=>l(f=>f+1),[]),c=n.state?.agents??[],[u,h]=g.useState(new Set);g.useEffect(()=>{const f=new Set(c.filter(p=>(p.backgroundTasks??[]).length>0).map(p=>p.agentId));h(p=>{const m=new Set([...p].filter(x=>f.has(x)));return m.size===p.size?p:m})},[c]);const d=g.useCallback(f=>{h(p=>{const m=new Set(p);return m.has(f)?m.delete(f):m.add(f),m})},[]);return a.jsxs(Se,{className:"mt-2",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[a.jsxs("h3",{className:"text-sm font-semibold",children:["État live",a.jsx("span",{className:"ml-2 rounded bg-canvas px-1.5 py-0.5 text-[0.6rem] uppercase text-muted",children:"read-only"})]}),a.jsx(M,{variant:"ghost",size:"sm",loading:n.busy,onClick:()=>void n.refresh(),children:"Rafraîchir"})]}),n.error&&a.jsx("p",{role:"alert",className:"mb-2 text-xs text-danger",children:n.error}),n.busy&&n.state===null?a.jsx("p",{className:"text-xs text-muted",children:"Chargement de l'état…"}):c.length===0?a.jsx("p",{className:"text-xs text-muted",children:"Aucun agent actif."}):a.jsx("ul",{className:"flex flex-col divide-y divide-border","data-testid":"web-workstate",children:c.map(f=>a.jsx(r4,{agent:f,open:r===f.agentId,onToggleOpen:()=>{i(p=>p===f.agentId?null:f.agentId),o()},onRefresh:n.refresh,bgExpanded:u.has(f.agentId),onToggleBgExpanded:()=>d(f.agentId)},f.agentId))}),t&&r&&a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[a.jsx("span",{className:"text-xs font-semibold text-muted",children:"Agent"}),a.jsx(M,{variant:"ghost",size:"sm",onClick:()=>{i(null),o()},children:"Fermer"})]}),a.jsx(OB,{projectId:e,agentId:r,cwd:t,refitSignal:s},r)]})]})}function r4({agent:e,open:t,onToggleOpen:n,onRefresh:r,bgExpanded:i,onToggleBgExpanded:s}){const l=e.live!==void 0,o=e.busy?.state==="busy",c=[...e.inbox??[]].sort((h,d)=>h.createdAtMs-d.createdAtMs),u=[...e.backgroundTasks??[]].sort((h,d)=>d.updatedAtMs-h.updatedAtMs||h.taskId.localeCompare(d.taskId));return a.jsxs("li",{className:"py-2 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between sm:gap-2",children:[a.jsx("span",{className:"min-w-0 truncate text-sm text-content",children:e.name}),a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-xs",children:[a.jsx("span",{className:q("rounded-full px-2 py-0.5 font-medium",l?"bg-success/15 text-success":"bg-raised text-muted"),children:l?"Live":"Offline"}),a.jsx("span",{className:q("rounded-full px-2 py-0.5 font-medium",o?"bg-warning/15 text-warning":"bg-raised text-muted"),children:o?"Busy":"Idle"}),a.jsx(M,{variant:"ghost",size:"sm","aria-pressed":t,onClick:n,children:t?"Fermer":"Ouvrir"})]})]}),c.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-faint",children:"Inbox"}),a.jsx("ul",{"aria-label":`${e.name} inbox`,className:"mt-1 flex flex-col gap-1",children:c.map(h=>a.jsxs("li",{className:"flex min-w-0 items-start gap-2 text-xs text-muted",children:[a.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-raised px-1.5 py-0.5 font-medium",children:h.kind}),a.jsx("span",{className:"min-w-0 flex-1 break-words",children:h.body})]},h.id))})]}),u.length>0&&a.jsxs("div",{className:"mt-2",children:[a.jsxs("button",{type:"button","aria-expanded":i,"aria-controls":`web-bg-tasks-${e.agentId}`,"aria-label":i?`Masquer les background tasks de ${e.name}`:`Afficher les background tasks de ${e.name}`,onClick:s,className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-faint hover:text-muted",children:[a.jsx("span",{"aria-hidden":"true",children:i?"▾":"▸"}),"Background tasks",a.jsx("span",{className:"rounded-full bg-raised px-1.5 py-0.5 font-medium normal-case tracking-normal text-muted",children:u.length})]}),i&&a.jsx("ul",{id:`web-bg-tasks-${e.agentId}`,"aria-label":`${e.name} background tasks`,className:"mt-1 flex flex-col gap-1",children:u.map(h=>a.jsx(l4,{task:h,onRefresh:r},h.taskId))})]})]})}const i4={running:"Running",completed:"Completed",failed:"Failed",cancelled:"Cancelled",pending:"Pending",delivered:"Delivered"};function s4(e){return e==="running"||e==="pending"?"bg-warning/15 text-warning":e==="completed"||e==="delivered"?"bg-success/10 text-success":e==="failed"||e==="cancelled"?"bg-danger/10 text-danger":"bg-raised text-muted"}function l4({task:e,onRefresh:t}){const{workState:n}=fe(),[r,i]=g.useState(!1),[s,l]=g.useState(null),o=e.status==="running"||e.status==="pending",c=e.status==="failed"||e.status==="cancelled";async function u(h){i(!0),l(null);try{await h(e.taskId),await t()}catch(d){l(xo(d))}finally{i(!1)}}return a.jsxs("li",{className:"min-w-0 text-xs text-muted",children:[a.jsxs("div",{className:"flex min-w-0 flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx("span",{className:q("shrink-0 rounded-full px-1.5 py-0.5 font-medium",s4(e.status)),children:i4[e.status]}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-content",children:e.kind})]}),a.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-1",children:[a.jsx(M,{size:"sm",variant:"ghost",disabled:!o||r,loading:r,onClick:()=>void u(h=>n.cancelBackgroundTask(h)),children:"Cancel"}),a.jsx(M,{size:"sm",variant:"ghost",disabled:!c||r,loading:r,onClick:()=>void u(h=>n.retryBackgroundTask(h)),children:"Retry"})]})]}),s&&a.jsx("p",{role:"alert",className:"mt-1 text-danger",children:s})]})}const Ka={aiProfiles:"Profils IA",devices:"Appareils"};function a4({session:e}={}){const t=e??ow(),[n,r]=g.useState(()=>t.isPaired()),[i,s]=g.useState(!1),[l,o]=g.useState(null),[c,u]=g.useState(!1);g.useEffect(()=>t.onUnauthorized(()=>{o(null),u(!1),r(!1)}),[t]);async function h(){if(!i){s(!0);try{await t.logout()}finally{sx(),s(!1),o(null),u(!1),r(!1)}}}const d=g.useCallback(()=>{t.forget(),sx(),o(null),u(!1),r(!1)},[t]);return a.jsxs("div",{className:"flex h-full flex-col bg-canvas text-content",children:[a.jsxs("header",{"data-testid":"web-header",className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:px-6",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("h1",{className:"text-base font-semibold tracking-tight sm:text-lg",children:"IdeA"}),a.jsx("span",{className:"rounded-md bg-raised px-1.5 py-0.5 text-[0.65rem] font-medium uppercase text-muted",children:"web"})]}),n&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(M,{variant:"ghost",size:"sm","aria-pressed":c,onClick:()=>u(!0),children:"Paramètres"}),a.jsx(M,{variant:"ghost",size:"sm",loading:i,onClick:()=>void h(),children:"Se déconnecter"})]})]}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:n?l==="aiProfiles"?a.jsx(Xv,{title:Ka.aiProfiles,onBack:()=>o(null),children:a.jsx(kw,{})}):l==="devices"?a.jsx(Xv,{title:Ka.devices,onBack:()=>o(null),children:a.jsx(Nw,{onSessionEnded:d})}):a.jsx(JB,{}):a.jsx(RB,{session:t,onPaired:()=>r(!0)})}),c&&a.jsx(u0,{title:"Paramètres",onClose:()=>u(!1),entries:[{id:"aiProfiles",label:Ka.aiProfiles,active:l==="aiProfiles",onSelect:()=>{o("aiProfiles"),u(!1)}},{id:"devices",label:Ka.devices,active:l==="devices",onSelect:()=>{o("devices"),u(!1)}},{id:"deployment",label:"Déploiement",active:!1,disabled:!0,secondaryLabel:"Desktop uniquement",hint:"Desktop uniquement",onSelect:()=>{}}]})]})}function Xv({title:e,onBack:t,children:n}){return a.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-2 pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))]",children:[a.jsx(M,{variant:"ghost",size:"sm",onClick:t,children:"← Retour"}),a.jsx("span",{className:"text-sm font-medium text-content",children:e})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4 pb-[max(1rem,env(safe-area-inset-bottom))] pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:p-6",children:a.jsx("div",{className:"mx-auto w-full max-w-xl",children:n})})]})}const d0=document.getElementById("root");if(!d0)throw new Error("missing #root element");const Qv=TB(window.location.search);window.__IDEA_TRANSPORT__="http";const o4=uw()==="http";nd.createRoot(d0).render(a.jsx(P0.StrictMode,{children:a.jsx(uP,{children:o4?a.jsx(a4,{}):Qv?a.jsx(LB,{panel:Qv.panel}):a.jsx(EB,{})})})); diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-voyD2-fw.css b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-voyD2-fw.css deleted file mode 100644 index dee6250..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/assets/index-voyD2-fw.css +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2014 The xterm.js authors. All rights reserved. - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * https://github.com/chjj/term.js - * @license MIT - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - * The original design remains. The terminal itself - * has been extended to include xterm CSI codes, among - * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;inset:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;inset:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--font-mono:"JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-normal:0em;--tracking-wide:.025em;--radius-md:.375rem;--radius-lg:.5rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-canvas:#0e1116;--color-surface:#161b22;--color-raised:#1c2430;--color-border:#2b3440;--color-border-strong:#3b4757;--color-content:#e6edf3;--color-muted:#9aa7b4;--color-faint:#6b7785;--color-primary:#4c8dff;--color-primary-hover:#3b7bf0;--color-on-primary:#fff;--color-danger:#f85149;--color-success:#3fb950;--color-warning:#d29922}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}:root{color-scheme:dark}html,body,#root{height:100%}@supports (height:100dvh){html,body,#root{height:100dvh}}body{background-color:var(--color-canvas);color:var(--color-content);font-family:var(--font-sans);-webkit-font-smoothing:antialiased;overscroll-behavior-y:none;margin:0}:focus-visible{outline:2px solid var(--color-primary);outline-offset:1px}}@layer components;@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing) * 0)}.top-0{top:calc(var(--spacing) * 0)}.top-full{top:100%}.right-0{right:calc(var(--spacing) * 0)}.right-4{right:calc(var(--spacing) * 4)}.bottom-0{bottom:calc(var(--spacing) * 0)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:calc(var(--spacing) * 0)}.left-full{left:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[4\]{z-index:4}.z-\[60\]{z-index:60}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-auto{margin:auto}.-mx-4{margin-inline:calc(var(--spacing) * -4)}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.-mb-4{margin-bottom:calc(var(--spacing) * -4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.size-1\.5{width:calc(var(--spacing) * 1.5);height:calc(var(--spacing) * 1.5)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-4{height:calc(var(--spacing) * 4)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-32{height:calc(var(--spacing) * 32)}.h-64{height:calc(var(--spacing) * 64)}.h-96{height:calc(var(--spacing) * 96)}.h-\[60dvh\]{height:60dvh}.h-full{height:100%}.max-h-40{max-height:calc(var(--spacing) * 40)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[80vh\]{max-height:80vh}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-10{min-height:calc(var(--spacing) * 10)}.min-h-11{min-height:calc(var(--spacing) * 11)}.min-h-20{min-height:calc(var(--spacing) * 20)}.min-h-24{min-height:calc(var(--spacing) * 24)}.min-h-32{min-height:calc(var(--spacing) * 32)}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-64{min-height:calc(var(--spacing) * 64)}.min-h-\[32px\]{min-height:32px}.min-h-\[40px\]{min-height:40px}.min-h-\[44px\]{min-height:44px}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-3{width:calc(var(--spacing) * 3)}.w-4{width:calc(var(--spacing) * 4)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-24{width:calc(var(--spacing) * 24)}.w-28{width:calc(var(--spacing) * 28)}.w-40{width:calc(var(--spacing) * 40)}.w-48{width:calc(var(--spacing) * 48)}.w-52{width:calc(var(--spacing) * 52)}.w-80{width:calc(var(--spacing) * 80)}.w-fit{width:fit-content}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[80\%\]{max-width:80%}.max-w-\[85\%\]{max-width:85%}.max-w-\[520px\]{max-width:520px}.max-w-\[calc\(100vw-2rem\)\]{max-width:calc(100vw - 2rem)}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-32{min-width:calc(var(--spacing) * 32)}.min-w-36{min-width:calc(var(--spacing) * 36)}.min-w-44{min-width:calc(var(--spacing) * 44)}.min-w-48{min-width:calc(var(--spacing) * 48)}.min-w-80{min-width:calc(var(--spacing) * 80)}.min-w-\[6rem\]{min-width:6rem}.min-w-\[8rem\]{min-width:8rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[440px\]{min-width:440px}.min-w-max{min-width:max-content}.flex-1{flex:1}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-col-resize{cursor:col-resize}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-\[4\.5rem_1fr\]{grid-template-columns:4.5rem 1fr}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0{gap:calc(var(--spacing) * 0)}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-border>:not(:last-child)){border-color:var(--color-border)}.self-end{align-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-md{border-top-left-radius:var(--radius-md);border-top-right-radius:var(--radius-md)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-border{border-color:var(--color-border)}.border-border-strong{border-color:var(--color-border-strong)}.border-border\/50{border-color:#2b344080}@supports (color:color-mix(in lab,red,red)){.border-border\/50{border-color:color-mix(in oklab,var(--color-border) 50%,transparent)}}.border-border\/60{border-color:#2b344099}@supports (color:color-mix(in lab,red,red)){.border-border\/60{border-color:color-mix(in oklab,var(--color-border) 60%,transparent)}}.border-border\/70{border-color:#2b3440b3}@supports (color:color-mix(in lab,red,red)){.border-border\/70{border-color:color-mix(in oklab,var(--color-border) 70%,transparent)}}.border-current{border-color:currentColor}.border-danger{border-color:var(--color-danger)}.border-danger\/40{border-color:#f8514966}@supports (color:color-mix(in lab,red,red)){.border-danger\/40{border-color:color-mix(in oklab,var(--color-danger) 40%,transparent)}}.border-primary{border-color:var(--color-primary)}.border-primary\/20{border-color:#4c8dff33}@supports (color:color-mix(in lab,red,red)){.border-primary\/20{border-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.border-primary\/25{border-color:#4c8dff40}@supports (color:color-mix(in lab,red,red)){.border-primary\/25{border-color:color-mix(in oklab,var(--color-primary) 25%,transparent)}}.border-primary\/30{border-color:#4c8dff4d}@supports (color:color-mix(in lab,red,red)){.border-primary\/30{border-color:color-mix(in oklab,var(--color-primary) 30%,transparent)}}.border-primary\/40{border-color:#4c8dff66}@supports (color:color-mix(in lab,red,red)){.border-primary\/40{border-color:color-mix(in oklab,var(--color-primary) 40%,transparent)}}.border-transparent{border-color:#0000}.border-warning\/40{border-color:#d2992266}@supports (color:color-mix(in lab,red,red)){.border-warning\/40{border-color:color-mix(in oklab,var(--color-warning) 40%,transparent)}}.border-t-transparent{border-top-color:#0000}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-black\/55{background-color:#0000008c}@supports (color:color-mix(in lab,red,red)){.bg-black\/55{background-color:color-mix(in oklab,var(--color-black) 55%,transparent)}}.bg-border{background-color:var(--color-border)}.bg-canvas{background-color:var(--color-canvas)}.bg-canvas\/85{background-color:#0e1116d9}@supports (color:color-mix(in lab,red,red)){.bg-canvas\/85{background-color:color-mix(in oklab,var(--color-canvas) 85%,transparent)}}.bg-danger{background-color:var(--color-danger)}.bg-danger\/10{background-color:#f851491a}@supports (color:color-mix(in lab,red,red)){.bg-danger\/10{background-color:color-mix(in oklab,var(--color-danger) 10%,transparent)}}.bg-danger\/15{background-color:#f8514926}@supports (color:color-mix(in lab,red,red)){.bg-danger\/15{background-color:color-mix(in oklab,var(--color-danger) 15%,transparent)}}.bg-danger\/20{background-color:#f8514933}@supports (color:color-mix(in lab,red,red)){.bg-danger\/20{background-color:color-mix(in oklab,var(--color-danger) 20%,transparent)}}.bg-faint{background-color:var(--color-faint)}.bg-muted\/15{background-color:#9aa7b426}@supports (color:color-mix(in lab,red,red)){.bg-muted\/15{background-color:color-mix(in oklab,var(--color-muted) 15%,transparent)}}.bg-muted\/20{background-color:#9aa7b433}@supports (color:color-mix(in lab,red,red)){.bg-muted\/20{background-color:color-mix(in oklab,var(--color-muted) 20%,transparent)}}.bg-primary{background-color:var(--color-primary)}.bg-primary\/5{background-color:#4c8dff0d}@supports (color:color-mix(in lab,red,red)){.bg-primary\/5{background-color:color-mix(in oklab,var(--color-primary) 5%,transparent)}}.bg-primary\/10{background-color:#4c8dff1a}@supports (color:color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}}.bg-primary\/15{background-color:#4c8dff26}@supports (color:color-mix(in lab,red,red)){.bg-primary\/15{background-color:color-mix(in oklab,var(--color-primary) 15%,transparent)}}.bg-primary\/20{background-color:#4c8dff33}@supports (color:color-mix(in lab,red,red)){.bg-primary\/20{background-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.bg-raised{background-color:var(--color-raised)}.bg-raised\/40{background-color:#1c243066}@supports (color:color-mix(in lab,red,red)){.bg-raised\/40{background-color:color-mix(in oklab,var(--color-raised) 40%,transparent)}}.bg-raised\/50{background-color:#1c243080}@supports (color:color-mix(in lab,red,red)){.bg-raised\/50{background-color:color-mix(in oklab,var(--color-raised) 50%,transparent)}}.bg-success{background-color:var(--color-success)}.bg-success\/10{background-color:#3fb9501a}@supports (color:color-mix(in lab,red,red)){.bg-success\/10{background-color:color-mix(in oklab,var(--color-success) 10%,transparent)}}.bg-success\/15{background-color:#3fb95026}@supports (color:color-mix(in lab,red,red)){.bg-success\/15{background-color:color-mix(in oklab,var(--color-success) 15%,transparent)}}.bg-success\/20{background-color:#3fb95033}@supports (color:color-mix(in lab,red,red)){.bg-success\/20{background-color:color-mix(in oklab,var(--color-success) 20%,transparent)}}.bg-surface{background-color:var(--color-surface)}.bg-surface\/60{background-color:#161b2299}@supports (color:color-mix(in lab,red,red)){.bg-surface\/60{background-color:color-mix(in oklab,var(--color-surface) 60%,transparent)}}.bg-surface\/80{background-color:#161b22cc}@supports (color:color-mix(in lab,red,red)){.bg-surface\/80{background-color:color-mix(in oklab,var(--color-surface) 80%,transparent)}}.bg-warning{background-color:var(--color-warning)}.bg-warning\/10{background-color:#d299221a}@supports (color:color-mix(in lab,red,red)){.bg-warning\/10{background-color:color-mix(in oklab,var(--color-warning) 10%,transparent)}}.bg-warning\/15{background-color:#d2992226}@supports (color:color-mix(in lab,red,red)){.bg-warning\/15{background-color:color-mix(in oklab,var(--color-warning) 15%,transparent)}}.bg-warning\/20{background-color:#d2992233}@supports (color:color-mix(in lab,red,red)){.bg-warning\/20{background-color:color-mix(in oklab,var(--color-warning) 20%,transparent)}}.fill-canvas{fill:var(--color-canvas)}.p-0{padding:calc(var(--spacing) * 0)}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-10{padding-block:calc(var(--spacing) * 10)}.pt-1{padding-top:calc(var(--spacing) * 1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-\[max\(0\.75rem\,env\(safe-area-inset-top\)\)\]{padding-top:max(.75rem,env(safe-area-inset-top))}.pr-\[max\(1rem\,env\(safe-area-inset-right\)\)\]{padding-right:max(1rem,env(safe-area-inset-right))}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pb-\[max\(0\.5rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.5rem,env(safe-area-inset-bottom))}.pb-\[max\(0\.75rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(.75rem,env(safe-area-inset-bottom))}.pb-\[max\(1rem\,env\(safe-area-inset-bottom\)\)\]{padding-bottom:max(1rem,env(safe-area-inset-bottom))}.pl-1{padding-left:calc(var(--spacing) * 1)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-\[max\(1rem\,env\(safe-area-inset-left\)\)\]{padding-left:max(1rem,env(safe-area-inset-left))}.text-center{text-align:center}.text-left{text-align:left}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[0\.6rem\]{font-size:.6rem}.text-\[0\.7rem\]{font-size:.7rem}.text-\[0\.65rem\]{font-size:.65rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.2em\]{--tw-tracking:.2em;letter-spacing:.2em}.tracking-normal{--tw-tracking:var(--tracking-normal);letter-spacing:var(--tracking-normal)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.text-content{color:var(--color-content)}.text-content\/90{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.text-content\/90{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.text-danger{color:var(--color-danger)}.text-danger\/80{color:#f85149cc}@supports (color:color-mix(in lab,red,red)){.text-danger\/80{color:color-mix(in oklab,var(--color-danger) 80%,transparent)}}.text-faint{color:var(--color-faint)}.text-muted{color:var(--color-muted)}.text-on-primary{color:var(--color-on-primary)}.text-primary{color:var(--color-primary)}.text-success{color:var(--color-success)}.text-transparent{color:#0000}.text-warning{color:var(--color-warning)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.normal-case{text-transform:none}.uppercase{text-transform:uppercase}.italic{font-style:italic}.underline{text-decoration-line:underline}.accent-primary{accent-color:var(--color-primary)}.opacity-20{opacity:.2}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-border-strong{--tw-ring-color:var(--color-border-strong)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.placeholder\:text-faint::placeholder{color:var(--color-faint)}.first\:pt-0:first-child{padding-top:calc(var(--spacing) * 0)}.last\:border-r-0:last-child{border-right-style:var(--tw-border-style);border-right-width:0}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.last\:pb-0:last-child{padding-bottom:calc(var(--spacing) * 0)}@media (hover:hover){.hover\:border-border:hover{border-color:var(--color-border)}.hover\:border-border-strong:hover{border-color:var(--color-border-strong)}.hover\:border-primary:hover{border-color:var(--color-primary)}.hover\:bg-border-strong:hover{background-color:var(--color-border-strong)}.hover\:bg-canvas:hover{background-color:var(--color-canvas)}.hover\:bg-primary-hover:hover{background-color:var(--color-primary-hover)}.hover\:bg-primary\/15:hover{background-color:#4c8dff26}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/15:hover{background-color:color-mix(in oklab,var(--color-primary) 15%,transparent)}}.hover\:bg-raised:hover{background-color:var(--color-raised)}.hover\:text-content:hover{color:var(--color-content)}.hover\:text-danger:hover{color:var(--color-danger)}.hover\:text-muted:hover{color:var(--color-muted)}.hover\:text-primary:hover{color:var(--color-primary)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:brightness-110:hover{--tw-brightness:brightness(110%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}}.focus\:border-primary:focus{border-color:var(--color-primary)}.focus\:bg-raised:focus{background-color:var(--color-raised)}.focus\:ring-1:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-primary:focus{--tw-ring-color:var(--color-primary)}.focus\:outline-none:focus,.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}@media (hover:hover){.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}.aria-pressed\:border-primary[aria-pressed=true]{border-color:var(--color-primary)}@media (min-width:40rem){.sm\:h-80{height:calc(var(--spacing) * 80)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:calc(var(--spacing) * 2)}.sm\:p-6{padding:calc(var(--spacing) * 6)}.sm\:px-6{padding-inline:calc(var(--spacing) * 6)}.sm\:text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.sm\:text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}}@media (min-width:48rem){.md\:w-56{width:calc(var(--spacing) * 56)}.md\:flex-row{flex-direction:row}}.\[\&_a\]\:text-primary a{color:var(--color-primary)}.\[\&_a\:hover\]\:underline a:hover{text-decoration-line:underline}.\[\&_blockquote\]\:border-l-2 blockquote{border-left-style:var(--tw-border-style);border-left-width:2px}.\[\&_blockquote\]\:border-primary blockquote{border-color:var(--color-primary)}.\[\&_blockquote\]\:text-muted blockquote{color:var(--color-muted)}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-canvas code{background-color:var(--color-canvas)}.\[\&_code\]\:px-1 code{padding-inline:calc(var(--spacing) * 1)}.\[\&_code\]\:text-primary code{color:var(--color-primary)}.\[\&_h1\]\:text-content h1,.\[\&_h2\]\:text-content h2,.\[\&_h3\]\:text-content h3{color:var(--color-content)}.\[\&_hr\]\:border-border hr{border-color:var(--color-border)}.\[\&_li\]\:text-content\/90 li{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.\[\&_li\]\:text-content\/90 li{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.\[\&_p\]\:text-content\/90 p{color:#e6edf3e6}@supports (color:color-mix(in lab,red,red)){.\[\&_p\]\:text-content\/90 p{color:color-mix(in oklab,var(--color-content) 90%,transparent)}}.\[\&_pre\]\:rounded-md pre{border-radius:var(--radius-md)}.\[\&_pre\]\:border pre{border-style:var(--tw-border-style);border-width:1px}.\[\&_pre\]\:border-border pre{border-color:var(--color-border)}.\[\&_pre\]\:bg-canvas pre{background-color:var(--color-canvas)}}@keyframes model-server-indeterminate{0%{left:-40%}to{left:100%}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}} diff --git a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/index.html b/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/index.html deleted file mode 100644 index 1afc32f..0000000 --- a/target/release/bundle/appimage/IdeA.AppDir/usr/lib/IdeA/web/index.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - IdeA - - - - -
- - diff --git a/target/release/bundle/appimage/IdeA_0.3.0_amd64.AppImage b/target/release/bundle/appimage/IdeA_0.3.0_amd64.AppImage deleted file mode 100755 index 07f2009..0000000 Binary files a/target/release/bundle/appimage/IdeA_0.3.0_amd64.AppImage and /dev/null differ