From 35e51ab32b64ca7cb468ff749da35a5085ab5c90 Mon Sep 17 00:00:00 2001 From: Jack Rothrock Date: Fri, 4 Sep 2026 17:01:03 -0600 Subject: [PATCH 1/2] fix(chat): don't yank the view down while reading during a stream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chat force-scrolled to the bottom on every streamed frame, so reading earlier output mid-turn kept snapping you back down. Stick-to-bottom now: scroll() only auto-scrolls when the user is at/near the bottom. A user scroll-up clears the intent (onScroll → stickRef=false); our own programmatic autoscroll is guarded so it doesn't re-arm the intent. Sending your own message re-sticks (you follow it). Measured against the live DOM each frame so a growing transcript can't strand a stale value. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../app-src/src/components/ChatPanel.tsx | 34 +++++++++- .../{index-BgodMaKm.js => index-ClsO5wVY.js} | 68 +++++++++---------- .../dashboard/webui/static/app/index.html | 2 +- 3 files changed, 67 insertions(+), 37 deletions(-) rename internal/dashboard/webui/static/app/assets/{index-BgodMaKm.js => index-ClsO5wVY.js} (85%) diff --git a/internal/dashboard/webui/app-src/src/components/ChatPanel.tsx b/internal/dashboard/webui/app-src/src/components/ChatPanel.tsx index be7df60..0d4de42 100644 --- a/internal/dashboard/webui/app-src/src/components/ChatPanel.tsx +++ b/internal/dashboard/webui/app-src/src/components/ChatPanel.tsx @@ -122,9 +122,36 @@ export function ChatPanel({ const curAssistantIdx = useRef(null); const lastToolIdx = useRef(null); + // Stick-to-bottom autoscroll: only auto-scroll when the user is already at (or + // near) the bottom. If they've scrolled UP to read earlier output, a streaming + // frame must NOT yank them back down. + // + // stickRef is the intent, updated ONLY by real user scrolling (onLogScroll): at + // the bottom → stick=true; scrolled up → stick=false. scroll() re-affirms it + // synchronously (a programmatic jump we make ourselves shouldn't clear it) and + // bails when the user is reading above. Measured against the LIVE DOM each call + // so a growing transcript can't strand a stale value. + const stickRef = useRef(true); + const nearBottom = (el: HTMLDivElement) => el.scrollHeight - el.scrollTop - el.clientHeight < 60; + const programmaticScroll = useRef(false); + const onLogScroll = useCallback(() => { + // Ignore the scroll events our own autoscroll causes; only USER scrolls should + // change the stick intent. + if (programmaticScroll.current) return; + const el = logRef.current; + if (el) stickRef.current = nearBottom(el); + }, []); const scroll = useCallback(() => { + const el = logRef.current; + if (!el || !stickRef.current) return; // reading above → leave them alone requestAnimationFrame(() => { - if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; + if (!logRef.current) return; + programmaticScroll.current = true; + logRef.current.scrollTop = logRef.current.scrollHeight; + // Clear the guard after the resulting scroll event has fired. + requestAnimationFrame(() => { + programmaticScroll.current = false; + }); }); }, []); @@ -275,6 +302,9 @@ export function ChatPanel({ setMsgs((m) => [...m, { role: "user", html: renderMarkdown(text) }]); wsRef.current.send(JSON.stringify({ prompt: text, ctx: getCtx?.() || "" })); setBusy(true); + // Sending your own message always follows it to the bottom, even if you'd + // scrolled up before. + stickRef.current = true; scroll(); }, [getCtx, scroll], @@ -344,7 +374,7 @@ export function ChatPanel({ )} -
+
{msgs.map((m, i) => { if (m.role === "meta") return ( diff --git a/internal/dashboard/webui/static/app/assets/index-BgodMaKm.js b/internal/dashboard/webui/static/app/assets/index-ClsO5wVY.js similarity index 85% rename from internal/dashboard/webui/static/app/assets/index-BgodMaKm.js rename to internal/dashboard/webui/static/app/assets/index-ClsO5wVY.js index 759b6e6..004c224 100644 --- a/internal/dashboard/webui/static/app/assets/index-BgodMaKm.js +++ b/internal/dashboard/webui/static/app/assets/index-ClsO5wVY.js @@ -22,7 +22,7 @@ var Jd=Object.defineProperty;var Yd=(e,t,r)=>t in e?Jd(e,t,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */(function(e){function t($,R){var D=$.length;$.push(R);e:for(;0>>1,P=$[M];if(0>>1;Mi(H,D))Ji(I,H)?($[M]=I,$[J]=D,M=J):($[M]=H,$[Y]=D,M=Y);else if(Ji(I,D))$[M]=I,$[J]=D,M=J;else break e}}return R}function i($,R){var D=$.sortIndex-R.sortIndex;return D!==0?D:$.id-R.id}if(typeof performance=="object"&&typeof performance.now=="function"){var h=performance;e.unstable_now=function(){return h.now()}}else{var y=Date,o=y.now();e.unstable_now=function(){return y.now()-o}}var u=[],d=[],m=1,f=null,g=3,w=!1,S=!1,v=!1,p=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,a=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function l($){for(var R=r(d);R!==null;){if(R.callback===null)n(d);else if(R.startTime<=$)n(d),R.sortIndex=R.expirationTime,t(u,R);else break;R=r(d)}}function _($){if(v=!1,l($),!S)if(r(u)!==null)S=!0,z(j);else{var R=r(d);R!==null&&K(_,R.startTime-$)}}function j($,R){S=!1,v&&(v=!1,c(x),x=-1),w=!0;var D=g;try{for(l(R),f=r(u);f!==null&&(!(f.expirationTime>R)||$&&!L());){var M=f.callback;if(typeof M=="function"){f.callback=null,g=f.priorityLevel;var P=M(f.expirationTime<=R);R=e.unstable_now(),typeof P=="function"?f.callback=P:f===r(u)&&n(u),l(R)}else n(u);f=r(u)}if(f!==null)var U=!0;else{var Y=r(d);Y!==null&&K(_,Y.startTime-R),U=!1}return U}finally{f=null,g=D,w=!1}}var b=!1,k=null,x=-1,N=5,E=-1;function L(){return!(e.unstable_now()-E$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return g},e.unstable_getFirstCallbackNode=function(){return r(u)},e.unstable_next=function($){switch(g){case 1:case 2:case 3:var R=3;break;default:R=g}var D=g;g=R;try{return $()}finally{g=D}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function($,R){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var D=g;g=$;try{return R()}finally{g=D}},e.unstable_scheduleCallback=function($,R,D){var M=e.unstable_now();switch(typeof D=="object"&&D!==null?(D=D.delay,D=typeof D=="number"&&0M?($.sortIndex=D,t(d,$),r(u)===null&&$===r(d)&&(v?(c(x),x=-1):v=!0,K(_,D-M))):($.sortIndex=P,t(u,$),S||w||(S=!0,z(j))),$},e.unstable_shouldYield=L,e.unstable_wrapCallback=function($){var R=g;return function(){var D=g;g=R;try{return $.apply(this,arguments)}finally{g=D}}}})(vu);gu.exports=vu;var yf=gu.exports;/** + */(function(e){function t($,R){var A=$.length;$.push(R);e:for(;0>>1,O=$[M];if(0>>1;Mi(z,A))Xi(I,z)?($[M]=I,$[X]=A,M=X):($[M]=z,$[F]=A,M=F);else if(Xi(I,A))$[M]=I,$[X]=A,M=X;else break e}}return R}function i($,R){var A=$.sortIndex-R.sortIndex;return A!==0?A:$.id-R.id}if(typeof performance=="object"&&typeof performance.now=="function"){var h=performance;e.unstable_now=function(){return h.now()}}else{var y=Date,o=y.now();e.unstable_now=function(){return y.now()-o}}var u=[],d=[],m=1,f=null,g=3,w=!1,S=!1,v=!1,p=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,a=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function l($){for(var R=r(d);R!==null;){if(R.callback===null)n(d);else if(R.startTime<=$)n(d),R.sortIndex=R.expirationTime,t(u,R);else break;R=r(d)}}function _($){if(v=!1,l($),!S)if(r(u)!==null)S=!0,K(j);else{var R=r(d);R!==null&&q(_,R.startTime-$)}}function j($,R){S=!1,v&&(v=!1,c(x),x=-1),w=!0;var A=g;try{for(l(R),f=r(u);f!==null&&(!(f.expirationTime>R)||$&&!L());){var M=f.callback;if(typeof M=="function"){f.callback=null,g=f.priorityLevel;var O=M(f.expirationTime<=R);R=e.unstable_now(),typeof O=="function"?f.callback=O:f===r(u)&&n(u),l(R)}else n(u);f=r(u)}if(f!==null)var W=!0;else{var F=r(d);F!==null&&q(_,F.startTime-R),W=!1}return W}finally{f=null,g=A,w=!1}}var b=!1,k=null,x=-1,N=5,E=-1;function L(){return!(e.unstable_now()-E$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return g},e.unstable_getFirstCallbackNode=function(){return r(u)},e.unstable_next=function($){switch(g){case 1:case 2:case 3:var R=3;break;default:R=g}var A=g;g=R;try{return $()}finally{g=A}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function($,R){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var A=g;g=$;try{return R()}finally{g=A}},e.unstable_scheduleCallback=function($,R,A){var M=e.unstable_now();switch(typeof A=="object"&&A!==null?(A=A.delay,A=typeof A=="number"&&0M?($.sortIndex=A,t(d,$),r(u)===null&&$===r(d)&&(v?(c(x),x=-1):v=!0,q(_,A-M))):($.sortIndex=O,t(u,$),S||w||(S=!0,K(j))),$},e.unstable_shouldYield=L,e.unstable_wrapCallback=function($){var R=g;return function(){var A=g;g=R;try{return $.apply(this,arguments)}finally{g=A}}}})(vu);gu.exports=vu;var yf=gu.exports;/** * @license React * react-dom.production.min.js * @@ -39,48 +39,48 @@ var Jd=Object.defineProperty;var Yd=(e,t,r)=>t in e?Jd(e,t,{enumerable:!0,config Error generating stack: `+h.message+` `+h.stack}return{value:e,source:t,stack:i,digest:null}}function io(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function Go(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var Qp=typeof WeakMap=="function"?WeakMap:Map;function Uh(e,t,r){r=Mt(-1,r),r.tag=3,r.payload={element:null};var n=t.value;return r.callback=function(){di||(di=!0,na=n),Go(e,t)},r}function zh(e,t,r){r=Mt(-1,r),r.tag=3;var n=e.type.getDerivedStateFromError;if(typeof n=="function"){var i=t.value;r.payload=function(){return n(i)},r.callback=function(){Go(e,t)}}var h=e.stateNode;return h!==null&&typeof h.componentDidCatch=="function"&&(r.callback=function(){Go(e,t),typeof n!="function"&&(rs===null?rs=new Set([this]):rs.add(this));var y=t.stack;this.componentDidCatch(t.value,{componentStack:y!==null?y:""})}),r}function oc(e,t,r){var n=e.pingCache;if(n===null){n=e.pingCache=new Qp;var i=new Set;n.set(t,i)}else i=n.get(t),i===void 0&&(i=new Set,n.set(t,i));i.has(r)||(i.add(r),e=dm.bind(null,e,t,r),t.then(e,e))}function ac(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function lc(e,t,r,n,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Mt(-1,1),t.tag=2,ss(r,t,1))),r.lanes|=1),e)}var Zp=Ft.ReactCurrentOwner,qe=!1;function Ue(e,t,r,n){t.child=e===null?_h(t,null,r,n):rr(t,e.child,r,n)}function cc(e,t,r,n,i){r=r.render;var h=t.ref;return Ys(t,i),n=Ka(e,t,r,n,h,i),r=Va(),e!==null&&!qe?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Ht(e,t,i)):(ve&&r&&Ta(t),t.flags|=1,Ue(e,t,n,i),t.child)}function uc(e,t,r,n,i){if(e===null){var h=r.type;return typeof h=="function"&&!sl(h)&&h.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=h,Wh(e,t,h,n,i)):(e=Fn(r.type,null,n,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(h=e.child,!(e.lanes&i)){var y=h.memoizedProps;if(r=r.compare,r=r!==null?r:zr,r(y,n)&&e.ref===t.ref)return Ht(e,t,i)}return t.flags|=1,e=is(h,n),e.ref=t.ref,e.return=t,t.child=e}function Wh(e,t,r,n,i){if(e!==null){var h=e.memoizedProps;if(zr(h,n)&&e.ref===t.ref)if(qe=!1,t.pendingProps=n=h,(e.lanes&i)!==0)e.flags&131072&&(qe=!0);else return t.lanes=e.lanes,Ht(e,t,i)}return Jo(e,t,r,n,i)}function Kh(e,t,r){var n=t.pendingProps,i=n.children,h=e!==null?e.memoizedState:null;if(n.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},fe(Ks,Qe),Qe|=r;else{if(!(r&1073741824))return e=h!==null?h.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,fe(Ks,Qe),Qe|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=h!==null?h.baseLanes:r,fe(Ks,Qe),Qe|=n}else h!==null?(n=h.baseLanes|r,t.memoizedState=null):n=r,fe(Ks,Qe),Qe|=n;return Ue(e,t,i,r),t.child}function Vh(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function Jo(e,t,r,n,i){var h=Je(r)?ws:Fe.current;return h=tr(t,h),Ys(t,i),r=Ka(e,t,r,n,h,i),n=Va(),e!==null&&!qe?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Ht(e,t,i)):(ve&&n&&Ta(t),t.flags|=1,Ue(e,t,r,i),t.child)}function hc(e,t,r,n,i){if(Je(r)){var h=!0;si(t)}else h=!1;if(Ys(t,i),t.stateNode===null)Bn(e,t),Fh(t,r,n),qo(t,r,n,i),n=!0;else if(e===null){var y=t.stateNode,o=t.memoizedProps;y.props=o;var u=y.context,d=r.contextType;typeof d=="object"&&d!==null?d=ut(d):(d=Je(r)?ws:Fe.current,d=tr(t,d));var m=r.getDerivedStateFromProps,f=typeof m=="function"||typeof y.getSnapshotBeforeUpdate=="function";f||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(o!==n||u!==d)&&ic(t,y,n,d),Vt=!1;var g=t.memoizedState;y.state=g,ai(t,n,y,i),u=t.memoizedState,o!==n||g!==u||Ge.current||Vt?(typeof m=="function"&&(Vo(t,r,m,n),u=t.memoizedState),(o=Vt||nc(t,r,o,n,g,u,d))?(f||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount()),typeof y.componentDidMount=="function"&&(t.flags|=4194308)):(typeof y.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=n,t.memoizedState=u),y.props=n,y.state=u,y.context=d,n=o):(typeof y.componentDidMount=="function"&&(t.flags|=4194308),n=!1)}else{y=t.stateNode,xh(e,t),o=t.memoizedProps,d=t.type===t.elementType?o:mt(t.type,o),y.props=d,f=t.pendingProps,g=y.context,u=r.contextType,typeof u=="object"&&u!==null?u=ut(u):(u=Je(r)?ws:Fe.current,u=tr(t,u));var w=r.getDerivedStateFromProps;(m=typeof w=="function"||typeof y.getSnapshotBeforeUpdate=="function")||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(o!==f||g!==u)&&ic(t,y,n,u),Vt=!1,g=t.memoizedState,y.state=g,ai(t,n,y,i);var S=t.memoizedState;o!==f||g!==S||Ge.current||Vt?(typeof w=="function"&&(Vo(t,r,w,n),S=t.memoizedState),(d=Vt||nc(t,r,d,n,g,S,u)||!1)?(m||typeof y.UNSAFE_componentWillUpdate!="function"&&typeof y.componentWillUpdate!="function"||(typeof y.componentWillUpdate=="function"&&y.componentWillUpdate(n,S,u),typeof y.UNSAFE_componentWillUpdate=="function"&&y.UNSAFE_componentWillUpdate(n,S,u)),typeof y.componentDidUpdate=="function"&&(t.flags|=4),typeof y.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof y.componentDidUpdate!="function"||o===e.memoizedProps&&g===e.memoizedState||(t.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&g===e.memoizedState||(t.flags|=1024),t.memoizedProps=n,t.memoizedState=S),y.props=n,y.state=S,y.context=u,n=d):(typeof y.componentDidUpdate!="function"||o===e.memoizedProps&&g===e.memoizedState||(t.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||o===e.memoizedProps&&g===e.memoizedState||(t.flags|=1024),n=!1)}return Yo(e,t,r,n,h,i)}function Yo(e,t,r,n,i,h){Vh(e,t);var y=(t.flags&128)!==0;if(!n&&!y)return i&&Yl(t,r,!1),Ht(e,t,h);n=t.stateNode,Zp.current=t;var o=y&&typeof r.getDerivedStateFromError!="function"?null:n.render();return t.flags|=1,e!==null&&y?(t.child=rr(t,e.child,null,h),t.child=rr(t,null,o,h)):Ue(e,t,o,h),t.memoizedState=n.state,i&&Yl(t,r,!0),t.child}function qh(e){var t=e.stateNode;t.pendingContext?Jl(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Jl(e,t.context,!1),Fa(e,t.containerInfo)}function dc(e,t,r,n,i){return sr(),Oa(i),t.flags|=256,Ue(e,t,r,n),t.child}var Xo={dehydrated:null,treeContext:null,retryLane:0};function Qo(e){return{baseLanes:e,cachePool:null,transitions:null}}function Gh(e,t,r){var n=t.pendingProps,i=_e.current,h=!1,y=(t.flags&128)!==0,o;if((o=y)||(o=e!==null&&e.memoizedState===null?!1:(i&2)!==0),o?(h=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),fe(_e,i&1),e===null)return Wo(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(y=n.children,e=n.fallback,h?(n=t.mode,h=t.child,y={mode:"hidden",children:y},!(n&1)&&h!==null?(h.childLanes=0,h.pendingProps=y):h=Ni(y,n,0,null),e=Ss(e,n,r,null),h.return=t,e.return=t,h.sibling=e,t.child=h,t.child.memoizedState=Qo(r),t.memoizedState=Xo,e):Ja(t,y));if(i=e.memoizedState,i!==null&&(o=i.dehydrated,o!==null))return em(e,t,y,n,o,i,r);if(h){h=n.fallback,y=t.mode,i=e.child,o=i.sibling;var u={mode:"hidden",children:n.children};return!(y&1)&&t.child!==i?(n=t.child,n.childLanes=0,n.pendingProps=u,t.deletions=null):(n=is(i,u),n.subtreeFlags=i.subtreeFlags&14680064),o!==null?h=is(o,h):(h=Ss(h,y,r,null),h.flags|=2),h.return=t,n.return=t,n.sibling=h,t.child=n,n=h,h=t.child,y=e.child.memoizedState,y=y===null?Qo(r):{baseLanes:y.baseLanes|r,cachePool:null,transitions:y.transitions},h.memoizedState=y,h.childLanes=e.childLanes&~r,t.memoizedState=Xo,n}return h=e.child,e=h.sibling,n=is(h,{mode:"visible",children:n.children}),!(t.mode&1)&&(n.lanes=r),n.return=t,n.sibling=null,e!==null&&(r=t.deletions,r===null?(t.deletions=[e],t.flags|=16):r.push(e)),t.child=n,t.memoizedState=null,n}function Ja(e,t){return t=Ni({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function wn(e,t,r,n){return n!==null&&Oa(n),rr(t,e.child,null,r),e=Ja(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function em(e,t,r,n,i,h,y){if(r)return t.flags&256?(t.flags&=-257,n=io(Error(Z(422))),wn(e,t,y,n)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(h=n.fallback,i=t.mode,n=Ni({mode:"visible",children:n.children},i,0,null),h=Ss(h,i,y,null),h.flags|=2,n.return=t,h.return=t,n.sibling=h,t.child=n,t.mode&1&&rr(t,e.child,null,y),t.child.memoizedState=Qo(y),t.memoizedState=Xo,h);if(!(t.mode&1))return wn(e,t,y,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var o=n.dgst;return n=o,h=Error(Z(419)),n=io(h,n,void 0),wn(e,t,y,n)}if(o=(y&e.childLanes)!==0,qe||o){if(n=Ae,n!==null){switch(y&-y){case 4:i=2;break;case 16:i=8;break;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:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(n.suspendedLanes|y)?0:i,i!==0&&i!==h.retryLane&&(h.retryLane=i,$t(e,i),yt(n,e,i,-1))}return tl(),n=io(Error(Z(421))),wn(e,t,y,n)}return i.data==="$?"?(t.flags|=128,t.child=e.child,t=fm.bind(null,e),i._reactRetry=t,null):(e=h.treeContext,Ze=ts(i.nextSibling),et=t,ve=!0,vt=null,e!==null&&(ot[at++]=Pt,ot[at++]=Ot,ot[at++]=bs,Pt=e.id,Ot=e.overflow,bs=t),t=Ja(t,n.children),t.flags|=4096,t)}function fc(e,t,r){e.lanes|=t;var n=e.alternate;n!==null&&(n.lanes|=t),Ko(e.return,t,r)}function oo(e,t,r,n,i){var h=e.memoizedState;h===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:n,tail:r,tailMode:i}:(h.isBackwards=t,h.rendering=null,h.renderingStartTime=0,h.last=n,h.tail=r,h.tailMode=i)}function Jh(e,t,r){var n=t.pendingProps,i=n.revealOrder,h=n.tail;if(Ue(e,t,n.children,r),n=_e.current,n&2)n=n&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&fc(e,r,t);else if(e.tag===19)fc(e,r,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}n&=1}if(fe(_e,n),!(t.mode&1))t.memoizedState=null;else switch(i){case"forwards":for(r=t.child,i=null;r!==null;)e=r.alternate,e!==null&&li(e)===null&&(i=r),r=r.sibling;r=i,r===null?(i=t.child,t.child=null):(i=r.sibling,r.sibling=null),oo(t,!1,i,r,h);break;case"backwards":for(r=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&li(e)===null){t.child=i;break}e=i.sibling,i.sibling=r,r=i,i=e}oo(t,!0,r,null,h);break;case"together":oo(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Bn(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Ht(e,t,r){if(e!==null&&(t.dependencies=e.dependencies),ks|=t.lanes,!(r&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(Z(153));if(t.child!==null){for(e=t.child,r=is(e,e.pendingProps),t.child=r,r.return=t;e.sibling!==null;)e=e.sibling,r=r.sibling=is(e,e.pendingProps),r.return=t;r.sibling=null}return t.child}function tm(e,t,r){switch(t.tag){case 3:qh(t),sr();break;case 5:Sh(t);break;case 1:Je(t.type)&&si(t);break;case 4:Fa(t,t.stateNode.containerInfo);break;case 10:var n=t.type._context,i=t.memoizedProps.value;fe(ii,n._currentValue),n._currentValue=i;break;case 13:if(n=t.memoizedState,n!==null)return n.dehydrated!==null?(fe(_e,_e.current&1),t.flags|=128,null):r&t.child.childLanes?Gh(e,t,r):(fe(_e,_e.current&1),e=Ht(e,t,r),e!==null?e.sibling:null);fe(_e,_e.current&1);break;case 19:if(n=(r&t.childLanes)!==0,e.flags&128){if(n)return Jh(e,t,r);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),fe(_e,_e.current),n)break;return null;case 22:case 23:return t.lanes=0,Kh(e,t,r)}return Ht(e,t,r)}var Yh,Zo,Xh,Qh;Yh=function(e,t){for(var r=t.child;r!==null;){if(r.tag===5||r.tag===6)e.appendChild(r.stateNode);else if(r.tag!==4&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===t)break;for(;r.sibling===null;){if(r.return===null||r.return===t)return;r=r.return}r.sibling.return=r.return,r=r.sibling}};Zo=function(){};Xh=function(e,t,r,n){var i=e.memoizedProps;if(i!==n){e=t.stateNode,ys(Rt.current);var h=null;switch(r){case"input":i=So(e,i),n=So(e,n),h=[];break;case"select":i=xe({},i,{value:void 0}),n=xe({},n,{value:void 0}),h=[];break;case"textarea":i=Co(e,i),n=Co(e,n),h=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(e.onclick=ei)}jo(r,n);var y;r=null;for(d in i)if(!n.hasOwnProperty(d)&&i.hasOwnProperty(d)&&i[d]!=null)if(d==="style"){var o=i[d];for(y in o)o.hasOwnProperty(y)&&(r||(r={}),r[y]="")}else d!=="dangerouslySetInnerHTML"&&d!=="children"&&d!=="suppressContentEditableWarning"&&d!=="suppressHydrationWarning"&&d!=="autoFocus"&&(Mr.hasOwnProperty(d)?h||(h=[]):(h=h||[]).push(d,null));for(d in n){var u=n[d];if(o=i!=null?i[d]:void 0,n.hasOwnProperty(d)&&u!==o&&(u!=null||o!=null))if(d==="style")if(o){for(y in o)!o.hasOwnProperty(y)||u&&u.hasOwnProperty(y)||(r||(r={}),r[y]="");for(y in u)u.hasOwnProperty(y)&&o[y]!==u[y]&&(r||(r={}),r[y]=u[y])}else r||(h||(h=[]),h.push(d,r)),r=u;else d==="dangerouslySetInnerHTML"?(u=u?u.__html:void 0,o=o?o.__html:void 0,u!=null&&o!==u&&(h=h||[]).push(d,u)):d==="children"?typeof u!="string"&&typeof u!="number"||(h=h||[]).push(d,""+u):d!=="suppressContentEditableWarning"&&d!=="suppressHydrationWarning"&&(Mr.hasOwnProperty(d)?(u!=null&&d==="onScroll"&&me("scroll",e),h||o===u||(h=[])):(h=h||[]).push(d,u))}r&&(h=h||[]).push("style",r);var d=h;(t.updateQueue=d)&&(t.flags|=4)}};Qh=function(e,t,r,n){r!==n&&(t.flags|=4)};function _r(e,t){if(!ve)switch(e.tailMode){case"hidden":t=e.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?e.tail=null:r.sibling=null;break;case"collapsed":r=e.tail;for(var n=null;r!==null;)r.alternate!==null&&(n=r),r=r.sibling;n===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:n.sibling=null}}function $e(e){var t=e.alternate!==null&&e.alternate.child===e.child,r=0,n=0;if(t)for(var i=e.child;i!==null;)r|=i.lanes|i.childLanes,n|=i.subtreeFlags&14680064,n|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)r|=i.lanes|i.childLanes,n|=i.subtreeFlags,n|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=n,e.childLanes=r,t}function sm(e,t,r){var n=t.pendingProps;switch(Pa(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return $e(t),null;case 1:return Je(t.type)&&ti(),$e(t),null;case 3:return n=t.stateNode,nr(),ge(Ge),ge(Fe),za(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(e===null||e.child===null)&&(xn(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,vt!==null&&(aa(vt),vt=null))),Zo(e,t),$e(t),null;case 5:Ua(t);var i=ys(Gr.current);if(r=t.type,e!==null&&t.stateNode!=null)Xh(e,t,r,n,i),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!n){if(t.stateNode===null)throw Error(Z(166));return $e(t),null}if(e=ys(Rt.current),xn(t)){n=t.stateNode,r=t.type;var h=t.memoizedProps;switch(n[Nt]=t,n[Vr]=h,e=(t.mode&1)!==0,r){case"dialog":me("cancel",n),me("close",n);break;case"iframe":case"object":case"embed":me("load",n);break;case"video":case"audio":for(i=0;i<\/script>",e=e.removeChild(e.firstChild)):typeof n.is=="string"?e=y.createElement(r,{is:n.is}):(e=y.createElement(r),r==="select"&&(y=e,n.multiple?y.multiple=!0:n.size&&(y.size=n.size))):e=y.createElementNS(e,r),e[Nt]=t,e[Vr]=n,Yh(e,t,!1,!1),t.stateNode=e;e:{switch(y=No(r,n),r){case"dialog":me("cancel",e),me("close",e),i=n;break;case"iframe":case"object":case"embed":me("load",e),i=n;break;case"video":case"audio":for(i=0;ior&&(t.flags|=128,n=!0,_r(h,!1),t.lanes=4194304)}else{if(!n)if(e=li(y),e!==null){if(t.flags|=128,n=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),_r(h,!0),h.tail===null&&h.tailMode==="hidden"&&!y.alternate&&!ve)return $e(t),null}else 2*ke()-h.renderingStartTime>or&&r!==1073741824&&(t.flags|=128,n=!0,_r(h,!1),t.lanes=4194304);h.isBackwards?(y.sibling=t.child,t.child=y):(r=h.last,r!==null?r.sibling=y:t.child=y,h.last=y)}return h.tail!==null?(t=h.tail,h.rendering=t,h.tail=t.sibling,h.renderingStartTime=ke(),t.sibling=null,r=_e.current,fe(_e,n?r&1|2:r&1),t):($e(t),null);case 22:case 23:return el(),n=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Qe&1073741824&&($e(t),t.subtreeFlags&6&&(t.flags|=8192)):$e(t),null;case 24:return null;case 25:return null}throw Error(Z(156,t.tag))}function rm(e,t){switch(Pa(t),t.tag){case 1:return Je(t.type)&&ti(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return nr(),ge(Ge),ge(Fe),za(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Ua(t),null;case 13:if(ge(_e),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Z(340));sr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ge(_e),null;case 4:return nr(),null;case 10:return Ba(t.type._context),null;case 22:case 23:return el(),null;case 24:return null;default:return null}}var bn=!1,He=!1,nm=typeof WeakSet=="function"?WeakSet:Set,ne=null;function Ws(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){we(e,t,n)}else r.current=null}function ea(e,t,r){try{r()}catch(n){we(e,t,n)}}var pc=!1;function im(e,t){if(Io=Xn,e=rh(),Aa(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,h=n.focusNode;n=n.focusOffset;try{r.nodeType,h.nodeType}catch{r=null;break e}var y=0,o=-1,u=-1,d=0,m=0,f=e,g=null;t:for(;;){for(var w;f!==r||i!==0&&f.nodeType!==3||(o=y+i),f!==h||n!==0&&f.nodeType!==3||(u=y+n),f.nodeType===3&&(y+=f.nodeValue.length),(w=f.firstChild)!==null;)g=f,f=w;for(;;){if(f===e)break t;if(g===r&&++d===i&&(o=y),g===h&&++m===n&&(u=y),(w=f.nextSibling)!==null)break;f=g,g=f.parentNode}f=w}r=o===-1||u===-1?null:{start:o,end:u}}else r=null}r=r||{start:0,end:0}}else r=null;for(Bo={focusedElem:e,selectionRange:r},Xn=!1,ne=t;ne!==null;)if(t=ne,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ne=e;else for(;ne!==null;){t=ne;try{var S=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var v=S.memoizedProps,p=S.memoizedState,c=t.stateNode,a=c.getSnapshotBeforeUpdate(t.elementType===t.type?v:mt(t.type,v),p);c.__reactInternalSnapshotBeforeUpdate=a}break;case 3:var l=t.stateNode.containerInfo;l.nodeType===1?l.textContent="":l.nodeType===9&&l.documentElement&&l.removeChild(l.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Z(163))}}catch(_){we(t,t.return,_)}if(e=t.sibling,e!==null){e.return=t.return,ne=e;break}ne=t.return}return S=pc,pc=!1,S}function Tr(e,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&e)===e){var h=i.destroy;i.destroy=void 0,h!==void 0&&ea(t,r,h)}i=i.next}while(i!==n)}}function ki(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function ta(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function Zh(e){var t=e.alternate;t!==null&&(e.alternate=null,Zh(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Nt],delete t[Vr],delete t[Fo],delete t[Fp],delete t[Up])),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 ed(e){return e.tag===5||e.tag===3||e.tag===4}function mc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ed(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 sa(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=ei));else if(n!==4&&(e=e.child,e!==null))for(sa(e,t,r),e=e.sibling;e!==null;)sa(e,t,r),e=e.sibling}function ra(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(n!==4&&(e=e.child,e!==null))for(ra(e,t,r),e=e.sibling;e!==null;)ra(e,t,r),e=e.sibling}var Pe=null,gt=!1;function zt(e,t,r){for(r=r.child;r!==null;)td(e,t,r),r=r.sibling}function td(e,t,r){if(Et&&typeof Et.onCommitFiberUnmount=="function")try{Et.onCommitFiberUnmount(vi,r)}catch{}switch(r.tag){case 5:He||Ws(r,t);case 6:var n=Pe,i=gt;Pe=null,zt(e,t,r),Pe=n,gt=i,Pe!==null&&(gt?(e=Pe,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Pe.removeChild(r.stateNode));break;case 18:Pe!==null&&(gt?(e=Pe,r=r.stateNode,e.nodeType===8?Zi(e.parentNode,r):e.nodeType===1&&Zi(e,r),Fr(e)):Zi(Pe,r.stateNode));break;case 4:n=Pe,i=gt,Pe=r.stateNode.containerInfo,gt=!0,zt(e,t,r),Pe=n,gt=i;break;case 0:case 11:case 14:case 15:if(!He&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var h=i,y=h.destroy;h=h.tag,y!==void 0&&(h&2||h&4)&&ea(r,t,y),i=i.next}while(i!==n)}zt(e,t,r);break;case 1:if(!He&&(Ws(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(o){we(r,t,o)}zt(e,t,r);break;case 21:zt(e,t,r);break;case 22:r.mode&1?(He=(n=He)||r.memoizedState!==null,zt(e,t,r),He=n):zt(e,t,r);break;default:zt(e,t,r)}}function gc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new nm),t.forEach(function(n){var i=pm.bind(null,e,n);r.has(n)||(r.add(n),n.then(i,i))})}}function pt(e,t){var r=t.deletions;if(r!==null)for(var n=0;ni&&(i=y),n&=~h}if(n=i,n=ke()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*am(n/1960))-n,10e?16:e,Xt===null)var n=!1;else{if(e=Xt,Xt=null,fi=0,ce&6)throw Error(Z(331));var i=ce;for(ce|=4,ne=e.current;ne!==null;){var h=ne,y=h.child;if(ne.flags&16){var o=h.deletions;if(o!==null){for(var u=0;uke()-Qa?xs(e,0):Xa|=r),Ye(e,t)}function cd(e,t){t===0&&(e.mode&1?(t=pn,pn<<=1,!(pn&130023424)&&(pn=4194304)):t=1);var r=ze();e=$t(e,t),e!==null&&(en(e,t,r),Ye(e,r))}function fm(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),cd(e,r)}function pm(e,t){var r=0;switch(e.tag){case 13:var n=e.stateNode,i=e.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(Z(314))}n!==null&&n.delete(t),cd(e,r)}var ud;ud=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||Ge.current)qe=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return qe=!1,tm(e,t,r);qe=!!(e.flags&131072)}else qe=!1,ve&&t.flags&1048576&&ph(t,ni,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;Bn(e,t),e=t.pendingProps;var i=tr(t,Fe.current);Ys(t,r),i=Ka(null,t,n,e,i,r);var h=Va();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,Je(n)?(h=!0,si(t)):h=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Ha(t),i.updater=Ci,t.stateNode=i,i._reactInternals=t,qo(t,n,e,r),t=Yo(null,t,n,!0,h,r)):(t.tag=0,ve&&h&&Ta(t),Ue(null,t,i,r),t=t.child),t;case 16:n=t.elementType;e:{switch(Bn(e,t),e=t.pendingProps,i=n._init,n=i(n._payload),t.type=n,i=t.tag=gm(n),e=mt(n,e),i){case 0:t=Jo(null,t,n,e,r);break e;case 1:t=hc(null,t,n,e,r);break e;case 11:t=cc(null,t,n,e,r);break e;case 14:t=uc(null,t,n,mt(n.type,e),r);break e}throw Error(Z(306,n,""))}return t;case 0:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:mt(n,i),Jo(e,t,n,i,r);case 1:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:mt(n,i),hc(e,t,n,i,r);case 3:e:{if(qh(t),e===null)throw Error(Z(387));n=t.pendingProps,h=t.memoizedState,i=h.element,xh(e,t),ai(t,n,null,r);var y=t.memoizedState;if(n=y.element,h.isDehydrated)if(h={element:n,isDehydrated:!1,cache:y.cache,pendingSuspenseBoundaries:y.pendingSuspenseBoundaries,transitions:y.transitions},t.updateQueue.baseState=h,t.memoizedState=h,t.flags&256){i=ir(Error(Z(423)),t),t=dc(e,t,n,r,i);break e}else if(n!==i){i=ir(Error(Z(424)),t),t=dc(e,t,n,r,i);break e}else for(Ze=ts(t.stateNode.containerInfo.firstChild),et=t,ve=!0,vt=null,r=_h(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(sr(),n===i){t=Ht(e,t,r);break e}Ue(e,t,n,r)}t=t.child}return t;case 5:return Sh(t),e===null&&Wo(t),n=t.type,i=t.pendingProps,h=e!==null?e.memoizedProps:null,y=i.children,$o(n,i)?y=null:h!==null&&$o(n,h)&&(t.flags|=32),Vh(e,t),Ue(e,t,y,r),t.child;case 6:return e===null&&Wo(t),null;case 13:return Gh(e,t,r);case 4:return Fa(t,t.stateNode.containerInfo),n=t.pendingProps,e===null?t.child=rr(t,null,n,r):Ue(e,t,n,r),t.child;case 11:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:mt(n,i),cc(e,t,n,i,r);case 7:return Ue(e,t,t.pendingProps,r),t.child;case 8:return Ue(e,t,t.pendingProps.children,r),t.child;case 12:return Ue(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,i=t.pendingProps,h=t.memoizedProps,y=i.value,fe(ii,n._currentValue),n._currentValue=y,h!==null)if(xt(h.value,y)){if(h.children===i.children&&!Ge.current){t=Ht(e,t,r);break e}}else for(h=t.child,h!==null&&(h.return=t);h!==null;){var o=h.dependencies;if(o!==null){y=h.child;for(var u=o.firstContext;u!==null;){if(u.context===n){if(h.tag===1){u=Mt(-1,r&-r),u.tag=2;var d=h.updateQueue;if(d!==null){d=d.shared;var m=d.pending;m===null?u.next=u:(u.next=m.next,m.next=u),d.pending=u}}h.lanes|=r,u=h.alternate,u!==null&&(u.lanes|=r),Ko(h.return,r,t),o.lanes|=r;break}u=u.next}}else if(h.tag===10)y=h.type===t.type?null:h.child;else if(h.tag===18){if(y=h.return,y===null)throw Error(Z(341));y.lanes|=r,o=y.alternate,o!==null&&(o.lanes|=r),Ko(y,r,t),y=h.sibling}else y=h.child;if(y!==null)y.return=h;else for(y=h;y!==null;){if(y===t){y=null;break}if(h=y.sibling,h!==null){h.return=y.return,y=h;break}y=y.return}h=y}Ue(e,t,i.children,r),t=t.child}return t;case 9:return i=t.type,n=t.pendingProps.children,Ys(t,r),i=ut(i),n=n(i),t.flags|=1,Ue(e,t,n,r),t.child;case 14:return n=t.type,i=mt(n,t.pendingProps),i=mt(n.type,i),uc(e,t,n,i,r);case 15:return Wh(e,t,t.type,t.pendingProps,r);case 17:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:mt(n,i),Bn(e,t),t.tag=1,Je(n)?(e=!0,si(t)):e=!1,Ys(t,r),Fh(t,n,i),qo(t,n,i,r),Yo(null,t,n,!0,e,r);case 19:return Jh(e,t,r);case 22:return Kh(e,t,r)}throw Error(Z(156,t.tag))};function hd(e,t){return Bu(e,t)}function mm(e,t,r,n){this.tag=e,this.key=r,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=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function lt(e,t,r,n){return new mm(e,t,r,n)}function sl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function gm(e){if(typeof e=="function")return sl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Sa)return 11;if(e===wa)return 14}return 2}function is(e,t){var r=e.alternate;return r===null?(r=lt(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Fn(e,t,r,n,i,h){var y=2;if(n=e,typeof e=="function")sl(e)&&(y=1);else if(typeof e=="string")y=5;else e:switch(e){case Os:return Ss(r.children,i,h,t);case xa:y=8,i|=8;break;case vo:return e=lt(12,r,t,i|2),e.elementType=vo,e.lanes=h,e;case _o:return e=lt(13,r,t,i),e.elementType=_o,e.lanes=h,e;case yo:return e=lt(19,r,t,i),e.elementType=yo,e.lanes=h,e;case Su:return Ni(r,i,h,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case yu:y=10;break e;case xu:y=9;break e;case Sa:y=11;break e;case wa:y=14;break e;case Kt:y=16,n=null;break e}throw Error(Z(130,e==null?e:typeof e,""))}return t=lt(y,r,t,i),t.elementType=e,t.type=n,t.lanes=h,t}function Ss(e,t,r,n){return e=lt(7,e,n,t),e.lanes=r,e}function Ni(e,t,r,n){return e=lt(22,e,n,t),e.elementType=Su,e.lanes=r,e.stateNode={isHidden:!1},e}function ao(e,t,r){return e=lt(6,e,null,t),e.lanes=r,e}function lo(e,t,r){return t=lt(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function vm(e,t,r,n,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=Ui(0),this.expirationTimes=Ui(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ui(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function rl(e,t,r,n,i,h,y,o,u){return e=new vm(e,t,r,o,u),t===1?(t=1,h===!0&&(t|=8)):t=0,h=lt(3,null,null,t),e.current=h,h.stateNode=e,h.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ha(h),e}function _m(e,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(md)}catch(e){console.error(e)}}md(),mu.exports=st;var bm=mu.exports,gd,Cc=bm;gd=Cc.createRoot,Cc.hydrateRoot;const vd=C.createContext({path:"/",navigate:()=>{}});function Cm({children:e}){const[t,r]=C.useState(()=>window.location.pathname);C.useEffect(()=>{const i=()=>r(window.location.pathname);return window.addEventListener("popstate",i),()=>window.removeEventListener("popstate",i)},[]);const n=C.useCallback(i=>{i!==window.location.pathname&&(window.history.pushState({},"",i),r(i))},[]);return s.jsx(vd.Provider,{value:{path:t,navigate:n},children:e})}function ur(){return C.useContext(vd)}function be({to:e,children:t,...r}){const{navigate:n}=ur();return s.jsx("a",{href:e,onClick:i=>{i.defaultPrevented||i.button!==0||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||(i.preventDefault(),n(e))},...r,children:t})}function _d(e){const t=e.match(/^\/p\/([^/]+)/);return t?t[1]:null}function km(e){const t=e.match(/^\/repos\/([^/]+)/);return t?t[1]:null}function jm(e){const t=e.match(/^\/repos\/([^/]+)\/prs\/(\d+)$/);return t?{repoId:t[1],number:parseInt(t[2],10)}:null}class yd extends Error{constructor(r,n){super(n||`HTTP ${r}`);Mi(this,"status");Mi(this,"body");this.status=r,this.body=n}}async function Ai(e){if(!e.ok){const r=await e.text().catch(()=>"");throw new yd(e.status,r)}const t=await e.text();return t?JSON.parse(t):void 0}function ee(e){return fetch(e,{credentials:"same-origin"}).then(t=>Ai(t))}function oe(e,t){return fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)}).then(r=>Ai(r))}function je(e,t){return fetch(e,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)})}function Un(e,t){return fetch(e,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)}).then(r=>Ai(r))}function St(e){return fetch(e,{method:"DELETE",credentials:"same-origin"}).then(t=>Ai(t))}function Nm(e){return fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw new yd(t.status,"");return t.text()})}function hs(e){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${e}`}const Em=4e3;function xd(e=Em){const[t,r]=C.useState({projects:[],bootId:null,connected:!1,loaded:!1}),n=C.useRef(null);return C.useEffect(()=>{let i=!0;const h=async()=>{try{const y=await ee("/status");if(!i)return;r({projects:y.projects||[],bootId:y.boot_id,connected:!0,loaded:!0})}catch{if(!i)return;r(y=>({...y,connected:!1,loaded:!0}))}};return h(),n.current=window.setInterval(h,e),()=>{i=!1,n.current&&window.clearInterval(n.current)}},[e]),t}const zn="corral.muted",kc="corral.mutedAll",jc="corral.bootId";function Rm(){try{return JSON.parse(localStorage.getItem(zn)||"{}")||{}}catch{return{}}}function Lm(e){const[t,r]=C.useState(Rm),[n,i]=C.useState(()=>localStorage.getItem(kc)==="1"),h=C.useRef(null);C.useEffect(()=>{if(!e)return;let m=null;try{m=localStorage.getItem(jc)}catch{}if(m===e){h.current=e;return}r({});try{localStorage.setItem(zn,"{}"),localStorage.setItem(jc,e)}catch{}h.current=e},[e]);const y=C.useCallback(m=>n||!!t[m],[n,t]),o=C.useCallback(m=>{r(f=>{const g={...f};g[m]?delete g[m]:g[m]=!0;try{localStorage.setItem(zn,JSON.stringify(g))}catch{}return g})},[]),u=C.useCallback(()=>{i(m=>{const f=!m;try{localStorage.setItem(kc,f?"1":"0")}catch{}return f})},[]),d=C.useCallback(m=>{r(f=>{if(!f[m])return f;const g={...f};delete g[m];try{localStorage.setItem(zn,JSON.stringify(g))}catch{}return g})},[]);return{isMuted:y,mutedAll:n,toggleMute:o,toggleMuteAll:u,forgetMute:d}}const Sd="corral.dnd",la="corral.dnd.snoozeUntil",co={enabled:!0,startHour:9,endHour:17};function Dm(){try{const e=JSON.parse(localStorage.getItem(Sd)||"null");if(e&&typeof e.enabled=="boolean")return{enabled:e.enabled,startHour:Nc(e.startHour,co.startHour),endHour:Nc(e.endHour,co.endHour)}}catch{}return co}function Nc(e,t){const r=Number(e);return Number.isInteger(r)&&r>=0&&r<=24?r:t}function Am(){try{const e=localStorage.getItem(la);if(e==="inf")return"inf";const t=Number(e);return t>0?t:null}catch{return null}}function Tm(e,t,r){return t===r?!1:t=t&&e=t||eDate.now());C.useEffect(()=>{const p=setInterval(()=>h(Date.now()),3e4);return()=>clearInterval(p)},[]),C.useEffect(()=>{try{localStorage.setItem(Sd,JSON.stringify(e))}catch{}},[e]),C.useEffect(()=>{try{r==null?localStorage.removeItem(la):localStorage.setItem(la,r==="inf"?"inf":String(r))}catch{}},[r]);const y=r==="inf"||typeof r=="number"&&r>i;C.useEffect(()=>{typeof r=="number"&&r<=i&&n(null)},[r,i]);const o=new Date(i).getHours(),u=Tm(o,e.startHour,e.endHour),d=e.enabled&&!u&&!y,m=C.useCallback(()=>!d,[d]),f=C.useCallback(p=>n(Date.now()+p*6e4),[]),g=C.useCallback(()=>n("inf"),[]),w=C.useCallback(()=>n(null),[]),S=C.useCallback(p=>t(c=>({...c,enabled:p})),[]),v=C.useCallback((p,c)=>t(a=>({...a,startHour:p,endHour:c})),[]);return{config:e,quiet:d,snoozeActive:y,snoozeUntil:r,notificationsAllowed:m,snoozeFor:f,snoozeUntilOff:g,clearSnooze:w,setEnabled:S,setWindow:v}}function Pm({dnd:e}){const[t,r]=C.useState(!1),n=C.useRef(null);C.useEffect(()=>{if(!t)return;const o=u=>{n.current&&!n.current.contains(u.target)&&r(!1)};return document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[t]);const i=e.quiet?"🌙 quiet":e.snoozeActive?"🔔 allowed":"🔔 alerts",h=e.quiet?"Do Not Disturb is active (quiet hours). Click to allow notifications.":e.snoozeActive?"Notifications temporarily allowed. Click to manage.":"Notifications on. Click to manage Do Not Disturb.",y=o=>{o(),r(!1)};return s.jsxs("div",{className:"dnd-control",ref:n,children:[s.jsxs("button",{type:"button",className:`btn dnd-btn${e.quiet?" quiet":""}`,title:h,"aria-pressed":e.quiet,onClick:()=>r(o=>!o),children:[i," ▾"]}),t&&s.jsxs("div",{className:"dnd-menu",role:"menu",children:[e.snoozeActive?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"dnd-menu-head",children:"Notifications allowed"}),s.jsx("button",{type:"button",className:"dnd-menu-item",onClick:()=>y(e.clearSnooze),children:"End now (back to Do Not Disturb)"})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"dnd-menu-head",children:"Allow notifications"}),s.jsx("button",{type:"button",className:"dnd-menu-item",onClick:()=>y(()=>e.snoozeFor(15)),children:"for 15 minutes"}),s.jsx("button",{type:"button",className:"dnd-menu-item",onClick:()=>y(()=>e.snoozeFor(60)),children:"for 1 hour"}),s.jsx("button",{type:"button",className:"dnd-menu-item",onClick:()=>y(e.snoozeUntilOff),children:"until I turn it off"})]}),s.jsx("div",{className:"dnd-menu-sep"}),s.jsx(be,{to:"/global",className:"dnd-menu-item dnd-menu-link",onClick:()=>r(!1),children:"Manage in Global settings →"})]})]})}let Wt=null;function Om(){try{if(!Wt){const t=window.AudioContext||window.webkitAudioContext;if(!t)return;Wt=new t}Wt.state==="suspended"&&Wt.resume();const e=Wt.currentTime;[880,1174.66].forEach((t,r)=>{const n=Wt.createOscillator(),i=Wt.createGain();n.type="sine",n.frequency.value=t;const h=e+r*.16;i.gain.setValueAtTime(1e-4,h),i.gain.exponentialRampToValueAtTime(.2,h+.02),i.gain.exponentialRampToValueAtTime(1e-4,h+.35),n.connect(i).connect(Wt.destination),n.start(h),n.stop(h+.4)})}catch{}}const bd=C.createContext({notify:()=>{},clearAll:()=>{}});function Mm(){return C.useContext(bd)}function Im({children:e}){const[t,r]=C.useState([]),n=C.useRef(1),i=C.useCallback(o=>{r(u=>u.filter(d=>d.key!==o))},[]),h=C.useCallback((o,u)=>{const d=n.current++;r(m=>[...m,{key:d,id:o,name:u}]),window.setTimeout(()=>i(d),13e3)},[i]),y=C.useCallback(()=>r([]),[]);return C.useEffect(()=>{const o=u=>{u.key==="."&&(u.ctrlKey||u.metaKey)&&y()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[y]),s.jsxs(bd.Provider,{value:{notify:h,clearAll:y},children:[e,s.jsx("div",{className:"toast-host",children:t.map(o=>s.jsxs(be,{className:"toast",to:`/p/${o.id}/`,children:[s.jsx("span",{className:"toast-dot"}),s.jsxs("span",{className:"toast-body",children:[s.jsx("strong",{children:o.name}),s.jsx("span",{className:"toast-sub",children:"is waiting on you"})]}),s.jsx("button",{className:"toast-x",title:"Dismiss","aria-label":"Dismiss",onClick:u=>{u.preventDefault(),u.stopPropagation(),i(o.key)},children:"✕"})]},o.key))})]})}var Cd={exports:{}};(function(e,t){(function(r,n){e.exports=n()})(globalThis,()=>(()=>{var r={4567:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.AccessibilityManager=void 0;const f=u(9042),g=u(9924),w=u(844),S=u(4725),v=u(2585),p=u(3656);let c=o.AccessibilityManager=class extends w.Disposable{constructor(a,l,_,j){super(),this._terminal=a,this._coreBrowserService=_,this._renderService=j,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let b=0;bthis._handleBoundaryFocus(b,0),this._bottomBoundaryFocusListener=b=>this._handleBoundaryFocus(b,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new g.TimeBasedDebouncer(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(b=>this._handleResize(b.rows))),this.register(this._terminal.onRender(b=>this._refreshRows(b.start,b.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(b=>this._handleChar(b))),this.register(this._terminal.onLineFeed(()=>this._handleChar(` `))),this.register(this._terminal.onA11yTab(b=>this._handleTab(b))),this.register(this._terminal.onKey(b=>this._handleKey(b.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this.register((0,p.addDisposableDomListener)(document,"selectionchange",()=>this._handleSelectionChange())),this.register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,w.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(a){for(let l=0;l0?this._charsToConsume.shift()!==a&&(this._charsToAnnounce+=a):this._charsToAnnounce+=a,a===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=f.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(a){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(a)||this._charsToConsume.push(a)}_refreshRows(a,l){this._liveRegionDebouncer.refresh(a,l,this._terminal.rows)}_renderRows(a,l){const _=this._terminal.buffer,j=_.lines.length.toString();for(let b=a;b<=l;b++){const k=_.lines.get(_.ydisp+b),x=[],N=(k==null?void 0:k.translateToString(!0,void 0,void 0,x))||"",E=(_.ydisp+b+1).toString(),L=this._rowElements[b];L&&(N.length===0?(L.innerText=" ",this._rowColumns.set(L,[0,1])):(L.textContent=N,this._rowColumns.set(L,x)),L.setAttribute("aria-posinset",E),L.setAttribute("aria-setsize",j))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(a,l){const _=a.target,j=this._rowElements[l===0?1:this._rowElements.length-2];if(_.getAttribute("aria-posinset")===(l===0?"1":`${this._terminal.buffer.lines.length}`)||a.relatedTarget!==j)return;let b,k;if(l===0?(b=_,k=this._rowElements.pop(),this._rowContainer.removeChild(k)):(b=this._rowElements.shift(),k=_,this._rowContainer.removeChild(b)),b.removeEventListener("focus",this._topBoundaryFocusListener),k.removeEventListener("focus",this._bottomBoundaryFocusListener),l===0){const x=this._createAccessibilityTreeNode();this._rowElements.unshift(x),this._rowContainer.insertAdjacentElement("afterbegin",x)}else{const x=this._createAccessibilityTreeNode();this._rowElements.push(x),this._rowContainer.appendChild(x)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(l===0?-1:1),this._rowElements[l===0?1:this._rowElements.length-2].focus(),a.preventDefault(),a.stopImmediatePropagation()}_handleSelectionChange(){var N;if(this._rowElements.length===0)return;const a=document.getSelection();if(!a)return;if(a.isCollapsed)return void(this._rowContainer.contains(a.anchorNode)&&this._terminal.clearSelection());if(!a.anchorNode||!a.focusNode)return void console.error("anchorNode and/or focusNode are null");let l={node:a.anchorNode,offset:a.anchorOffset},_={node:a.focusNode,offset:a.focusOffset};if((l.node.compareDocumentPosition(_.node)&Node.DOCUMENT_POSITION_PRECEDING||l.node===_.node&&l.offset>_.offset)&&([l,_]=[_,l]),l.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(l={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(l.node))return;const j=this._rowElements.slice(-1)[0];if(_.node.compareDocumentPosition(j)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(_={node:j,offset:((N=j.textContent)==null?void 0:N.length)??0}),!this._rowContainer.contains(_.node))return;const b=({node:E,offset:L})=>{const T=E instanceof Text?E.parentNode:E;let O=parseInt(T==null?void 0:T.getAttribute("aria-posinset"),10)-1;if(isNaN(O))return console.warn("row is invalid. Race condition?"),null;const B=this._rowColumns.get(T);if(!B)return console.warn("columns is null. Race condition?"),null;let F=L=this._terminal.cols&&(++O,F=0),{row:O,column:F}},k=b(l),x=b(_);if(k&&x){if(k.row>x.row||k.row===x.row&&k.column>=x.column)throw new Error("invalid range");this._terminal.select(k.column,k.row,(x.row-k.row)*this._terminal.cols-k.column+x.column)}}_handleResize(a){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let l=this._rowContainer.children.length;la;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const a=this._coreBrowserService.mainDocument.createElement("div");return a.setAttribute("role","listitem"),a.tabIndex=-1,this._refreshRowDimensions(a),a}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let a=0;a{function u(g){return g.replace(/\r?\n/g,"\r")}function d(g,w){return w?"\x1B[200~"+g+"\x1B[201~":g}function m(g,w,S,v){g=d(g=u(g),S.decPrivateModes.bracketedPasteMode&&v.rawOptions.ignoreBracketedPasteMode!==!0),S.triggerDataEvent(g,!0),w.value=""}function f(g,w,S){const v=S.getBoundingClientRect(),p=g.clientX-v.left-10,c=g.clientY-v.top-10;w.style.width="20px",w.style.height="20px",w.style.left=`${p}px`,w.style.top=`${c}px`,w.style.zIndex="1000",w.focus()}Object.defineProperty(o,"__esModule",{value:!0}),o.rightClickHandler=o.moveTextAreaUnderMouseCursor=o.paste=o.handlePasteEvent=o.copyHandler=o.bracketTextForPaste=o.prepareTextForTerminal=void 0,o.prepareTextForTerminal=u,o.bracketTextForPaste=d,o.copyHandler=function(g,w){g.clipboardData&&g.clipboardData.setData("text/plain",w.selectionText),g.preventDefault()},o.handlePasteEvent=function(g,w,S,v){g.stopPropagation(),g.clipboardData&&m(g.clipboardData.getData("text/plain"),w,S,v)},o.paste=m,o.moveTextAreaUnderMouseCursor=f,o.rightClickHandler=function(g,w,S,v,p){f(g,w,S),p&&v.rightClickSelect(g),w.value=v.selectionText,w.select()}},7239:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorContrastCache=void 0;const d=u(1505);o.ColorContrastCache=class{constructor(){this._color=new d.TwoKeyMap,this._css=new d.TwoKeyMap}setCss(m,f,g){this._css.set(m,f,g)}getCss(m,f){return this._css.get(m,f)}setColor(m,f,g){this._color.set(m,f,g)}getColor(m,f){return this._color.get(m,f)}clear(){this._color.clear(),this._css.clear()}}},3656:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.addDisposableDomListener=void 0,o.addDisposableDomListener=function(u,d,m,f){u.addEventListener(d,m,f);let g=!1;return{dispose:()=>{g||(g=!0,u.removeEventListener(d,m,f))}}}},3551:function(y,o,u){var d=this&&this.__decorate||function(c,a,l,_){var j,b=arguments.length,k=b<3?a:_===null?_=Object.getOwnPropertyDescriptor(a,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(c,a,l,_);else for(var x=c.length-1;x>=0;x--)(j=c[x])&&(k=(b<3?j(k):b>3?j(a,l,k):j(a,l))||k);return b>3&&k&&Object.defineProperty(a,l,k),k},m=this&&this.__param||function(c,a){return function(l,_){a(l,_,c)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Linkifier=void 0;const f=u(3656),g=u(8460),w=u(844),S=u(2585),v=u(4725);let p=o.Linkifier=class extends w.Disposable{get currentLink(){return this._currentLink}constructor(c,a,l,_,j){super(),this._element=c,this._mouseService=a,this._renderService=l,this._bufferService=_,this._linkProviderService=j,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new g.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new g.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,w.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,w.toDisposable)(()=>{var b;this._lastMouseEvent=void 0,(b=this._activeProviderReplies)==null||b.clear()})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this.register((0,f.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,f.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,f.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,f.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(c){this._lastMouseEvent=c;const a=this._positionFromMouseEvent(c,this._element,this._mouseService);if(!a)return;this._isMouseOut=!1;const l=c.composedPath();for(let _=0;_{b==null||b.forEach(k=>{k.link.dispose&&k.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=c.y);let l=!1;for(const[b,k]of this._linkProviderService.linkProviders.entries())a?(j=this._activeProviderReplies)!=null&&j.get(b)&&(l=this._checkLinkProviderResult(b,c,l)):k.provideLinks(c.y,x=>{var E,L;if(this._isMouseOut)return;const N=x==null?void 0:x.map(T=>({link:T}));(E=this._activeProviderReplies)==null||E.set(b,N),l=this._checkLinkProviderResult(b,c,l),((L=this._activeProviderReplies)==null?void 0:L.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(c.y,this._activeProviderReplies)})}_removeIntersectingLinks(c,a){const l=new Set;for(let _=0;_c?this._bufferService.cols:k.link.range.end.x;for(let E=x;E<=N;E++){if(l.has(E)){j.splice(b--,1);break}l.add(E)}}}}_checkLinkProviderResult(c,a,l){var b;if(!this._activeProviderReplies)return l;const _=this._activeProviderReplies.get(c);let j=!1;for(let k=0;kthis._linkAtPosition(x.link,a));k&&(l=!0,this._handleNewLink(k))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!l)for(let k=0;kthis._linkAtPosition(N.link,a));if(x){l=!0,this._handleNewLink(x);break}}return l}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(c){if(!this._currentLink)return;const a=this._positionFromMouseEvent(c,this._element,this._mouseService);a&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,a)&&this._currentLink.link.activate(c,this._currentLink.link.text)}_clearCurrentLink(c,a){this._currentLink&&this._lastMouseEvent&&(!c||!a||this._currentLink.link.range.start.y>=c&&this._currentLink.link.range.end.y<=a)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,w.disposeArray)(this._linkCacheDisposables))}_handleNewLink(c){if(!this._lastMouseEvent)return;const a=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);a&&this._linkAtPosition(c.link,a)&&(this._currentLink=c,this._currentLink.state={decorations:{underline:c.link.decorations===void 0||c.link.decorations.underline,pointerCursor:c.link.decorations===void 0||c.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,c.link,this._lastMouseEvent),c.link.decorations={},Object.defineProperties(c.link.decorations,{pointerCursor:{get:()=>{var l,_;return(_=(l=this._currentLink)==null?void 0:l.state)==null?void 0:_.decorations.pointerCursor},set:l=>{var _;(_=this._currentLink)!=null&&_.state&&this._currentLink.state.decorations.pointerCursor!==l&&(this._currentLink.state.decorations.pointerCursor=l,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",l))}},underline:{get:()=>{var l,_;return(_=(l=this._currentLink)==null?void 0:l.state)==null?void 0:_.decorations.underline},set:l=>{var _,j,b;(_=this._currentLink)!=null&&_.state&&((b=(j=this._currentLink)==null?void 0:j.state)==null?void 0:b.decorations.underline)!==l&&(this._currentLink.state.decorations.underline=l,this._currentLink.state.isHovered&&this._fireUnderlineEvent(c.link,l))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(l=>{if(!this._currentLink)return;const _=l.start===0?0:l.start+1+this._bufferService.buffer.ydisp,j=this._bufferService.buffer.ydisp+1+l.end;if(this._currentLink.link.range.start.y>=_&&this._currentLink.link.range.end.y<=j&&(this._clearCurrentLink(_,j),this._lastMouseEvent)){const b=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);b&&this._askForLink(b,!1)}})))}_linkHover(c,a,l){var _;(_=this._currentLink)!=null&&_.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(a,!0),this._currentLink.state.decorations.pointerCursor&&c.classList.add("xterm-cursor-pointer")),a.hover&&a.hover(l,a.text)}_fireUnderlineEvent(c,a){const l=c.range,_=this._bufferService.buffer.ydisp,j=this._createLinkUnderlineEvent(l.start.x-1,l.start.y-_-1,l.end.x,l.end.y-_-1,void 0);(a?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(j)}_linkLeave(c,a,l){var _;(_=this._currentLink)!=null&&_.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(a,!1),this._currentLink.state.decorations.pointerCursor&&c.classList.remove("xterm-cursor-pointer")),a.leave&&a.leave(l,a.text)}_linkAtPosition(c,a){const l=c.range.start.y*this._bufferService.cols+c.range.start.x,_=c.range.end.y*this._bufferService.cols+c.range.end.x,j=a.y*this._bufferService.cols+a.x;return l<=j&&j<=_}_positionFromMouseEvent(c,a,l){const _=l.getCoords(c,a,this._bufferService.cols,this._bufferService.rows);if(_)return{x:_[0],y:_[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(c,a,l,_,j){return{x1:c,y1:a,x2:l,y2:_,cols:this._bufferService.cols,fg:j}}};o.Linkifier=p=d([m(1,v.IMouseService),m(2,v.IRenderService),m(3,S.IBufferService),m(4,v.ILinkProviderService)],p)},9042:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.tooMuchOutput=o.promptLabel=void 0,o.promptLabel="Terminal input",o.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(y,o,u){var d=this&&this.__decorate||function(v,p,c,a){var l,_=arguments.length,j=_<3?p:a===null?a=Object.getOwnPropertyDescriptor(p,c):a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(v,p,c,a);else for(var b=v.length-1;b>=0;b--)(l=v[b])&&(j=(_<3?l(j):_>3?l(p,c,j):l(p,c))||j);return _>3&&j&&Object.defineProperty(p,c,j),j},m=this&&this.__param||function(v,p){return function(c,a){p(c,a,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkProvider=void 0;const f=u(511),g=u(2585);let w=o.OscLinkProvider=class{constructor(v,p,c){this._bufferService=v,this._optionsService=p,this._oscLinkService=c}provideLinks(v,p){var N;const c=this._bufferService.buffer.lines.get(v-1);if(!c)return void p(void 0);const a=[],l=this._optionsService.rawOptions.linkHandler,_=new f.CellData,j=c.getTrimmedLength();let b=-1,k=-1,x=!1;for(let E=0;El?l.activate(B,F,T):S(0,F),hover:(B,F)=>{var z;return(z=l==null?void 0:l.hover)==null?void 0:z.call(l,B,F,T)},leave:(B,F)=>{var z;return(z=l==null?void 0:l.leave)==null?void 0:z.call(l,B,F,T)}})}x=!1,_.hasExtendedAttrs()&&_.extended.urlId?(k=E,b=_.extended.urlId):(k=-1,b=-1)}}p(a)}};function S(v,p){if(confirm(`Do you want to navigate to ${p}? +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=f.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(a){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(a)||this._charsToConsume.push(a)}_refreshRows(a,l){this._liveRegionDebouncer.refresh(a,l,this._terminal.rows)}_renderRows(a,l){const _=this._terminal.buffer,j=_.lines.length.toString();for(let b=a;b<=l;b++){const k=_.lines.get(_.ydisp+b),x=[],N=(k==null?void 0:k.translateToString(!0,void 0,void 0,x))||"",E=(_.ydisp+b+1).toString(),L=this._rowElements[b];L&&(N.length===0?(L.innerText=" ",this._rowColumns.set(L,[0,1])):(L.textContent=N,this._rowColumns.set(L,x)),L.setAttribute("aria-posinset",E),L.setAttribute("aria-setsize",j))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(a,l){const _=a.target,j=this._rowElements[l===0?1:this._rowElements.length-2];if(_.getAttribute("aria-posinset")===(l===0?"1":`${this._terminal.buffer.lines.length}`)||a.relatedTarget!==j)return;let b,k;if(l===0?(b=_,k=this._rowElements.pop(),this._rowContainer.removeChild(k)):(b=this._rowElements.shift(),k=_,this._rowContainer.removeChild(b)),b.removeEventListener("focus",this._topBoundaryFocusListener),k.removeEventListener("focus",this._bottomBoundaryFocusListener),l===0){const x=this._createAccessibilityTreeNode();this._rowElements.unshift(x),this._rowContainer.insertAdjacentElement("afterbegin",x)}else{const x=this._createAccessibilityTreeNode();this._rowElements.push(x),this._rowContainer.appendChild(x)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(l===0?-1:1),this._rowElements[l===0?1:this._rowElements.length-2].focus(),a.preventDefault(),a.stopImmediatePropagation()}_handleSelectionChange(){var N;if(this._rowElements.length===0)return;const a=document.getSelection();if(!a)return;if(a.isCollapsed)return void(this._rowContainer.contains(a.anchorNode)&&this._terminal.clearSelection());if(!a.anchorNode||!a.focusNode)return void console.error("anchorNode and/or focusNode are null");let l={node:a.anchorNode,offset:a.anchorOffset},_={node:a.focusNode,offset:a.focusOffset};if((l.node.compareDocumentPosition(_.node)&Node.DOCUMENT_POSITION_PRECEDING||l.node===_.node&&l.offset>_.offset)&&([l,_]=[_,l]),l.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(l={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(l.node))return;const j=this._rowElements.slice(-1)[0];if(_.node.compareDocumentPosition(j)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(_={node:j,offset:((N=j.textContent)==null?void 0:N.length)??0}),!this._rowContainer.contains(_.node))return;const b=({node:E,offset:L})=>{const T=E instanceof Text?E.parentNode:E;let P=parseInt(T==null?void 0:T.getAttribute("aria-posinset"),10)-1;if(isNaN(P))return console.warn("row is invalid. Race condition?"),null;const B=this._rowColumns.get(T);if(!B)return console.warn("columns is null. Race condition?"),null;let U=L=this._terminal.cols&&(++P,U=0),{row:P,column:U}},k=b(l),x=b(_);if(k&&x){if(k.row>x.row||k.row===x.row&&k.column>=x.column)throw new Error("invalid range");this._terminal.select(k.column,k.row,(x.row-k.row)*this._terminal.cols-k.column+x.column)}}_handleResize(a){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let l=this._rowContainer.children.length;la;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const a=this._coreBrowserService.mainDocument.createElement("div");return a.setAttribute("role","listitem"),a.tabIndex=-1,this._refreshRowDimensions(a),a}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let a=0;a{function u(g){return g.replace(/\r?\n/g,"\r")}function d(g,w){return w?"\x1B[200~"+g+"\x1B[201~":g}function m(g,w,S,v){g=d(g=u(g),S.decPrivateModes.bracketedPasteMode&&v.rawOptions.ignoreBracketedPasteMode!==!0),S.triggerDataEvent(g,!0),w.value=""}function f(g,w,S){const v=S.getBoundingClientRect(),p=g.clientX-v.left-10,c=g.clientY-v.top-10;w.style.width="20px",w.style.height="20px",w.style.left=`${p}px`,w.style.top=`${c}px`,w.style.zIndex="1000",w.focus()}Object.defineProperty(o,"__esModule",{value:!0}),o.rightClickHandler=o.moveTextAreaUnderMouseCursor=o.paste=o.handlePasteEvent=o.copyHandler=o.bracketTextForPaste=o.prepareTextForTerminal=void 0,o.prepareTextForTerminal=u,o.bracketTextForPaste=d,o.copyHandler=function(g,w){g.clipboardData&&g.clipboardData.setData("text/plain",w.selectionText),g.preventDefault()},o.handlePasteEvent=function(g,w,S,v){g.stopPropagation(),g.clipboardData&&m(g.clipboardData.getData("text/plain"),w,S,v)},o.paste=m,o.moveTextAreaUnderMouseCursor=f,o.rightClickHandler=function(g,w,S,v,p){f(g,w,S),p&&v.rightClickSelect(g),w.value=v.selectionText,w.select()}},7239:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorContrastCache=void 0;const d=u(1505);o.ColorContrastCache=class{constructor(){this._color=new d.TwoKeyMap,this._css=new d.TwoKeyMap}setCss(m,f,g){this._css.set(m,f,g)}getCss(m,f){return this._css.get(m,f)}setColor(m,f,g){this._color.set(m,f,g)}getColor(m,f){return this._color.get(m,f)}clear(){this._color.clear(),this._css.clear()}}},3656:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.addDisposableDomListener=void 0,o.addDisposableDomListener=function(u,d,m,f){u.addEventListener(d,m,f);let g=!1;return{dispose:()=>{g||(g=!0,u.removeEventListener(d,m,f))}}}},3551:function(y,o,u){var d=this&&this.__decorate||function(c,a,l,_){var j,b=arguments.length,k=b<3?a:_===null?_=Object.getOwnPropertyDescriptor(a,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(c,a,l,_);else for(var x=c.length-1;x>=0;x--)(j=c[x])&&(k=(b<3?j(k):b>3?j(a,l,k):j(a,l))||k);return b>3&&k&&Object.defineProperty(a,l,k),k},m=this&&this.__param||function(c,a){return function(l,_){a(l,_,c)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Linkifier=void 0;const f=u(3656),g=u(8460),w=u(844),S=u(2585),v=u(4725);let p=o.Linkifier=class extends w.Disposable{get currentLink(){return this._currentLink}constructor(c,a,l,_,j){super(),this._element=c,this._mouseService=a,this._renderService=l,this._bufferService=_,this._linkProviderService=j,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new g.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new g.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,w.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,w.toDisposable)(()=>{var b;this._lastMouseEvent=void 0,(b=this._activeProviderReplies)==null||b.clear()})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this.register((0,f.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,f.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,f.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,f.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(c){this._lastMouseEvent=c;const a=this._positionFromMouseEvent(c,this._element,this._mouseService);if(!a)return;this._isMouseOut=!1;const l=c.composedPath();for(let _=0;_{b==null||b.forEach(k=>{k.link.dispose&&k.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=c.y);let l=!1;for(const[b,k]of this._linkProviderService.linkProviders.entries())a?(j=this._activeProviderReplies)!=null&&j.get(b)&&(l=this._checkLinkProviderResult(b,c,l)):k.provideLinks(c.y,x=>{var E,L;if(this._isMouseOut)return;const N=x==null?void 0:x.map(T=>({link:T}));(E=this._activeProviderReplies)==null||E.set(b,N),l=this._checkLinkProviderResult(b,c,l),((L=this._activeProviderReplies)==null?void 0:L.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(c.y,this._activeProviderReplies)})}_removeIntersectingLinks(c,a){const l=new Set;for(let _=0;_c?this._bufferService.cols:k.link.range.end.x;for(let E=x;E<=N;E++){if(l.has(E)){j.splice(b--,1);break}l.add(E)}}}}_checkLinkProviderResult(c,a,l){var b;if(!this._activeProviderReplies)return l;const _=this._activeProviderReplies.get(c);let j=!1;for(let k=0;kthis._linkAtPosition(x.link,a));k&&(l=!0,this._handleNewLink(k))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!l)for(let k=0;kthis._linkAtPosition(N.link,a));if(x){l=!0,this._handleNewLink(x);break}}return l}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(c){if(!this._currentLink)return;const a=this._positionFromMouseEvent(c,this._element,this._mouseService);a&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,a)&&this._currentLink.link.activate(c,this._currentLink.link.text)}_clearCurrentLink(c,a){this._currentLink&&this._lastMouseEvent&&(!c||!a||this._currentLink.link.range.start.y>=c&&this._currentLink.link.range.end.y<=a)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,w.disposeArray)(this._linkCacheDisposables))}_handleNewLink(c){if(!this._lastMouseEvent)return;const a=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);a&&this._linkAtPosition(c.link,a)&&(this._currentLink=c,this._currentLink.state={decorations:{underline:c.link.decorations===void 0||c.link.decorations.underline,pointerCursor:c.link.decorations===void 0||c.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,c.link,this._lastMouseEvent),c.link.decorations={},Object.defineProperties(c.link.decorations,{pointerCursor:{get:()=>{var l,_;return(_=(l=this._currentLink)==null?void 0:l.state)==null?void 0:_.decorations.pointerCursor},set:l=>{var _;(_=this._currentLink)!=null&&_.state&&this._currentLink.state.decorations.pointerCursor!==l&&(this._currentLink.state.decorations.pointerCursor=l,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",l))}},underline:{get:()=>{var l,_;return(_=(l=this._currentLink)==null?void 0:l.state)==null?void 0:_.decorations.underline},set:l=>{var _,j,b;(_=this._currentLink)!=null&&_.state&&((b=(j=this._currentLink)==null?void 0:j.state)==null?void 0:b.decorations.underline)!==l&&(this._currentLink.state.decorations.underline=l,this._currentLink.state.isHovered&&this._fireUnderlineEvent(c.link,l))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(l=>{if(!this._currentLink)return;const _=l.start===0?0:l.start+1+this._bufferService.buffer.ydisp,j=this._bufferService.buffer.ydisp+1+l.end;if(this._currentLink.link.range.start.y>=_&&this._currentLink.link.range.end.y<=j&&(this._clearCurrentLink(_,j),this._lastMouseEvent)){const b=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);b&&this._askForLink(b,!1)}})))}_linkHover(c,a,l){var _;(_=this._currentLink)!=null&&_.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(a,!0),this._currentLink.state.decorations.pointerCursor&&c.classList.add("xterm-cursor-pointer")),a.hover&&a.hover(l,a.text)}_fireUnderlineEvent(c,a){const l=c.range,_=this._bufferService.buffer.ydisp,j=this._createLinkUnderlineEvent(l.start.x-1,l.start.y-_-1,l.end.x,l.end.y-_-1,void 0);(a?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(j)}_linkLeave(c,a,l){var _;(_=this._currentLink)!=null&&_.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(a,!1),this._currentLink.state.decorations.pointerCursor&&c.classList.remove("xterm-cursor-pointer")),a.leave&&a.leave(l,a.text)}_linkAtPosition(c,a){const l=c.range.start.y*this._bufferService.cols+c.range.start.x,_=c.range.end.y*this._bufferService.cols+c.range.end.x,j=a.y*this._bufferService.cols+a.x;return l<=j&&j<=_}_positionFromMouseEvent(c,a,l){const _=l.getCoords(c,a,this._bufferService.cols,this._bufferService.rows);if(_)return{x:_[0],y:_[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(c,a,l,_,j){return{x1:c,y1:a,x2:l,y2:_,cols:this._bufferService.cols,fg:j}}};o.Linkifier=p=d([m(1,v.IMouseService),m(2,v.IRenderService),m(3,S.IBufferService),m(4,v.ILinkProviderService)],p)},9042:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.tooMuchOutput=o.promptLabel=void 0,o.promptLabel="Terminal input",o.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(y,o,u){var d=this&&this.__decorate||function(v,p,c,a){var l,_=arguments.length,j=_<3?p:a===null?a=Object.getOwnPropertyDescriptor(p,c):a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(v,p,c,a);else for(var b=v.length-1;b>=0;b--)(l=v[b])&&(j=(_<3?l(j):_>3?l(p,c,j):l(p,c))||j);return _>3&&j&&Object.defineProperty(p,c,j),j},m=this&&this.__param||function(v,p){return function(c,a){p(c,a,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkProvider=void 0;const f=u(511),g=u(2585);let w=o.OscLinkProvider=class{constructor(v,p,c){this._bufferService=v,this._optionsService=p,this._oscLinkService=c}provideLinks(v,p){var N;const c=this._bufferService.buffer.lines.get(v-1);if(!c)return void p(void 0);const a=[],l=this._optionsService.rawOptions.linkHandler,_=new f.CellData,j=c.getTrimmedLength();let b=-1,k=-1,x=!1;for(let E=0;El?l.activate(B,U,T):S(0,U),hover:(B,U)=>{var K;return(K=l==null?void 0:l.hover)==null?void 0:K.call(l,B,U,T)},leave:(B,U)=>{var K;return(K=l==null?void 0:l.leave)==null?void 0:K.call(l,B,U,T)}})}x=!1,_.hasExtendedAttrs()&&_.extended.urlId?(k=E,b=_.extended.urlId):(k=-1,b=-1)}}p(a)}};function S(v,p){if(confirm(`Do you want to navigate to ${p}? -WARNING: This link could potentially be dangerous`)){const c=window.open();if(c){try{c.opener=null}catch{}c.location.href=p}else console.warn("Opening link blocked as opener could not be cleared")}}o.OscLinkProvider=w=d([m(0,g.IBufferService),m(1,g.IOptionsService),m(2,g.IOscLinkService)],w)},6193:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.RenderDebouncer=void 0,o.RenderDebouncer=class{constructor(u,d){this._renderCallback=u,this._coreBrowserService=d,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(u){return this._refreshCallbacks.push(u),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(u,d,m){this._rowCount=m,u=u!==void 0?u:0,d=d!==void 0?d:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,d):d,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)return void this._runRefreshCallbacks();const u=Math.max(this._rowStart,0),d=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,d),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const u of this._refreshCallbacks)u(0);this._refreshCallbacks=[]}}},3236:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Terminal=void 0;const d=u(3614),m=u(3656),f=u(3551),g=u(9042),w=u(3730),S=u(1680),v=u(3107),p=u(5744),c=u(2950),a=u(1296),l=u(428),_=u(4269),j=u(5114),b=u(8934),k=u(3230),x=u(9312),N=u(4725),E=u(6731),L=u(8055),T=u(8969),O=u(8460),B=u(844),F=u(6114),z=u(8437),K=u(2584),$=u(7399),R=u(5941),D=u(9074),M=u(2585),P=u(5435),U=u(4567),Y=u(779);class H extends T.CoreTerminal{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}constructor(I={}){super(I),this.browser=F,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new B.MutableDisposable),this._onCursorMove=this.register(new O.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new O.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new O.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new O.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new O.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new O.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new O.EventEmitter),this._onBlur=this.register(new O.EventEmitter),this._onA11yCharEmitter=this.register(new O.EventEmitter),this._onA11yTabEmitter=this.register(new O.EventEmitter),this._onWillOpen=this.register(new O.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(D.DecorationService),this._instantiationService.setService(M.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Y.LinkProviderService),this._instantiationService.setService(N.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(w.OscLinkProvider)),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((A,q)=>this.refresh(A,q))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(A=>this._reportWindowsOptions(A))),this.register(this._inputHandler.onColor(A=>this._handleColorEvent(A))),this.register((0,O.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,O.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,O.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,O.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(A=>this._afterResize(A.cols,A.rows))),this.register((0,B.toDisposable)(()=>{var A,q;this._customKeyEventHandler=void 0,(q=(A=this.element)==null?void 0:A.parentNode)==null||q.removeChild(this.element)}))}_handleColorEvent(I){if(this._themeService)for(const A of I){let q,W="";switch(A.index){case 256:q="foreground",W="10";break;case 257:q="background",W="11";break;case 258:q="cursor",W="12";break;default:q="ansi",W="4;"+A.index}switch(A.type){case 0:const X=L.color.toColorRGB(q==="ansi"?this._themeService.colors.ansi[A.index]:this._themeService.colors[q]);this.coreService.triggerDataEvent(`${K.C0.ESC}]${W};${(0,R.toRgbString)(X)}${K.C1_ESCAPED.ST}`);break;case 1:if(q==="ansi")this._themeService.modifyColors(Q=>Q.ansi[A.index]=L.channels.toColor(...A.color));else{const Q=q;this._themeService.modifyColors(re=>re[Q]=L.channels.toColor(...A.color))}break;case 2:this._themeService.restoreColor(A.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(I){I?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(U.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(I){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var I;return(I=this.textarea)==null?void 0:I.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(K.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const I=this.buffer.ybase+this.buffer.y,A=this.buffer.lines.get(I);if(!A)return;const q=Math.min(this.buffer.x,this.cols-1),W=this._renderService.dimensions.css.cell.height,X=A.getWidth(q),Q=this._renderService.dimensions.css.cell.width*X,re=this.buffer.y*this._renderService.dimensions.css.cell.height,ie=q*this._renderService.dimensions.css.cell.width;this.textarea.style.left=ie+"px",this.textarea.style.top=re+"px",this.textarea.style.width=Q+"px",this.textarea.style.height=W+"px",this.textarea.style.lineHeight=W+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,m.addDisposableDomListener)(this.element,"copy",A=>{this.hasSelection()&&(0,d.copyHandler)(A,this._selectionService)}));const I=A=>(0,d.handlePasteEvent)(A,this.textarea,this.coreService,this.optionsService);this.register((0,m.addDisposableDomListener)(this.textarea,"paste",I)),this.register((0,m.addDisposableDomListener)(this.element,"paste",I)),F.isFirefox?this.register((0,m.addDisposableDomListener)(this.element,"mousedown",A=>{A.button===2&&(0,d.rightClickHandler)(A,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,m.addDisposableDomListener)(this.element,"contextmenu",A=>{(0,d.rightClickHandler)(A,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),F.isLinux&&this.register((0,m.addDisposableDomListener)(this.element,"auxclick",A=>{A.button===1&&(0,d.moveTextAreaUnderMouseCursor)(A,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,m.addDisposableDomListener)(this.textarea,"keyup",I=>this._keyUp(I),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"keydown",I=>this._keyDown(I),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"keypress",I=>this._keyPress(I),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionupdate",I=>this._compositionHelper.compositionupdate(I))),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,m.addDisposableDomListener)(this.textarea,"input",I=>this._inputEvent(I),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(I){var q;if(!I)throw new Error("Terminal requires a parent element.");if(I.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((q=this.element)==null?void 0:q.ownerDocument.defaultView)&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=I.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"),I.appendChild(this.element);const A=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),A.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,m.addDisposableDomListener)(this.screenElement,"mousemove",W=>this.updateCursorStyle(W))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),A.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",g.promptLabel),F.isChromeOS||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._coreBrowserService=this.register(this._instantiationService.createInstance(j.CoreBrowserService,this.textarea,I.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(N.ICoreBrowserService,this._coreBrowserService),this.register((0,m.addDisposableDomListener)(this.textarea,"focus",W=>this._handleTextAreaFocus(W))),this.register((0,m.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(l.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(N.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(E.ThemeService),this._instantiationService.setService(N.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(_.CharacterJoinerService),this._instantiationService.setService(N.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(k.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(N.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(W=>this._onRender.fire(W))),this.onResize(W=>this._renderService.resize(W.cols,W.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(c.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(b.MouseService),this._instantiationService.setService(N.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(f.Linkifier,this.screenElement)),this.element.appendChild(A);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(S.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(W=>this.scrollLines(W.amount,W.suppressScrollEvent,1)),this.register(this._inputHandler.onRequestSyncScrollBar(()=>this.viewport.syncScrollArea())),this.register(this.viewport),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.register(this._renderService.onDimensionsChange(()=>this.viewport.syncScrollArea())),this._selectionService=this.register(this._instantiationService.createInstance(x.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(N.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(W=>this.scrollLines(W.amount,W.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(W=>this._renderService.handleSelectionChanged(W.start,W.end,W.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(W=>{this.textarea.value=W,this.textarea.focus(),this.textarea.select()})),this.register(this._onScroll.event(W=>{this.viewport.syncScrollArea(),this._selectionService.refresh()})),this.register((0,m.addDisposableDomListener)(this._viewportElement,"scroll",()=>this._selectionService.refresh())),this.register(this._instantiationService.createInstance(v.BufferDecorationRenderer,this.screenElement)),this.register((0,m.addDisposableDomListener)(this.element,"mousedown",W=>this._selectionService.handleMouseDown(W))),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(U.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",W=>this._handleScreenReaderModeOptionChange(W))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",W=>{!this._overviewRulerRenderer&&W&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(a.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const I=this,A=this.element;function q(Q){const re=I._mouseService.getMouseReportCoords(Q,I.screenElement);if(!re)return!1;let ie,he;switch(Q.overrideType||Q.type){case"mousemove":he=32,Q.buttons===void 0?(ie=3,Q.button!==void 0&&(ie=Q.button<3?Q.button:3)):ie=1&Q.buttons?0:4&Q.buttons?1:2&Q.buttons?2:3;break;case"mouseup":he=0,ie=Q.button<3?Q.button:3;break;case"mousedown":he=1,ie=Q.button<3?Q.button:3;break;case"wheel":if(I._customWheelEventHandler&&I._customWheelEventHandler(Q)===!1||I.viewport.getLinesScrolled(Q)===0)return!1;he=Q.deltaY<0?0:1,ie=4;break;default:return!1}return!(he===void 0||ie===void 0||ie>4)&&I.coreMouseService.triggerMouseEvent({col:re.col,row:re.row,x:re.x,y:re.y,button:ie,action:he,ctrl:Q.ctrlKey,alt:Q.altKey,shift:Q.shiftKey})}const W={mouseup:null,wheel:null,mousedrag:null,mousemove:null},X={mouseup:Q=>(q(Q),Q.buttons||(this._document.removeEventListener("mouseup",W.mouseup),W.mousedrag&&this._document.removeEventListener("mousemove",W.mousedrag)),this.cancel(Q)),wheel:Q=>(q(Q),this.cancel(Q,!0)),mousedrag:Q=>{Q.buttons&&q(Q)},mousemove:Q=>{Q.buttons||q(Q)}};this.register(this.coreMouseService.onProtocolChange(Q=>{Q?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(Q)),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()),8&Q?W.mousemove||(A.addEventListener("mousemove",X.mousemove),W.mousemove=X.mousemove):(A.removeEventListener("mousemove",W.mousemove),W.mousemove=null),16&Q?W.wheel||(A.addEventListener("wheel",X.wheel,{passive:!1}),W.wheel=X.wheel):(A.removeEventListener("wheel",W.wheel),W.wheel=null),2&Q?W.mouseup||(W.mouseup=X.mouseup):(this._document.removeEventListener("mouseup",W.mouseup),W.mouseup=null),4&Q?W.mousedrag||(W.mousedrag=X.mousedrag):(this._document.removeEventListener("mousemove",W.mousedrag),W.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,m.addDisposableDomListener)(A,"mousedown",Q=>{if(Q.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(Q))return q(Q),W.mouseup&&this._document.addEventListener("mouseup",W.mouseup),W.mousedrag&&this._document.addEventListener("mousemove",W.mousedrag),this.cancel(Q)})),this.register((0,m.addDisposableDomListener)(A,"wheel",Q=>{if(!W.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(Q)===!1)return!1;if(!this.buffer.hasScrollback){const re=this.viewport.getLinesScrolled(Q);if(re===0)return;const ie=K.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(Q.deltaY<0?"A":"B");let he="";for(let Ce=0;Ce{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(Q),this.cancel(Q)},{passive:!0})),this.register((0,m.addDisposableDomListener)(A,"touchmove",Q=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(Q)?void 0:this.cancel(Q)},{passive:!1}))}refresh(I,A){var q;(q=this._renderService)==null||q.refreshRows(I,A)}updateCursorStyle(I){var A;(A=this._selectionService)!=null&&A.shouldColumnSelect(I)?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(I,A,q=0){var W;q===1?(super.scrollLines(I,A,q),this.refresh(0,this.rows-1)):(W=this.viewport)==null||W.scrollLines(I)}paste(I){(0,d.paste)(I,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(I){this._customKeyEventHandler=I}attachCustomWheelEventHandler(I){this._customWheelEventHandler=I}registerLinkProvider(I){return this._linkProviderService.registerLinkProvider(I)}registerCharacterJoiner(I){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const A=this._characterJoinerService.register(I);return this.refresh(0,this.rows-1),A}deregisterCharacterJoiner(I){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(I)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(I){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+I)}registerDecoration(I){return this._decorationService.registerDecoration(I)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(I,A,q){this._selectionService.setSelection(I,A,q)}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(){var I;(I=this._selectionService)==null||I.clearSelection()}selectAll(){var I;(I=this._selectionService)==null||I.selectAll()}selectLines(I,A){var q;(q=this._selectionService)==null||q.selectLines(I,A)}_keyDown(I){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1)return!1;const A=this.browser.isMac&&this.options.macOptionIsMeta&&I.altKey;if(!A&&!this._compositionHelper.keydown(I))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;A||I.key!=="Dead"&&I.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const q=(0,$.evaluateKeyboardEvent)(I,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(I),q.type===3||q.type===2){const W=this.rows-1;return this.scrollLines(q.type===2?-W:W),this.cancel(I,!0)}return q.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,I)||(q.cancel&&this.cancel(I,!0),!q.key||!!(I.key&&!I.ctrlKey&&!I.altKey&&!I.metaKey&&I.key.length===1&&I.key.charCodeAt(0)>=65&&I.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(q.key!==K.C0.ETX&&q.key!==K.C0.CR||(this.textarea.value=""),this._onKey.fire({key:q.key,domEvent:I}),this._showCursor(),this.coreService.triggerDataEvent(q.key,!0),!this.optionsService.rawOptions.screenReaderMode||I.altKey||I.ctrlKey?this.cancel(I,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(I,A){const q=I.isMac&&!this.options.macOptionIsMeta&&A.altKey&&!A.ctrlKey&&!A.metaKey||I.isWindows&&A.altKey&&A.ctrlKey&&!A.metaKey||I.isWindows&&A.getModifierState("AltGraph");return A.type==="keypress"?q:q&&(!A.keyCode||A.keyCode>47)}_keyUp(I){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1||(function(A){return A.keyCode===16||A.keyCode===17||A.keyCode===18}(I)||this.focus(),this.updateCursorStyle(I),this._keyPressHandled=!1)}_keyPress(I){let A;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1)return!1;if(this.cancel(I),I.charCode)A=I.charCode;else if(I.which===null||I.which===void 0)A=I.keyCode;else{if(I.which===0||I.charCode===0)return!1;A=I.which}return!(!A||(I.altKey||I.ctrlKey||I.metaKey)&&!this._isThirdLevelShift(this.browser,I)||(A=String.fromCharCode(A),this._onKey.fire({key:A,domEvent:I}),this._showCursor(),this.coreService.triggerDataEvent(A,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(I){if(I.data&&I.inputType==="insertText"&&(!I.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const A=I.data;return this.coreService.triggerDataEvent(A,!0),this.cancel(I),!0}return!1}resize(I,A){I!==this.cols||A!==this.rows?super.resize(I,A):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(I,A){var q,W;(q=this._charSizeService)==null||q.measure(),(W=this.viewport)==null||W.syncScrollArea(!0)}clear(){var I;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 A=1;A{Object.defineProperty(o,"__esModule",{value:!0}),o.TimeBasedDebouncer=void 0,o.TimeBasedDebouncer=class{constructor(u,d=1e3){this._renderCallback=u,this._debounceThresholdMS=d,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(u,d,m){this._rowCount=m,u=u!==void 0?u:0,d=d!==void 0?d:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,d):d;const f=Date.now();if(f-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=f,this._innerRefresh();else if(!this._additionalRefreshRequested){const g=f-this._lastRefreshMs,w=this._debounceThresholdMS-g;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},w)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const u=Math.max(this._rowStart,0),d=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,d)}}},1680:function(y,o,u){var d=this&&this.__decorate||function(c,a,l,_){var j,b=arguments.length,k=b<3?a:_===null?_=Object.getOwnPropertyDescriptor(a,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(c,a,l,_);else for(var x=c.length-1;x>=0;x--)(j=c[x])&&(k=(b<3?j(k):b>3?j(a,l,k):j(a,l))||k);return b>3&&k&&Object.defineProperty(a,l,k),k},m=this&&this.__param||function(c,a){return function(l,_){a(l,_,c)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Viewport=void 0;const f=u(3656),g=u(4725),w=u(8460),S=u(844),v=u(2585);let p=o.Viewport=class extends S.Disposable{constructor(c,a,l,_,j,b,k,x){super(),this._viewportElement=c,this._scrollArea=a,this._bufferService=l,this._optionsService=_,this._charSizeService=j,this._renderService=b,this._coreBrowserService=k,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new w.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,f.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(N=>this._activeBuffer=N.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(N=>this._renderDimensions=N)),this._handleThemeChange(x.colors),this.register(x.onChangeColors(N=>this._handleThemeChange(N))),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.syncScrollArea())),setTimeout(()=>this.syncScrollArea())}_handleThemeChange(c){this._viewportElement.style.backgroundColor=c.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame(()=>this.syncScrollArea())}_refresh(c){if(c)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const a=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==a&&(this._lastRecordedBufferHeight=a,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const c=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==c&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=c),this._refreshAnimationFrame=null}syncScrollArea(c=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(c);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(c)}_handleScroll(c){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const a=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:a,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const c=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(c*(this._smoothScrollState.target-this._smoothScrollState.origin)),c<1?this._coreBrowserService.window.requestAnimationFrame(()=>this._smoothScroll()):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(c,a){const l=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(a<0&&this._viewportElement.scrollTop!==0||a>0&&l0&&(l=T),_=""}}return{bufferElements:j,cursorElement:l}}getLinesScrolled(c){if(c.deltaY===0||c.shiftKey)return 0;let a=this._applyScrollModifier(c.deltaY,c);return c.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=this._currentRowHeight+0,this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):c.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(c,a){const l=this._optionsService.rawOptions.fastScrollModifier;return l==="alt"&&a.altKey||l==="ctrl"&&a.ctrlKey||l==="shift"&&a.shiftKey?c*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:c*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(c){this._lastTouchY=c.touches[0].pageY}handleTouchMove(c){const a=this._lastTouchY-c.touches[0].pageY;return this._lastTouchY=c.touches[0].pageY,a!==0&&(this._viewportElement.scrollTop+=a,this._bubbleScroll(c,a))}};o.Viewport=p=d([m(2,v.IBufferService),m(3,v.IOptionsService),m(4,g.ICharSizeService),m(5,g.IRenderService),m(6,g.ICoreBrowserService),m(7,g.IThemeService)],p)},3107:function(y,o,u){var d=this&&this.__decorate||function(v,p,c,a){var l,_=arguments.length,j=_<3?p:a===null?a=Object.getOwnPropertyDescriptor(p,c):a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(v,p,c,a);else for(var b=v.length-1;b>=0;b--)(l=v[b])&&(j=(_<3?l(j):_>3?l(p,c,j):l(p,c))||j);return _>3&&j&&Object.defineProperty(p,c,j),j},m=this&&this.__param||function(v,p){return function(c,a){p(c,a,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferDecorationRenderer=void 0;const f=u(4725),g=u(844),w=u(2585);let S=o.BufferDecorationRenderer=class extends g.Disposable{constructor(v,p,c,a,l){super(),this._screenElement=v,this._bufferService=p,this._coreBrowserService=c,this._decorationService=a,this._renderService=l,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(_=>this._removeDecoration(_))),this.register((0,g.toDisposable)(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(const v of this._decorationService.decorations)this._renderDecoration(v);this._dimensionsChanged=!1}_renderDecoration(v){this._refreshStyle(v),this._dimensionsChanged&&this._refreshXPosition(v)}_createElement(v){var a;const p=this._coreBrowserService.mainDocument.createElement("div");p.classList.add("xterm-decoration"),p.classList.toggle("xterm-decoration-top-layer",((a=v==null?void 0:v.options)==null?void 0:a.layer)==="top"),p.style.width=`${Math.round((v.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,p.style.height=(v.options.height||1)*this._renderService.dimensions.css.cell.height+"px",p.style.top=(v.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",p.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const c=v.options.x??0;return c&&c>this._bufferService.cols&&(p.style.display="none"),this._refreshXPosition(v,p),p}_refreshStyle(v){const p=v.marker.line-this._bufferService.buffers.active.ydisp;if(p<0||p>=this._bufferService.rows)v.element&&(v.element.style.display="none",v.onRenderEmitter.fire(v.element));else{let c=this._decorationElements.get(v);c||(c=this._createElement(v),v.element=c,this._decorationElements.set(v,c),this._container.appendChild(c),v.onDispose(()=>{this._decorationElements.delete(v),c.remove()})),c.style.top=p*this._renderService.dimensions.css.cell.height+"px",c.style.display=this._altBufferIsActive?"none":"block",v.onRenderEmitter.fire(c)}}_refreshXPosition(v,p=v.element){if(!p)return;const c=v.options.x??0;(v.options.anchor||"left")==="right"?p.style.right=c?c*this._renderService.dimensions.css.cell.width+"px":"":p.style.left=c?c*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(v){var p;(p=this._decorationElements.get(v))==null||p.remove(),this._decorationElements.delete(v),v.dispose()}};o.BufferDecorationRenderer=S=d([m(1,w.IBufferService),m(2,f.ICoreBrowserService),m(3,w.IDecorationService),m(4,f.IRenderService)],S)},5871:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorZoneStore=void 0,o.ColorZoneStore=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(u){if(u.options.overviewRulerOptions){for(const d of this._zones)if(d.color===u.options.overviewRulerOptions.color&&d.position===u.options.overviewRulerOptions.position){if(this._lineIntersectsZone(d,u.marker.line))return;if(this._lineAdjacentToZone(d,u.marker.line,u.options.overviewRulerOptions.position))return void this._addLineToZone(d,u.marker.line)}if(this._zonePoolIndex=u.startBufferLine&&d<=u.endBufferLine}_lineAdjacentToZone(u,d,m){return d>=u.startBufferLine-this._linePadding[m||"full"]&&d<=u.endBufferLine+this._linePadding[m||"full"]}_addLineToZone(u,d){u.startBufferLine=Math.min(u.startBufferLine,d),u.endBufferLine=Math.max(u.endBufferLine,d)}}},5744:function(y,o,u){var d=this&&this.__decorate||function(l,_,j,b){var k,x=arguments.length,N=x<3?_:b===null?b=Object.getOwnPropertyDescriptor(_,j):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(l,_,j,b);else for(var E=l.length-1;E>=0;E--)(k=l[E])&&(N=(x<3?k(N):x>3?k(_,j,N):k(_,j))||N);return x>3&&N&&Object.defineProperty(_,j,N),N},m=this&&this.__param||function(l,_){return function(j,b){_(j,b,l)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OverviewRulerRenderer=void 0;const f=u(5871),g=u(4725),w=u(844),S=u(2585),v={full:0,left:0,center:0,right:0},p={full:0,left:0,center:0,right:0},c={full:0,left:0,center:0,right:0};let a=o.OverviewRulerRenderer=class extends w.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(l,_,j,b,k,x,N){var L;super(),this._viewportElement=l,this._screenElement=_,this._bufferService=j,this._decorationService=b,this._renderService=k,this._optionsService=x,this._coreBrowserService=N,this._colorZoneStore=new f.ColorZoneStore,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(),(L=this._viewportElement.parentElement)==null||L.insertBefore(this._canvas,this._viewportElement);const E=this._canvas.getContext("2d");if(!E)throw new Error("Ctx cannot be null");this._ctx=E,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,w.toDisposable)(()=>{var T;(T=this._canvas)==null||T.remove()}))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this.register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0)))}_registerBufferChangeListeners(){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())}))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender(()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",()=>this._queueRefresh(!0))),this.register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const l=Math.floor(this._canvas.width/3),_=Math.ceil(this._canvas.width/3);p.full=this._canvas.width,p.left=l,p.center=_,p.right=l,this._refreshDrawHeightConstants(),c.full=0,c.left=0,c.center=p.left,c.right=p.left+p.center}_refreshDrawHeightConstants(){v.full=Math.round(2*this._coreBrowserService.dpr);const l=this._canvas.height/this._bufferService.buffer.lines.length,_=Math.round(Math.max(Math.min(l,12),6)*this._coreBrowserService.dpr);v.left=_,v.center=_,v.right=_}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.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(const _ of this._decorationService.decorations)this._colorZoneStore.addDecoration(_);this._ctx.lineWidth=1;const l=this._colorZoneStore.zones;for(const _ of l)_.position!=="full"&&this._renderColorZone(_);for(const _ of l)_.position==="full"&&this._renderColorZone(_);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(l){this._ctx.fillStyle=l.color,this._ctx.fillRect(c[l.position||"full"],Math.round((this._canvas.height-1)*(l.startBufferLine/this._bufferService.buffers.active.lines.length)-v[l.position||"full"]/2),p[l.position||"full"],Math.round((this._canvas.height-1)*((l.endBufferLine-l.startBufferLine)/this._bufferService.buffers.active.lines.length)+v[l.position||"full"]))}_queueRefresh(l,_){this._shouldUpdateDimensions=l||this._shouldUpdateDimensions,this._shouldUpdateAnchor=_||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};o.OverviewRulerRenderer=a=d([m(2,S.IBufferService),m(3,S.IDecorationService),m(4,g.IRenderService),m(5,S.IOptionsService),m(6,g.ICoreBrowserService)],a)},2950:function(y,o,u){var d=this&&this.__decorate||function(v,p,c,a){var l,_=arguments.length,j=_<3?p:a===null?a=Object.getOwnPropertyDescriptor(p,c):a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(v,p,c,a);else for(var b=v.length-1;b>=0;b--)(l=v[b])&&(j=(_<3?l(j):_>3?l(p,c,j):l(p,c))||j);return _>3&&j&&Object.defineProperty(p,c,j),j},m=this&&this.__param||function(v,p){return function(c,a){p(c,a,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CompositionHelper=void 0;const f=u(4725),g=u(2585),w=u(2584);let S=o.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(v,p,c,a,l,_){this._textarea=v,this._compositionView=p,this._bufferService=c,this._optionsService=a,this._coreService=l,this._renderService=_,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(v){this._compositionView.textContent=v.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(v){if(this._isComposing||this._isSendingComposition){if(v.keyCode===229||v.keyCode===16||v.keyCode===17||v.keyCode===18)return!1;this._finalizeComposition(!1)}return v.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(v){if(this._compositionView.classList.remove("active"),this._isComposing=!1,v){const p={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let c;this._isSendingComposition=!1,p.start+=this._dataAlreadySent.length,c=this._isComposing?this._textarea.value.substring(p.start,p.end):this._textarea.value.substring(p.start),c.length>0&&this._coreService.triggerDataEvent(c,!0)}},0)}else{this._isSendingComposition=!1;const p=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(p,!0)}}_handleAnyTextareaChanges(){const v=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const p=this._textarea.value,c=p.replace(v,"");this._dataAlreadySent=c,p.length>v.length?this._coreService.triggerDataEvent(c,!0):p.lengththis.updateCompositionElements(!0),0)}}};o.CompositionHelper=S=d([m(2,g.IBufferService),m(3,g.IOptionsService),m(4,g.ICoreService),m(5,f.IRenderService)],S)},9806:(y,o)=>{function u(d,m,f){const g=f.getBoundingClientRect(),w=d.getComputedStyle(f),S=parseInt(w.getPropertyValue("padding-left")),v=parseInt(w.getPropertyValue("padding-top"));return[m.clientX-g.left-S,m.clientY-g.top-v]}Object.defineProperty(o,"__esModule",{value:!0}),o.getCoords=o.getCoordsRelativeToElement=void 0,o.getCoordsRelativeToElement=u,o.getCoords=function(d,m,f,g,w,S,v,p,c){if(!S)return;const a=u(d,m,f);return a?(a[0]=Math.ceil((a[0]+(c?v/2:0))/v),a[1]=Math.ceil(a[1]/p),a[0]=Math.min(Math.max(a[0],1),g+(c?1:0)),a[1]=Math.min(Math.max(a[1],1),w),a):void 0}},9504:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.moveToCellSequence=void 0;const d=u(2584);function m(p,c,a,l){const _=p-f(p,a),j=c-f(c,a),b=Math.abs(_-j)-function(k,x,N){let E=0;const L=k-f(k,N),T=x-f(x,N);for(let O=0;O=0&&pc?"A":"B"}function w(p,c,a,l,_,j){let b=p,k=c,x="";for(;b!==a||k!==l;)b+=_?1:-1,_&&b>j.cols-1?(x+=j.buffer.translateBufferLineToString(k,!1,p,b),b=0,p=0,k++):!_&&b<0&&(x+=j.buffer.translateBufferLineToString(k,!1,0,p+1),b=j.cols-1,p=b,k--);return x+j.buffer.translateBufferLineToString(k,!1,p,b)}function S(p,c){const a=c?"O":"[";return d.C0.ESC+a+p}function v(p,c){p=Math.floor(p);let a="";for(let l=0;l0?L-f(L,T):N;const F=L,z=function(K,$,R,D,M,P){let U;return U=m(R,D,M,P).length>0?D-f(D,M):$,K=R&&Up?"D":"C",v(Math.abs(_-p),S(b,l));b=j>c?"D":"C";const k=Math.abs(j-c);return v(function(x,N){return N.cols-x}(j>c?p:_,a)+(k-1)*a.cols+1+((j>c?_:p)-1),S(b,l))}},1296:function(y,o,u){var d=this&&this.__decorate||function(O,B,F,z){var K,$=arguments.length,R=$<3?B:z===null?z=Object.getOwnPropertyDescriptor(B,F):z;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(O,B,F,z);else for(var D=O.length-1;D>=0;D--)(K=O[D])&&(R=($<3?K(R):$>3?K(B,F,R):K(B,F))||R);return $>3&&R&&Object.defineProperty(B,F,R),R},m=this&&this.__param||function(O,B){return function(F,z){B(F,z,O)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRenderer=void 0;const f=u(3787),g=u(2550),w=u(2223),S=u(6171),v=u(6052),p=u(4725),c=u(8055),a=u(8460),l=u(844),_=u(2585),j="xterm-dom-renderer-owner-",b="xterm-rows",k="xterm-fg-",x="xterm-bg-",N="xterm-focus",E="xterm-selection";let L=1,T=o.DomRenderer=class extends l.Disposable{constructor(O,B,F,z,K,$,R,D,M,P,U,Y,H){super(),this._terminal=O,this._document=B,this._element=F,this._screenElement=z,this._viewportElement=K,this._helperContainer=$,this._linkifier2=R,this._charSizeService=M,this._optionsService=P,this._bufferService=U,this._coreBrowserService=Y,this._themeService=H,this._terminalClass=L++,this._rowElements=[],this._selectionRenderModel=(0,v.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new a.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(b),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(E),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,S.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(J=>this._injectCss(J))),this._injectCss(this._themeService.colors),this._rowFactory=D.createInstance(f.DomRendererRowFactory,document),this._element.classList.add(j+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(J=>this._handleLinkHover(J))),this.register(this._linkifier2.onHideLinkUnderline(J=>this._handleLinkLeave(J))),this.register((0,l.toDisposable)(()=>{this._element.classList.remove(j+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new g.WidthCache(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(){const O=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*O,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*O),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/O),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/O),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(const F of this._rowElements)F.style.width=`${this.dimensions.css.canvas.width}px`,F.style.height=`${this.dimensions.css.cell.height}px`,F.style.lineHeight=`${this.dimensions.css.cell.height}px`,F.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const B=`${this._terminalSelector} .${b} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=B,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(O){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let B=`${this._terminalSelector} .${b} { color: ${O.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;B+=`${this._terminalSelector} .${b} .xterm-dim { color: ${c.color.multiplyOpacity(O.foreground,.5).css};}`,B+=`${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;}`;const F=`blink_underline_${this._terminalClass}`,z=`blink_bar_${this._terminalClass}`,K=`blink_block_${this._terminalClass}`;B+=`@keyframes ${F} { 50% { border-bottom-style: hidden; }}`,B+=`@keyframes ${z} { 50% { box-shadow: none; }}`,B+=`@keyframes ${K} { 0% { background-color: ${O.cursor.css}; color: ${O.cursorAccent.css}; } 50% { background-color: inherit; color: ${O.cursor.css}; }}`,B+=`${this._terminalSelector} .${b}.${N} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${F} 1s step-end infinite;}${this._terminalSelector} .${b}.${N} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${z} 1s step-end infinite;}${this._terminalSelector} .${b}.${N} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${K} 1s step-end infinite;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-block { background-color: ${O.cursor.css}; color: ${O.cursorAccent.css};}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${O.cursor.css} !important; color: ${O.cursorAccent.css} !important;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${O.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${O.cursor.css} inset;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${O.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,B+=`${this._terminalSelector} .${E} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${E} div { position: absolute; background-color: ${O.selectionBackgroundOpaque.css};}${this._terminalSelector} .${E} div { position: absolute; background-color: ${O.selectionInactiveBackgroundOpaque.css};}`;for(const[$,R]of O.ansi.entries())B+=`${this._terminalSelector} .${k}${$} { color: ${R.css}; }${this._terminalSelector} .${k}${$}.xterm-dim { color: ${c.color.multiplyOpacity(R,.5).css}; }${this._terminalSelector} .${x}${$} { background-color: ${R.css}; }`;B+=`${this._terminalSelector} .${k}${w.INVERTED_DEFAULT_COLOR} { color: ${c.color.opaque(O.background).css}; }${this._terminalSelector} .${k}${w.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${c.color.multiplyOpacity(c.color.opaque(O.background),.5).css}; }${this._terminalSelector} .${x}${w.INVERTED_DEFAULT_COLOR} { background-color: ${O.foreground.css}; }`,this._themeStyleElement.textContent=B}_setDefaultSpacing(){const O=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${O}px`,this._rowFactory.defaultSpacing=O}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(O,B){for(let F=this._rowElements.length;F<=B;F++){const z=this._document.createElement("div");this._rowContainer.appendChild(z),this._rowElements.push(z)}for(;this._rowElements.length>B;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(O,B){this._refreshRowElements(O,B),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(N),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(N),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(O,B,F){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(O,B,F),this.renderRows(0,this._bufferService.rows-1),!O||!B)return;this._selectionRenderModel.update(this._terminal,O,B,F);const z=this._selectionRenderModel.viewportStartRow,K=this._selectionRenderModel.viewportEndRow,$=this._selectionRenderModel.viewportCappedStartRow,R=this._selectionRenderModel.viewportCappedEndRow;if($>=this._bufferService.rows||R<0)return;const D=this._document.createDocumentFragment();if(F){const M=O[0]>B[0];D.appendChild(this._createSelectionElement($,M?B[0]:O[0],M?O[0]:B[0],R-$+1))}else{const M=z===$?O[0]:0,P=$===K?B[0]:this._bufferService.cols;D.appendChild(this._createSelectionElement($,M,P));const U=R-$-1;if(D.appendChild(this._createSelectionElement($+1,0,this._bufferService.cols,U)),$!==R){const Y=K===R?B[0]:this._bufferService.cols;D.appendChild(this._createSelectionElement(R,0,Y))}}this._selectionContainer.appendChild(D)}_createSelectionElement(O,B,F,z=1){const K=this._document.createElement("div"),$=B*this.dimensions.css.cell.width;let R=this.dimensions.css.cell.width*(F-B);return $+R>this.dimensions.css.canvas.width&&(R=this.dimensions.css.canvas.width-$),K.style.height=z*this.dimensions.css.cell.height+"px",K.style.top=O*this.dimensions.css.cell.height+"px",K.style.left=`${$}px`,K.style.width=`${R}px`,K}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(const O of this._rowElements)O.replaceChildren()}renderRows(O,B){const F=this._bufferService.buffer,z=F.ybase+F.y,K=Math.min(F.x,this._bufferService.cols-1),$=this._optionsService.rawOptions.cursorBlink,R=this._optionsService.rawOptions.cursorStyle,D=this._optionsService.rawOptions.cursorInactiveStyle;for(let M=O;M<=B;M++){const P=M+F.ydisp,U=this._rowElements[M],Y=F.lines.get(P);if(!U||!Y)break;U.replaceChildren(...this._rowFactory.createRow(Y,P,P===z,R,D,K,$,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${j}${this._terminalClass}`}_handleLinkHover(O){this._setCellUnderline(O.x1,O.x2,O.y1,O.y2,O.cols,!0)}_handleLinkLeave(O){this._setCellUnderline(O.x1,O.x2,O.y1,O.y2,O.cols,!1)}_setCellUnderline(O,B,F,z,K,$){F<0&&(O=0),z<0&&(B=0);const R=this._bufferService.rows-1;F=Math.max(Math.min(F,R),0),z=Math.max(Math.min(z,R),0),K=Math.min(K,this._bufferService.cols);const D=this._bufferService.buffer,M=D.ybase+D.y,P=Math.min(D.x,K-1),U=this._optionsService.rawOptions.cursorBlink,Y=this._optionsService.rawOptions.cursorStyle,H=this._optionsService.rawOptions.cursorInactiveStyle;for(let J=F;J<=z;++J){const I=J+D.ydisp,A=this._rowElements[J],q=D.lines.get(I);if(!A||!q)break;A.replaceChildren(...this._rowFactory.createRow(q,I,I===M,Y,H,P,U,this.dimensions.css.cell.width,this._widthCache,$?J===F?O:0:-1,$?(J===z?B:K)-1:-1))}}};o.DomRenderer=T=d([m(7,_.IInstantiationService),m(8,p.ICharSizeService),m(9,_.IOptionsService),m(10,_.IBufferService),m(11,p.ICoreBrowserService),m(12,p.IThemeService)],T)},3787:function(y,o,u){var d=this&&this.__decorate||function(b,k,x,N){var E,L=arguments.length,T=L<3?k:N===null?N=Object.getOwnPropertyDescriptor(k,x):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(b,k,x,N);else for(var O=b.length-1;O>=0;O--)(E=b[O])&&(T=(L<3?E(T):L>3?E(k,x,T):E(k,x))||T);return L>3&&T&&Object.defineProperty(k,x,T),T},m=this&&this.__param||function(b,k){return function(x,N){k(x,N,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRendererRowFactory=void 0;const f=u(2223),g=u(643),w=u(511),S=u(2585),v=u(8055),p=u(4725),c=u(4269),a=u(6171),l=u(3734);let _=o.DomRendererRowFactory=class{constructor(b,k,x,N,E,L,T){this._document=b,this._characterJoinerService=k,this._optionsService=x,this._coreBrowserService=N,this._coreService=E,this._decorationService=L,this._themeService=T,this._workCell=new w.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(b,k,x){this._selectionStart=b,this._selectionEnd=k,this._columnSelectMode=x}createRow(b,k,x,N,E,L,T,O,B,F,z){const K=[],$=this._characterJoinerService.getJoinedCharacters(k),R=this._themeService.colors;let D,M=b.getNoBgTrimmedLength();x&&M0&&re===$[0][0]){he=!0;const pe=$.shift();ae=new c.JoinedCellData(this._workCell,b.translateToString(!0,pe[0],pe[1]),pe[1]-pe[0]),Ce=pe[1]-1,ie=ae.getWidth()}const dt=this._isCellInSelection(re,k),wt=x&&re===L,nt=Q&&re>=F&&re<=z;let ft=!1;this._decorationService.forEachDecorationAtCell(re,k,void 0,pe=>{ft=!0});let Ie=ae.getChars()||g.WHITESPACE_CELL_CHAR;if(Ie===" "&&(ae.isUnderline()||ae.isOverline())&&(Ie=" "),W=ie*O-B.get(Ie,ae.isBold(),ae.isItalic()),D){if(P&&(dt&&q||!dt&&!q&&ae.bg===Y)&&(dt&&q&&R.selectionForeground||ae.fg===H)&&ae.extended.ext===J&&nt===I&&W===A&&!wt&&!he&&!ft){ae.isInvisible()?U+=g.WHITESPACE_CELL_CHAR:U+=Ie,P++;continue}P&&(D.textContent=U),D=this._document.createElement("span"),P=0,U=""}else D=this._document.createElement("span");if(Y=ae.bg,H=ae.fg,J=ae.extended.ext,I=nt,A=W,q=dt,he&&L>=re&&L<=Ce&&(L=re),!this._coreService.isCursorHidden&&wt&&this._coreService.isCursorInitialized){if(X.push("xterm-cursor"),this._coreBrowserService.isFocused)T&&X.push("xterm-cursor-blink"),X.push(N==="bar"?"xterm-cursor-bar":N==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(E)switch(E){case"outline":X.push("xterm-cursor-outline");break;case"block":X.push("xterm-cursor-block");break;case"bar":X.push("xterm-cursor-bar");break;case"underline":X.push("xterm-cursor-underline")}}if(ae.isBold()&&X.push("xterm-bold"),ae.isItalic()&&X.push("xterm-italic"),ae.isDim()&&X.push("xterm-dim"),U=ae.isInvisible()?g.WHITESPACE_CELL_CHAR:ae.getChars()||g.WHITESPACE_CELL_CHAR,ae.isUnderline()&&(X.push(`xterm-underline-${ae.extended.underlineStyle}`),U===" "&&(U=" "),!ae.isUnderlineColorDefault()))if(ae.isUnderlineColorRGB())D.style.textDecorationColor=`rgb(${l.AttributeData.toColorRGB(ae.getUnderlineColor()).join(",")})`;else{let pe=ae.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&ae.isBold()&&pe<8&&(pe+=8),D.style.textDecorationColor=R.ansi[pe].css}ae.isOverline()&&(X.push("xterm-overline"),U===" "&&(U=" ")),ae.isStrikethrough()&&X.push("xterm-strikethrough"),nt&&(D.style.textDecoration="underline");let Le=ae.getFgColor(),G=ae.getFgColorMode(),te=ae.getBgColor(),Se=ae.getBgColorMode();const Ut=!!ae.isInverse();if(Ut){const pe=Le;Le=te,te=pe;const Ls=G;G=Se,Se=Ls}let Te,Rs,bt,Lt=!1;switch(this._decorationService.forEachDecorationAtCell(re,k,void 0,pe=>{pe.options.layer!=="top"&&Lt||(pe.backgroundColorRGB&&(Se=50331648,te=pe.backgroundColorRGB.rgba>>8&16777215,Te=pe.backgroundColorRGB),pe.foregroundColorRGB&&(G=50331648,Le=pe.foregroundColorRGB.rgba>>8&16777215,Rs=pe.foregroundColorRGB),Lt=pe.options.layer==="top")}),!Lt&&dt&&(Te=this._coreBrowserService.isFocused?R.selectionBackgroundOpaque:R.selectionInactiveBackgroundOpaque,te=Te.rgba>>8&16777215,Se=50331648,Lt=!0,R.selectionForeground&&(G=50331648,Le=R.selectionForeground.rgba>>8&16777215,Rs=R.selectionForeground)),Lt&&X.push("xterm-decoration-top"),Se){case 16777216:case 33554432:bt=R.ansi[te],X.push(`xterm-bg-${te}`);break;case 50331648:bt=v.channels.toColor(te>>16,te>>8&255,255&te),this._addStyle(D,`background-color:#${j((te>>>0).toString(16),"0",6)}`);break;default:Ut?(bt=R.foreground,X.push(`xterm-bg-${f.INVERTED_DEFAULT_COLOR}`)):bt=R.background}switch(Te||ae.isDim()&&(Te=v.color.multiplyOpacity(bt,.5)),G){case 16777216:case 33554432:ae.isBold()&&Le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Le+=8),this._applyMinimumContrast(D,bt,R.ansi[Le],ae,Te,void 0)||X.push(`xterm-fg-${Le}`);break;case 50331648:const pe=v.channels.toColor(Le>>16&255,Le>>8&255,255&Le);this._applyMinimumContrast(D,bt,pe,ae,Te,Rs)||this._addStyle(D,`color:#${j(Le.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(D,bt,R.foreground,ae,Te,Rs)||Ut&&X.push(`xterm-fg-${f.INVERTED_DEFAULT_COLOR}`)}X.length&&(D.className=X.join(" "),X.length=0),wt||he||ft?D.textContent=U:P++,W!==this.defaultSpacing&&(D.style.letterSpacing=`${W}px`),K.push(D),re=Ce}return D&&P&&(D.textContent=U),K}_applyMinimumContrast(b,k,x,N,E,L){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,a.treatGlyphAsBackgroundColor)(N.getCode()))return!1;const T=this._getContrastCache(N);let O;if(E||L||(O=T.getColor(k.rgba,x.rgba)),O===void 0){const B=this._optionsService.rawOptions.minimumContrastRatio/(N.isDim()?2:1);O=v.color.ensureContrastRatio(E||k,L||x,B),T.setColor((E||k).rgba,(L||x).rgba,O??null)}return!!O&&(this._addStyle(b,`color:${O.css}`),!0)}_getContrastCache(b){return b.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(b,k){b.setAttribute("style",`${b.getAttribute("style")||""}${k};`)}_isCellInSelection(b,k){const x=this._selectionStart,N=this._selectionEnd;return!(!x||!N)&&(this._columnSelectMode?x[0]<=N[0]?b>=x[0]&&k>=x[1]&&b=x[1]&&b>=N[0]&&k<=N[1]:k>x[1]&&k=x[0]&&b=x[0])}};function j(b,k,x){for(;b.length{Object.defineProperty(o,"__esModule",{value:!0}),o.WidthCache=void 0,o.WidthCache=class{constructor(u,d){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=u.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const m=u.createElement("span");m.classList.add("xterm-char-measure-element");const f=u.createElement("span");f.classList.add("xterm-char-measure-element"),f.style.fontWeight="bold";const g=u.createElement("span");g.classList.add("xterm-char-measure-element"),g.style.fontStyle="italic";const w=u.createElement("span");w.classList.add("xterm-char-measure-element"),w.style.fontWeight="bold",w.style.fontStyle="italic",this._measureElements=[m,f,g,w],this._container.appendChild(m),this._container.appendChild(f),this._container.appendChild(g),this._container.appendChild(w),d.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(u,d,m,f){u===this._font&&d===this._fontSize&&m===this._weight&&f===this._weightBold||(this._font=u,this._fontSize=d,this._weight=m,this._weightBold=f,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${m}`,this._measureElements[1].style.fontWeight=`${f}`,this._measureElements[2].style.fontWeight=`${m}`,this._measureElements[3].style.fontWeight=`${f}`,this.clear())}get(u,d,m){let f=0;if(!d&&!m&&u.length===1&&(f=u.charCodeAt(0))<256){if(this._flat[f]!==-9999)return this._flat[f];const S=this._measure(u,0);return S>0&&(this._flat[f]=S),S}let g=u;d&&(g+="B"),m&&(g+="I");let w=this._holey.get(g);if(w===void 0){let S=0;d&&(S|=1),m&&(S|=2),w=this._measure(u,S),w>0&&this._holey.set(g,w)}return w}_measure(u,d){const m=this._measureElements[d];return m.textContent=u.repeat(32),m.offsetWidth/32}}},2223:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TEXT_BASELINE=o.DIM_OPACITY=o.INVERTED_DEFAULT_COLOR=void 0;const d=u(6114);o.INVERTED_DEFAULT_COLOR=257,o.DIM_OPACITY=.5,o.TEXT_BASELINE=d.isFirefox||d.isLegacyEdge?"bottom":"ideographic"},6171:(y,o)=>{function u(m){return 57508<=m&&m<=57558}function d(m){return m>=128512&&m<=128591||m>=127744&&m<=128511||m>=128640&&m<=128767||m>=9728&&m<=9983||m>=9984&&m<=10175||m>=65024&&m<=65039||m>=129280&&m<=129535||m>=127462&&m<=127487}Object.defineProperty(o,"__esModule",{value:!0}),o.computeNextVariantOffset=o.createRenderDimensions=o.treatGlyphAsBackgroundColor=o.allowRescaling=o.isEmoji=o.isRestrictedPowerlineGlyph=o.isPowerlineGlyph=o.throwIfFalsy=void 0,o.throwIfFalsy=function(m){if(!m)throw new Error("value must not be falsy");return m},o.isPowerlineGlyph=u,o.isRestrictedPowerlineGlyph=function(m){return 57520<=m&&m<=57527},o.isEmoji=d,o.allowRescaling=function(m,f,g,w){return f===1&&g>Math.ceil(1.5*w)&&m!==void 0&&m>255&&!d(m)&&!u(m)&&!function(S){return 57344<=S&&S<=63743}(m)},o.treatGlyphAsBackgroundColor=function(m){return u(m)||function(f){return 9472<=f&&f<=9631}(m)},o.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},o.computeNextVariantOffset=function(m,f,g=0){return(m-(2*Math.round(f)-g))%(2*Math.round(f))}},6052:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createSelectionRenderModel=void 0;class u{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(m,f,g,w=!1){if(this.selectionStart=f,this.selectionEnd=g,!f||!g||f[0]===g[0]&&f[1]===g[1])return void this.clear();const S=m.buffers.active.ydisp,v=f[1]-S,p=g[1]-S,c=Math.max(v,0),a=Math.min(p,m.rows-1);c>=m.rows||a<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=w,this.viewportStartRow=v,this.viewportEndRow=p,this.viewportCappedStartRow=c,this.viewportCappedEndRow=a,this.startCol=f[0],this.endCol=g[0])}isCellSelected(m,f,g){return!!this.hasSelection&&(g-=m.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?f>=this.startCol&&g>=this.viewportCappedStartRow&&f=this.viewportCappedStartRow&&f>=this.endCol&&g<=this.viewportCappedEndRow:g>this.viewportStartRow&&g=this.startCol&&f=this.startCol)}}o.createSelectionRenderModel=function(){return new u}},456:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionModel=void 0,o.SelectionModel=class{constructor(u){this._bufferService=u,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?u%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)-1]:[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[u,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[Math.max(u,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const u=this.selectionStart,d=this.selectionEnd;return!(!u||!d)&&(u[1]>d[1]||u[1]===d[1]&&u[0]>d[0])}handleTrim(u){return this.selectionStart&&(this.selectionStart[1]-=u),this.selectionEnd&&(this.selectionEnd[1]-=u),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharSizeService=void 0;const f=u(2585),g=u(8460),w=u(844);let S=o.CharSizeService=class extends w.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(a,l,_){super(),this._optionsService=_,this.width=0,this.height=0,this._onCharSizeChange=this.register(new g.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new c(this._optionsService))}catch{this._measureStrategy=this.register(new p(a,l,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const a=this._measureStrategy.measure();a.width===this.width&&a.height===this.height||(this.width=a.width,this.height=a.height,this._onCharSizeChange.fire())}};o.CharSizeService=S=d([m(2,f.IOptionsService)],S);class v extends w.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(l,_){l!==void 0&&l>0&&_!==void 0&&_>0&&(this._result.width=l,this._result.height=_)}}class p extends v{constructor(l,_,j){super(),this._document=l,this._parentElement=_,this._optionsService=j,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}}class c extends v{constructor(l){super(),this._optionsService=l,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const _=this._ctx.measureText("W");if(!("width"in _&&"fontBoundingBoxAscent"in _&&"fontBoundingBoxDescent"in _))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const l=this._ctx.measureText("W");return this._validateAndSet(l.width,l.fontBoundingBoxAscent+l.fontBoundingBoxDescent),this._result}}},4269:function(y,o,u){var d=this&&this.__decorate||function(c,a,l,_){var j,b=arguments.length,k=b<3?a:_===null?_=Object.getOwnPropertyDescriptor(a,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(c,a,l,_);else for(var x=c.length-1;x>=0;x--)(j=c[x])&&(k=(b<3?j(k):b>3?j(a,l,k):j(a,l))||k);return b>3&&k&&Object.defineProperty(a,l,k),k},m=this&&this.__param||function(c,a){return function(l,_){a(l,_,c)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharacterJoinerService=o.JoinedCellData=void 0;const f=u(3734),g=u(643),w=u(511),S=u(2585);class v extends f.AttributeData{constructor(a,l,_){super(),this.content=0,this.combinedData="",this.fg=a.fg,this.bg=a.bg,this.combinedData=l,this._width=_}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(a){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.JoinedCellData=v;let p=o.CharacterJoinerService=class kd{constructor(a){this._bufferService=a,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new w.CellData}register(a){const l={id:this._nextCharacterJoinerId++,handler:a};return this._characterJoiners.push(l),l.id}deregister(a){for(let l=0;l1){const T=this._getJoinedRanges(j,x,k,l,b);for(let O=0;O1){const L=this._getJoinedRanges(j,x,k,l,b);for(let T=0;T{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreBrowserService=void 0;const d=u(844),m=u(8460),f=u(3656);class g extends d.Disposable{constructor(v,p,c){super(),this._textarea=v,this._window=p,this.mainDocument=c,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new w(this._window),this._onDprChange=this.register(new m.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new m.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange(a=>this._screenDprMonitor.setWindow(a))),this.register((0,m.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",()=>this._isFocused=!0),this._textarea.addEventListener("blur",()=>this._isFocused=!1)}get window(){return this._window}set window(v){this._window!==v&&(this._window=v,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}}o.CoreBrowserService=g;class w extends d.Disposable{constructor(v){super(),this._parentWindow=v,this._windowResizeListener=this.register(new d.MutableDisposable),this._onDprChange=this.register(new m.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,d.toDisposable)(()=>this.clearListener()))}setWindow(v){this._parentWindow=v,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,f.addDisposableDomListener)(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var v;this._outerListener&&((v=this._resolutionMediaMatchList)==null||v.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)}}},779:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.LinkProviderService=void 0;const d=u(844);class m extends d.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,d.toDisposable)(()=>this.linkProviders.length=0))}registerLinkProvider(g){return this.linkProviders.push(g),{dispose:()=>{const w=this.linkProviders.indexOf(g);w!==-1&&this.linkProviders.splice(w,1)}}}}o.LinkProviderService=m},8934:function(y,o,u){var d=this&&this.__decorate||function(S,v,p,c){var a,l=arguments.length,_=l<3?v:c===null?c=Object.getOwnPropertyDescriptor(v,p):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(S,v,p,c);else for(var j=S.length-1;j>=0;j--)(a=S[j])&&(_=(l<3?a(_):l>3?a(v,p,_):a(v,p))||_);return l>3&&_&&Object.defineProperty(v,p,_),_},m=this&&this.__param||function(S,v){return function(p,c){v(p,c,S)}};Object.defineProperty(o,"__esModule",{value:!0}),o.MouseService=void 0;const f=u(4725),g=u(9806);let w=o.MouseService=class{constructor(S,v){this._renderService=S,this._charSizeService=v}getCoords(S,v,p,c,a){return(0,g.getCoords)(window,S,v,p,c,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(S,v){const p=(0,g.getCoordsRelativeToElement)(window,S,v);if(this._charSizeService.hasValidSize)return p[0]=Math.min(Math.max(p[0],0),this._renderService.dimensions.css.canvas.width-1),p[1]=Math.min(Math.max(p[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(p[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(p[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(p[0]),y:Math.floor(p[1])}}};o.MouseService=w=d([m(0,f.IRenderService),m(1,f.ICharSizeService)],w)},3230:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.RenderService=void 0;const f=u(6193),g=u(4725),w=u(8460),S=u(844),v=u(7226),p=u(2585);let c=o.RenderService=class extends S.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(a,l,_,j,b,k,x,N){super(),this._rowCount=a,this._charSizeService=j,this._renderer=this.register(new S.MutableDisposable),this._pausedResizeTask=new v.DebouncedIdleTask,this._observerDisposable=this.register(new S.MutableDisposable),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 w.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new w.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new w.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new w.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new f.RenderDebouncer((E,L)=>this._renderRows(E,L),x),this.register(this._renderDebouncer),this.register(x.onDprChange(()=>this.handleDevicePixelRatioChange())),this.register(k.onResize(()=>this._fullRefresh())),this.register(k.buffers.onBufferActivate(()=>{var E;return(E=this._renderer.value)==null?void 0:E.clear()})),this.register(_.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(b.onDecorationRegistered(()=>this._fullRefresh())),this.register(b.onDecorationRemoved(()=>this._fullRefresh())),this.register(_.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(k.cols,k.rows),this._fullRefresh()})),this.register(_.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(k.buffer.y,k.buffer.y,!0))),this.register(N.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(x.window,l),this.register(x.onWindowChange(E=>this._registerIntersectionObserver(E,l)))}_registerIntersectionObserver(a,l){if("IntersectionObserver"in a){const _=new a.IntersectionObserver(j=>this._handleIntersectionChange(j[j.length-1]),{threshold:0});_.observe(l),this._observerDisposable.value=(0,S.toDisposable)(()=>_.disconnect())}}_handleIntersectionChange(a){this._isPaused=a.isIntersecting===void 0?a.intersectionRatio===0:!a.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(a,l,_=!1){this._isPaused?this._needsFullRefresh=!0:(_||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(a,l,this._rowCount))}_renderRows(a,l){this._renderer.value&&(a=Math.min(a,this._rowCount-1),l=Math.min(l,this._rowCount-1),this._renderer.value.renderRows(a,l),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:a,end:l}),this._onRender.fire({start:a,end:l}),this._isNextRenderRedrawOnly=!0)}resize(a,l){this._rowCount=l,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(a){this._renderer.value=a,this._renderer.value&&(this._renderer.value.onRequestRedraw(l=>this.refreshRows(l.start,l.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(a){return this._renderDebouncer.addRefreshCallback(a)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var a,l;this._renderer.value&&((l=(a=this._renderer.value).clearTextureAtlas)==null||l.call(a),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(a,l){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var _;return(_=this._renderer.value)==null?void 0:_.handleResize(a,l)}):this._renderer.value.handleResize(a,l),this._fullRefresh())}handleCharSizeChanged(){var a;(a=this._renderer.value)==null||a.handleCharSizeChanged()}handleBlur(){var a;(a=this._renderer.value)==null||a.handleBlur()}handleFocus(){var a;(a=this._renderer.value)==null||a.handleFocus()}handleSelectionChanged(a,l,_){var j;this._selectionState.start=a,this._selectionState.end=l,this._selectionState.columnSelectMode=_,(j=this._renderer.value)==null||j.handleSelectionChanged(a,l,_)}handleCursorMove(){var a;(a=this._renderer.value)==null||a.handleCursorMove()}clear(){var a;(a=this._renderer.value)==null||a.clear()}};o.RenderService=c=d([m(2,p.IOptionsService),m(3,g.ICharSizeService),m(4,p.IDecorationService),m(5,p.IBufferService),m(6,g.ICoreBrowserService),m(7,g.IThemeService)],c)},9312:function(y,o,u){var d=this&&this.__decorate||function(x,N,E,L){var T,O=arguments.length,B=O<3?N:L===null?L=Object.getOwnPropertyDescriptor(N,E):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")B=Reflect.decorate(x,N,E,L);else for(var F=x.length-1;F>=0;F--)(T=x[F])&&(B=(O<3?T(B):O>3?T(N,E,B):T(N,E))||B);return O>3&&B&&Object.defineProperty(N,E,B),B},m=this&&this.__param||function(x,N){return function(E,L){N(E,L,x)}};Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionService=void 0;const f=u(9806),g=u(9504),w=u(456),S=u(4725),v=u(8460),p=u(844),c=u(6114),a=u(4841),l=u(511),_=u(2585),j=" ",b=new RegExp(j,"g");let k=o.SelectionService=class extends p.Disposable{constructor(x,N,E,L,T,O,B,F,z){super(),this._element=x,this._screenElement=N,this._linkifier=E,this._bufferService=L,this._coreService=T,this._mouseService=O,this._optionsService=B,this._renderService=F,this._coreBrowserService=z,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new l.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new v.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new v.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new v.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new v.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=K=>this._handleMouseMove(K),this._mouseUpListener=K=>this._handleMouseUp(K),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(K=>this._handleTrim(K)),this.register(this._bufferService.buffers.onBufferActivate(K=>this._handleBufferActivate(K))),this.enable(),this._model=new w.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,p.toDisposable)(()=>{this._removeMouseDownListeners()}))}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(){const x=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!(!x||!N||x[0]===N[0]&&x[1]===N[1])}get selectionText(){const x=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;if(!x||!N)return"";const E=this._bufferService.buffer,L=[];if(this._activeSelectionMode===3){if(x[0]===N[0])return"";const T=x[0]T.replace(b," ")).join(c.isWindows?`\r +WARNING: This link could potentially be dangerous`)){const c=window.open();if(c){try{c.opener=null}catch{}c.location.href=p}else console.warn("Opening link blocked as opener could not be cleared")}}o.OscLinkProvider=w=d([m(0,g.IBufferService),m(1,g.IOptionsService),m(2,g.IOscLinkService)],w)},6193:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.RenderDebouncer=void 0,o.RenderDebouncer=class{constructor(u,d){this._renderCallback=u,this._coreBrowserService=d,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(u){return this._refreshCallbacks.push(u),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(u,d,m){this._rowCount=m,u=u!==void 0?u:0,d=d!==void 0?d:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,d):d,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)return void this._runRefreshCallbacks();const u=Math.max(this._rowStart,0),d=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,d),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const u of this._refreshCallbacks)u(0);this._refreshCallbacks=[]}}},3236:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Terminal=void 0;const d=u(3614),m=u(3656),f=u(3551),g=u(9042),w=u(3730),S=u(1680),v=u(3107),p=u(5744),c=u(2950),a=u(1296),l=u(428),_=u(4269),j=u(5114),b=u(8934),k=u(3230),x=u(9312),N=u(4725),E=u(6731),L=u(8055),T=u(8969),P=u(8460),B=u(844),U=u(6114),K=u(8437),q=u(2584),$=u(7399),R=u(5941),A=u(9074),M=u(2585),O=u(5435),W=u(4567),F=u(779);class z extends T.CoreTerminal{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}constructor(I={}){super(I),this.browser=U,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new B.MutableDisposable),this._onCursorMove=this.register(new P.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new P.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new P.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new P.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new P.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new P.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new P.EventEmitter),this._onBlur=this.register(new P.EventEmitter),this._onA11yCharEmitter=this.register(new P.EventEmitter),this._onA11yTabEmitter=this.register(new P.EventEmitter),this._onWillOpen=this.register(new P.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(M.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(F.LinkProviderService),this._instantiationService.setService(N.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(w.OscLinkProvider)),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((D,V)=>this.refresh(D,V))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(D=>this._reportWindowsOptions(D))),this.register(this._inputHandler.onColor(D=>this._handleColorEvent(D))),this.register((0,P.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,P.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,P.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,P.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(D=>this._afterResize(D.cols,D.rows))),this.register((0,B.toDisposable)(()=>{var D,V;this._customKeyEventHandler=void 0,(V=(D=this.element)==null?void 0:D.parentNode)==null||V.removeChild(this.element)}))}_handleColorEvent(I){if(this._themeService)for(const D of I){let V,H="";switch(D.index){case 256:V="foreground",H="10";break;case 257:V="background",H="11";break;case 258:V="cursor",H="12";break;default:V="ansi",H="4;"+D.index}switch(D.type){case 0:const J=L.color.toColorRGB(V==="ansi"?this._themeService.colors.ansi[D.index]:this._themeService.colors[V]);this.coreService.triggerDataEvent(`${q.C0.ESC}]${H};${(0,R.toRgbString)(J)}${q.C1_ESCAPED.ST}`);break;case 1:if(V==="ansi")this._themeService.modifyColors(Q=>Q.ansi[D.index]=L.channels.toColor(...D.color));else{const Q=V;this._themeService.modifyColors(re=>re[Q]=L.channels.toColor(...D.color))}break;case 2:this._themeService.restoreColor(D.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(I){I?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(W.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(I){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(q.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var I;return(I=this.textarea)==null?void 0:I.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(q.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const I=this.buffer.ybase+this.buffer.y,D=this.buffer.lines.get(I);if(!D)return;const V=Math.min(this.buffer.x,this.cols-1),H=this._renderService.dimensions.css.cell.height,J=D.getWidth(V),Q=this._renderService.dimensions.css.cell.width*J,re=this.buffer.y*this._renderService.dimensions.css.cell.height,ie=V*this._renderService.dimensions.css.cell.width;this.textarea.style.left=ie+"px",this.textarea.style.top=re+"px",this.textarea.style.width=Q+"px",this.textarea.style.height=H+"px",this.textarea.style.lineHeight=H+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,m.addDisposableDomListener)(this.element,"copy",D=>{this.hasSelection()&&(0,d.copyHandler)(D,this._selectionService)}));const I=D=>(0,d.handlePasteEvent)(D,this.textarea,this.coreService,this.optionsService);this.register((0,m.addDisposableDomListener)(this.textarea,"paste",I)),this.register((0,m.addDisposableDomListener)(this.element,"paste",I)),U.isFirefox?this.register((0,m.addDisposableDomListener)(this.element,"mousedown",D=>{D.button===2&&(0,d.rightClickHandler)(D,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,m.addDisposableDomListener)(this.element,"contextmenu",D=>{(0,d.rightClickHandler)(D,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),U.isLinux&&this.register((0,m.addDisposableDomListener)(this.element,"auxclick",D=>{D.button===1&&(0,d.moveTextAreaUnderMouseCursor)(D,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,m.addDisposableDomListener)(this.textarea,"keyup",I=>this._keyUp(I),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"keydown",I=>this._keyDown(I),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"keypress",I=>this._keyPress(I),!0)),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionupdate",I=>this._compositionHelper.compositionupdate(I))),this.register((0,m.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,m.addDisposableDomListener)(this.textarea,"input",I=>this._inputEvent(I),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(I){var V;if(!I)throw new Error("Terminal requires a parent element.");if(I.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((V=this.element)==null?void 0:V.ownerDocument.defaultView)&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=I.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"),I.appendChild(this.element);const D=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),D.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,m.addDisposableDomListener)(this.screenElement,"mousemove",H=>this.updateCursorStyle(H))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),D.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",g.promptLabel),U.isChromeOS||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._coreBrowserService=this.register(this._instantiationService.createInstance(j.CoreBrowserService,this.textarea,I.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(N.ICoreBrowserService,this._coreBrowserService),this.register((0,m.addDisposableDomListener)(this.textarea,"focus",H=>this._handleTextAreaFocus(H))),this.register((0,m.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(l.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(N.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(E.ThemeService),this._instantiationService.setService(N.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(_.CharacterJoinerService),this._instantiationService.setService(N.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(k.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(N.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(H=>this._onRender.fire(H))),this.onResize(H=>this._renderService.resize(H.cols,H.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(c.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(b.MouseService),this._instantiationService.setService(N.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(f.Linkifier,this.screenElement)),this.element.appendChild(D);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(S.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(H=>this.scrollLines(H.amount,H.suppressScrollEvent,1)),this.register(this._inputHandler.onRequestSyncScrollBar(()=>this.viewport.syncScrollArea())),this.register(this.viewport),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.register(this._renderService.onDimensionsChange(()=>this.viewport.syncScrollArea())),this._selectionService=this.register(this._instantiationService.createInstance(x.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(N.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(H=>this.scrollLines(H.amount,H.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(H=>this._renderService.handleSelectionChanged(H.start,H.end,H.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(H=>{this.textarea.value=H,this.textarea.focus(),this.textarea.select()})),this.register(this._onScroll.event(H=>{this.viewport.syncScrollArea(),this._selectionService.refresh()})),this.register((0,m.addDisposableDomListener)(this._viewportElement,"scroll",()=>this._selectionService.refresh())),this.register(this._instantiationService.createInstance(v.BufferDecorationRenderer,this.screenElement)),this.register((0,m.addDisposableDomListener)(this.element,"mousedown",H=>this._selectionService.handleMouseDown(H))),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(W.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",H=>this._handleScreenReaderModeOptionChange(H))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",H=>{!this._overviewRulerRenderer&&H&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(a.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const I=this,D=this.element;function V(Q){const re=I._mouseService.getMouseReportCoords(Q,I.screenElement);if(!re)return!1;let ie,he;switch(Q.overrideType||Q.type){case"mousemove":he=32,Q.buttons===void 0?(ie=3,Q.button!==void 0&&(ie=Q.button<3?Q.button:3)):ie=1&Q.buttons?0:4&Q.buttons?1:2&Q.buttons?2:3;break;case"mouseup":he=0,ie=Q.button<3?Q.button:3;break;case"mousedown":he=1,ie=Q.button<3?Q.button:3;break;case"wheel":if(I._customWheelEventHandler&&I._customWheelEventHandler(Q)===!1||I.viewport.getLinesScrolled(Q)===0)return!1;he=Q.deltaY<0?0:1,ie=4;break;default:return!1}return!(he===void 0||ie===void 0||ie>4)&&I.coreMouseService.triggerMouseEvent({col:re.col,row:re.row,x:re.x,y:re.y,button:ie,action:he,ctrl:Q.ctrlKey,alt:Q.altKey,shift:Q.shiftKey})}const H={mouseup:null,wheel:null,mousedrag:null,mousemove:null},J={mouseup:Q=>(V(Q),Q.buttons||(this._document.removeEventListener("mouseup",H.mouseup),H.mousedrag&&this._document.removeEventListener("mousemove",H.mousedrag)),this.cancel(Q)),wheel:Q=>(V(Q),this.cancel(Q,!0)),mousedrag:Q=>{Q.buttons&&V(Q)},mousemove:Q=>{Q.buttons||V(Q)}};this.register(this.coreMouseService.onProtocolChange(Q=>{Q?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(Q)),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()),8&Q?H.mousemove||(D.addEventListener("mousemove",J.mousemove),H.mousemove=J.mousemove):(D.removeEventListener("mousemove",H.mousemove),H.mousemove=null),16&Q?H.wheel||(D.addEventListener("wheel",J.wheel,{passive:!1}),H.wheel=J.wheel):(D.removeEventListener("wheel",H.wheel),H.wheel=null),2&Q?H.mouseup||(H.mouseup=J.mouseup):(this._document.removeEventListener("mouseup",H.mouseup),H.mouseup=null),4&Q?H.mousedrag||(H.mousedrag=J.mousedrag):(this._document.removeEventListener("mousemove",H.mousedrag),H.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,m.addDisposableDomListener)(D,"mousedown",Q=>{if(Q.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(Q))return V(Q),H.mouseup&&this._document.addEventListener("mouseup",H.mouseup),H.mousedrag&&this._document.addEventListener("mousemove",H.mousedrag),this.cancel(Q)})),this.register((0,m.addDisposableDomListener)(D,"wheel",Q=>{if(!H.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(Q)===!1)return!1;if(!this.buffer.hasScrollback){const re=this.viewport.getLinesScrolled(Q);if(re===0)return;const ie=q.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(Q.deltaY<0?"A":"B");let he="";for(let Ce=0;Ce{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(Q),this.cancel(Q)},{passive:!0})),this.register((0,m.addDisposableDomListener)(D,"touchmove",Q=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(Q)?void 0:this.cancel(Q)},{passive:!1}))}refresh(I,D){var V;(V=this._renderService)==null||V.refreshRows(I,D)}updateCursorStyle(I){var D;(D=this._selectionService)!=null&&D.shouldColumnSelect(I)?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(I,D,V=0){var H;V===1?(super.scrollLines(I,D,V),this.refresh(0,this.rows-1)):(H=this.viewport)==null||H.scrollLines(I)}paste(I){(0,d.paste)(I,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(I){this._customKeyEventHandler=I}attachCustomWheelEventHandler(I){this._customWheelEventHandler=I}registerLinkProvider(I){return this._linkProviderService.registerLinkProvider(I)}registerCharacterJoiner(I){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const D=this._characterJoinerService.register(I);return this.refresh(0,this.rows-1),D}deregisterCharacterJoiner(I){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(I)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(I){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+I)}registerDecoration(I){return this._decorationService.registerDecoration(I)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(I,D,V){this._selectionService.setSelection(I,D,V)}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(){var I;(I=this._selectionService)==null||I.clearSelection()}selectAll(){var I;(I=this._selectionService)==null||I.selectAll()}selectLines(I,D){var V;(V=this._selectionService)==null||V.selectLines(I,D)}_keyDown(I){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1)return!1;const D=this.browser.isMac&&this.options.macOptionIsMeta&&I.altKey;if(!D&&!this._compositionHelper.keydown(I))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;D||I.key!=="Dead"&&I.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const V=(0,$.evaluateKeyboardEvent)(I,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(I),V.type===3||V.type===2){const H=this.rows-1;return this.scrollLines(V.type===2?-H:H),this.cancel(I,!0)}return V.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,I)||(V.cancel&&this.cancel(I,!0),!V.key||!!(I.key&&!I.ctrlKey&&!I.altKey&&!I.metaKey&&I.key.length===1&&I.key.charCodeAt(0)>=65&&I.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(V.key!==q.C0.ETX&&V.key!==q.C0.CR||(this.textarea.value=""),this._onKey.fire({key:V.key,domEvent:I}),this._showCursor(),this.coreService.triggerDataEvent(V.key,!0),!this.optionsService.rawOptions.screenReaderMode||I.altKey||I.ctrlKey?this.cancel(I,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(I,D){const V=I.isMac&&!this.options.macOptionIsMeta&&D.altKey&&!D.ctrlKey&&!D.metaKey||I.isWindows&&D.altKey&&D.ctrlKey&&!D.metaKey||I.isWindows&&D.getModifierState("AltGraph");return D.type==="keypress"?V:V&&(!D.keyCode||D.keyCode>47)}_keyUp(I){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1||(function(D){return D.keyCode===16||D.keyCode===17||D.keyCode===18}(I)||this.focus(),this.updateCursorStyle(I),this._keyPressHandled=!1)}_keyPress(I){let D;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1)return!1;if(this.cancel(I),I.charCode)D=I.charCode;else if(I.which===null||I.which===void 0)D=I.keyCode;else{if(I.which===0||I.charCode===0)return!1;D=I.which}return!(!D||(I.altKey||I.ctrlKey||I.metaKey)&&!this._isThirdLevelShift(this.browser,I)||(D=String.fromCharCode(D),this._onKey.fire({key:D,domEvent:I}),this._showCursor(),this.coreService.triggerDataEvent(D,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(I){if(I.data&&I.inputType==="insertText"&&(!I.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const D=I.data;return this.coreService.triggerDataEvent(D,!0),this.cancel(I),!0}return!1}resize(I,D){I!==this.cols||D!==this.rows?super.resize(I,D):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(I,D){var V,H;(V=this._charSizeService)==null||V.measure(),(H=this.viewport)==null||H.syncScrollArea(!0)}clear(){var I;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 D=1;D{Object.defineProperty(o,"__esModule",{value:!0}),o.TimeBasedDebouncer=void 0,o.TimeBasedDebouncer=class{constructor(u,d=1e3){this._renderCallback=u,this._debounceThresholdMS=d,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(u,d,m){this._rowCount=m,u=u!==void 0?u:0,d=d!==void 0?d:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,d):d;const f=Date.now();if(f-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=f,this._innerRefresh();else if(!this._additionalRefreshRequested){const g=f-this._lastRefreshMs,w=this._debounceThresholdMS-g;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},w)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const u=Math.max(this._rowStart,0),d=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,d)}}},1680:function(y,o,u){var d=this&&this.__decorate||function(c,a,l,_){var j,b=arguments.length,k=b<3?a:_===null?_=Object.getOwnPropertyDescriptor(a,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(c,a,l,_);else for(var x=c.length-1;x>=0;x--)(j=c[x])&&(k=(b<3?j(k):b>3?j(a,l,k):j(a,l))||k);return b>3&&k&&Object.defineProperty(a,l,k),k},m=this&&this.__param||function(c,a){return function(l,_){a(l,_,c)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Viewport=void 0;const f=u(3656),g=u(4725),w=u(8460),S=u(844),v=u(2585);let p=o.Viewport=class extends S.Disposable{constructor(c,a,l,_,j,b,k,x){super(),this._viewportElement=c,this._scrollArea=a,this._bufferService=l,this._optionsService=_,this._charSizeService=j,this._renderService=b,this._coreBrowserService=k,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new w.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,f.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(N=>this._activeBuffer=N.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(N=>this._renderDimensions=N)),this._handleThemeChange(x.colors),this.register(x.onChangeColors(N=>this._handleThemeChange(N))),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.syncScrollArea())),setTimeout(()=>this.syncScrollArea())}_handleThemeChange(c){this._viewportElement.style.backgroundColor=c.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame(()=>this.syncScrollArea())}_refresh(c){if(c)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const a=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==a&&(this._lastRecordedBufferHeight=a,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const c=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==c&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=c),this._refreshAnimationFrame=null}syncScrollArea(c=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(c);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(c)}_handleScroll(c){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const a=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:a,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const c=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(c*(this._smoothScrollState.target-this._smoothScrollState.origin)),c<1?this._coreBrowserService.window.requestAnimationFrame(()=>this._smoothScroll()):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(c,a){const l=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(a<0&&this._viewportElement.scrollTop!==0||a>0&&l0&&(l=T),_=""}}return{bufferElements:j,cursorElement:l}}getLinesScrolled(c){if(c.deltaY===0||c.shiftKey)return 0;let a=this._applyScrollModifier(c.deltaY,c);return c.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=this._currentRowHeight+0,this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):c.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(c,a){const l=this._optionsService.rawOptions.fastScrollModifier;return l==="alt"&&a.altKey||l==="ctrl"&&a.ctrlKey||l==="shift"&&a.shiftKey?c*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:c*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(c){this._lastTouchY=c.touches[0].pageY}handleTouchMove(c){const a=this._lastTouchY-c.touches[0].pageY;return this._lastTouchY=c.touches[0].pageY,a!==0&&(this._viewportElement.scrollTop+=a,this._bubbleScroll(c,a))}};o.Viewport=p=d([m(2,v.IBufferService),m(3,v.IOptionsService),m(4,g.ICharSizeService),m(5,g.IRenderService),m(6,g.ICoreBrowserService),m(7,g.IThemeService)],p)},3107:function(y,o,u){var d=this&&this.__decorate||function(v,p,c,a){var l,_=arguments.length,j=_<3?p:a===null?a=Object.getOwnPropertyDescriptor(p,c):a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(v,p,c,a);else for(var b=v.length-1;b>=0;b--)(l=v[b])&&(j=(_<3?l(j):_>3?l(p,c,j):l(p,c))||j);return _>3&&j&&Object.defineProperty(p,c,j),j},m=this&&this.__param||function(v,p){return function(c,a){p(c,a,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferDecorationRenderer=void 0;const f=u(4725),g=u(844),w=u(2585);let S=o.BufferDecorationRenderer=class extends g.Disposable{constructor(v,p,c,a,l){super(),this._screenElement=v,this._bufferService=p,this._coreBrowserService=c,this._decorationService=a,this._renderService=l,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(_=>this._removeDecoration(_))),this.register((0,g.toDisposable)(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(const v of this._decorationService.decorations)this._renderDecoration(v);this._dimensionsChanged=!1}_renderDecoration(v){this._refreshStyle(v),this._dimensionsChanged&&this._refreshXPosition(v)}_createElement(v){var a;const p=this._coreBrowserService.mainDocument.createElement("div");p.classList.add("xterm-decoration"),p.classList.toggle("xterm-decoration-top-layer",((a=v==null?void 0:v.options)==null?void 0:a.layer)==="top"),p.style.width=`${Math.round((v.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,p.style.height=(v.options.height||1)*this._renderService.dimensions.css.cell.height+"px",p.style.top=(v.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",p.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const c=v.options.x??0;return c&&c>this._bufferService.cols&&(p.style.display="none"),this._refreshXPosition(v,p),p}_refreshStyle(v){const p=v.marker.line-this._bufferService.buffers.active.ydisp;if(p<0||p>=this._bufferService.rows)v.element&&(v.element.style.display="none",v.onRenderEmitter.fire(v.element));else{let c=this._decorationElements.get(v);c||(c=this._createElement(v),v.element=c,this._decorationElements.set(v,c),this._container.appendChild(c),v.onDispose(()=>{this._decorationElements.delete(v),c.remove()})),c.style.top=p*this._renderService.dimensions.css.cell.height+"px",c.style.display=this._altBufferIsActive?"none":"block",v.onRenderEmitter.fire(c)}}_refreshXPosition(v,p=v.element){if(!p)return;const c=v.options.x??0;(v.options.anchor||"left")==="right"?p.style.right=c?c*this._renderService.dimensions.css.cell.width+"px":"":p.style.left=c?c*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(v){var p;(p=this._decorationElements.get(v))==null||p.remove(),this._decorationElements.delete(v),v.dispose()}};o.BufferDecorationRenderer=S=d([m(1,w.IBufferService),m(2,f.ICoreBrowserService),m(3,w.IDecorationService),m(4,f.IRenderService)],S)},5871:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorZoneStore=void 0,o.ColorZoneStore=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(u){if(u.options.overviewRulerOptions){for(const d of this._zones)if(d.color===u.options.overviewRulerOptions.color&&d.position===u.options.overviewRulerOptions.position){if(this._lineIntersectsZone(d,u.marker.line))return;if(this._lineAdjacentToZone(d,u.marker.line,u.options.overviewRulerOptions.position))return void this._addLineToZone(d,u.marker.line)}if(this._zonePoolIndex=u.startBufferLine&&d<=u.endBufferLine}_lineAdjacentToZone(u,d,m){return d>=u.startBufferLine-this._linePadding[m||"full"]&&d<=u.endBufferLine+this._linePadding[m||"full"]}_addLineToZone(u,d){u.startBufferLine=Math.min(u.startBufferLine,d),u.endBufferLine=Math.max(u.endBufferLine,d)}}},5744:function(y,o,u){var d=this&&this.__decorate||function(l,_,j,b){var k,x=arguments.length,N=x<3?_:b===null?b=Object.getOwnPropertyDescriptor(_,j):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(l,_,j,b);else for(var E=l.length-1;E>=0;E--)(k=l[E])&&(N=(x<3?k(N):x>3?k(_,j,N):k(_,j))||N);return x>3&&N&&Object.defineProperty(_,j,N),N},m=this&&this.__param||function(l,_){return function(j,b){_(j,b,l)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OverviewRulerRenderer=void 0;const f=u(5871),g=u(4725),w=u(844),S=u(2585),v={full:0,left:0,center:0,right:0},p={full:0,left:0,center:0,right:0},c={full:0,left:0,center:0,right:0};let a=o.OverviewRulerRenderer=class extends w.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(l,_,j,b,k,x,N){var L;super(),this._viewportElement=l,this._screenElement=_,this._bufferService=j,this._decorationService=b,this._renderService=k,this._optionsService=x,this._coreBrowserService=N,this._colorZoneStore=new f.ColorZoneStore,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(),(L=this._viewportElement.parentElement)==null||L.insertBefore(this._canvas,this._viewportElement);const E=this._canvas.getContext("2d");if(!E)throw new Error("Ctx cannot be null");this._ctx=E,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,w.toDisposable)(()=>{var T;(T=this._canvas)==null||T.remove()}))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this.register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0)))}_registerBufferChangeListeners(){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())}))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender(()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",()=>this._queueRefresh(!0))),this.register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const l=Math.floor(this._canvas.width/3),_=Math.ceil(this._canvas.width/3);p.full=this._canvas.width,p.left=l,p.center=_,p.right=l,this._refreshDrawHeightConstants(),c.full=0,c.left=0,c.center=p.left,c.right=p.left+p.center}_refreshDrawHeightConstants(){v.full=Math.round(2*this._coreBrowserService.dpr);const l=this._canvas.height/this._bufferService.buffer.lines.length,_=Math.round(Math.max(Math.min(l,12),6)*this._coreBrowserService.dpr);v.left=_,v.center=_,v.right=_}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*v.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(const _ of this._decorationService.decorations)this._colorZoneStore.addDecoration(_);this._ctx.lineWidth=1;const l=this._colorZoneStore.zones;for(const _ of l)_.position!=="full"&&this._renderColorZone(_);for(const _ of l)_.position==="full"&&this._renderColorZone(_);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(l){this._ctx.fillStyle=l.color,this._ctx.fillRect(c[l.position||"full"],Math.round((this._canvas.height-1)*(l.startBufferLine/this._bufferService.buffers.active.lines.length)-v[l.position||"full"]/2),p[l.position||"full"],Math.round((this._canvas.height-1)*((l.endBufferLine-l.startBufferLine)/this._bufferService.buffers.active.lines.length)+v[l.position||"full"]))}_queueRefresh(l,_){this._shouldUpdateDimensions=l||this._shouldUpdateDimensions,this._shouldUpdateAnchor=_||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};o.OverviewRulerRenderer=a=d([m(2,S.IBufferService),m(3,S.IDecorationService),m(4,g.IRenderService),m(5,S.IOptionsService),m(6,g.ICoreBrowserService)],a)},2950:function(y,o,u){var d=this&&this.__decorate||function(v,p,c,a){var l,_=arguments.length,j=_<3?p:a===null?a=Object.getOwnPropertyDescriptor(p,c):a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(v,p,c,a);else for(var b=v.length-1;b>=0;b--)(l=v[b])&&(j=(_<3?l(j):_>3?l(p,c,j):l(p,c))||j);return _>3&&j&&Object.defineProperty(p,c,j),j},m=this&&this.__param||function(v,p){return function(c,a){p(c,a,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CompositionHelper=void 0;const f=u(4725),g=u(2585),w=u(2584);let S=o.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(v,p,c,a,l,_){this._textarea=v,this._compositionView=p,this._bufferService=c,this._optionsService=a,this._coreService=l,this._renderService=_,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(v){this._compositionView.textContent=v.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(v){if(this._isComposing||this._isSendingComposition){if(v.keyCode===229||v.keyCode===16||v.keyCode===17||v.keyCode===18)return!1;this._finalizeComposition(!1)}return v.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(v){if(this._compositionView.classList.remove("active"),this._isComposing=!1,v){const p={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let c;this._isSendingComposition=!1,p.start+=this._dataAlreadySent.length,c=this._isComposing?this._textarea.value.substring(p.start,p.end):this._textarea.value.substring(p.start),c.length>0&&this._coreService.triggerDataEvent(c,!0)}},0)}else{this._isSendingComposition=!1;const p=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(p,!0)}}_handleAnyTextareaChanges(){const v=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const p=this._textarea.value,c=p.replace(v,"");this._dataAlreadySent=c,p.length>v.length?this._coreService.triggerDataEvent(c,!0):p.lengththis.updateCompositionElements(!0),0)}}};o.CompositionHelper=S=d([m(2,g.IBufferService),m(3,g.IOptionsService),m(4,g.ICoreService),m(5,f.IRenderService)],S)},9806:(y,o)=>{function u(d,m,f){const g=f.getBoundingClientRect(),w=d.getComputedStyle(f),S=parseInt(w.getPropertyValue("padding-left")),v=parseInt(w.getPropertyValue("padding-top"));return[m.clientX-g.left-S,m.clientY-g.top-v]}Object.defineProperty(o,"__esModule",{value:!0}),o.getCoords=o.getCoordsRelativeToElement=void 0,o.getCoordsRelativeToElement=u,o.getCoords=function(d,m,f,g,w,S,v,p,c){if(!S)return;const a=u(d,m,f);return a?(a[0]=Math.ceil((a[0]+(c?v/2:0))/v),a[1]=Math.ceil(a[1]/p),a[0]=Math.min(Math.max(a[0],1),g+(c?1:0)),a[1]=Math.min(Math.max(a[1],1),w),a):void 0}},9504:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.moveToCellSequence=void 0;const d=u(2584);function m(p,c,a,l){const _=p-f(p,a),j=c-f(c,a),b=Math.abs(_-j)-function(k,x,N){let E=0;const L=k-f(k,N),T=x-f(x,N);for(let P=0;P=0&&pc?"A":"B"}function w(p,c,a,l,_,j){let b=p,k=c,x="";for(;b!==a||k!==l;)b+=_?1:-1,_&&b>j.cols-1?(x+=j.buffer.translateBufferLineToString(k,!1,p,b),b=0,p=0,k++):!_&&b<0&&(x+=j.buffer.translateBufferLineToString(k,!1,0,p+1),b=j.cols-1,p=b,k--);return x+j.buffer.translateBufferLineToString(k,!1,p,b)}function S(p,c){const a=c?"O":"[";return d.C0.ESC+a+p}function v(p,c){p=Math.floor(p);let a="";for(let l=0;l0?L-f(L,T):N;const U=L,K=function(q,$,R,A,M,O){let W;return W=m(R,A,M,O).length>0?A-f(A,M):$,q=R&&Wp?"D":"C",v(Math.abs(_-p),S(b,l));b=j>c?"D":"C";const k=Math.abs(j-c);return v(function(x,N){return N.cols-x}(j>c?p:_,a)+(k-1)*a.cols+1+((j>c?_:p)-1),S(b,l))}},1296:function(y,o,u){var d=this&&this.__decorate||function(P,B,U,K){var q,$=arguments.length,R=$<3?B:K===null?K=Object.getOwnPropertyDescriptor(B,U):K;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(P,B,U,K);else for(var A=P.length-1;A>=0;A--)(q=P[A])&&(R=($<3?q(R):$>3?q(B,U,R):q(B,U))||R);return $>3&&R&&Object.defineProperty(B,U,R),R},m=this&&this.__param||function(P,B){return function(U,K){B(U,K,P)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRenderer=void 0;const f=u(3787),g=u(2550),w=u(2223),S=u(6171),v=u(6052),p=u(4725),c=u(8055),a=u(8460),l=u(844),_=u(2585),j="xterm-dom-renderer-owner-",b="xterm-rows",k="xterm-fg-",x="xterm-bg-",N="xterm-focus",E="xterm-selection";let L=1,T=o.DomRenderer=class extends l.Disposable{constructor(P,B,U,K,q,$,R,A,M,O,W,F,z){super(),this._terminal=P,this._document=B,this._element=U,this._screenElement=K,this._viewportElement=q,this._helperContainer=$,this._linkifier2=R,this._charSizeService=M,this._optionsService=O,this._bufferService=W,this._coreBrowserService=F,this._themeService=z,this._terminalClass=L++,this._rowElements=[],this._selectionRenderModel=(0,v.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new a.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(b),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(E),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,S.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(X=>this._injectCss(X))),this._injectCss(this._themeService.colors),this._rowFactory=A.createInstance(f.DomRendererRowFactory,document),this._element.classList.add(j+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(X=>this._handleLinkHover(X))),this.register(this._linkifier2.onHideLinkUnderline(X=>this._handleLinkLeave(X))),this.register((0,l.toDisposable)(()=>{this._element.classList.remove(j+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new g.WidthCache(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(){const P=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*P,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*P),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/P),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/P),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(const U of this._rowElements)U.style.width=`${this.dimensions.css.canvas.width}px`,U.style.height=`${this.dimensions.css.cell.height}px`,U.style.lineHeight=`${this.dimensions.css.cell.height}px`,U.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const B=`${this._terminalSelector} .${b} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=B,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(P){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let B=`${this._terminalSelector} .${b} { color: ${P.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;B+=`${this._terminalSelector} .${b} .xterm-dim { color: ${c.color.multiplyOpacity(P.foreground,.5).css};}`,B+=`${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;}`;const U=`blink_underline_${this._terminalClass}`,K=`blink_bar_${this._terminalClass}`,q=`blink_block_${this._terminalClass}`;B+=`@keyframes ${U} { 50% { border-bottom-style: hidden; }}`,B+=`@keyframes ${K} { 50% { box-shadow: none; }}`,B+=`@keyframes ${q} { 0% { background-color: ${P.cursor.css}; color: ${P.cursorAccent.css}; } 50% { background-color: inherit; color: ${P.cursor.css}; }}`,B+=`${this._terminalSelector} .${b}.${N} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${U} 1s step-end infinite;}${this._terminalSelector} .${b}.${N} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${K} 1s step-end infinite;}${this._terminalSelector} .${b}.${N} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${q} 1s step-end infinite;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-block { background-color: ${P.cursor.css}; color: ${P.cursorAccent.css};}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${P.cursor.css} !important; color: ${P.cursorAccent.css} !important;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${P.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${P.cursor.css} inset;}${this._terminalSelector} .${b} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${P.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,B+=`${this._terminalSelector} .${E} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${E} div { position: absolute; background-color: ${P.selectionBackgroundOpaque.css};}${this._terminalSelector} .${E} div { position: absolute; background-color: ${P.selectionInactiveBackgroundOpaque.css};}`;for(const[$,R]of P.ansi.entries())B+=`${this._terminalSelector} .${k}${$} { color: ${R.css}; }${this._terminalSelector} .${k}${$}.xterm-dim { color: ${c.color.multiplyOpacity(R,.5).css}; }${this._terminalSelector} .${x}${$} { background-color: ${R.css}; }`;B+=`${this._terminalSelector} .${k}${w.INVERTED_DEFAULT_COLOR} { color: ${c.color.opaque(P.background).css}; }${this._terminalSelector} .${k}${w.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${c.color.multiplyOpacity(c.color.opaque(P.background),.5).css}; }${this._terminalSelector} .${x}${w.INVERTED_DEFAULT_COLOR} { background-color: ${P.foreground.css}; }`,this._themeStyleElement.textContent=B}_setDefaultSpacing(){const P=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${P}px`,this._rowFactory.defaultSpacing=P}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(P,B){for(let U=this._rowElements.length;U<=B;U++){const K=this._document.createElement("div");this._rowContainer.appendChild(K),this._rowElements.push(K)}for(;this._rowElements.length>B;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(P,B){this._refreshRowElements(P,B),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(N),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(N),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(P,B,U){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(P,B,U),this.renderRows(0,this._bufferService.rows-1),!P||!B)return;this._selectionRenderModel.update(this._terminal,P,B,U);const K=this._selectionRenderModel.viewportStartRow,q=this._selectionRenderModel.viewportEndRow,$=this._selectionRenderModel.viewportCappedStartRow,R=this._selectionRenderModel.viewportCappedEndRow;if($>=this._bufferService.rows||R<0)return;const A=this._document.createDocumentFragment();if(U){const M=P[0]>B[0];A.appendChild(this._createSelectionElement($,M?B[0]:P[0],M?P[0]:B[0],R-$+1))}else{const M=K===$?P[0]:0,O=$===q?B[0]:this._bufferService.cols;A.appendChild(this._createSelectionElement($,M,O));const W=R-$-1;if(A.appendChild(this._createSelectionElement($+1,0,this._bufferService.cols,W)),$!==R){const F=q===R?B[0]:this._bufferService.cols;A.appendChild(this._createSelectionElement(R,0,F))}}this._selectionContainer.appendChild(A)}_createSelectionElement(P,B,U,K=1){const q=this._document.createElement("div"),$=B*this.dimensions.css.cell.width;let R=this.dimensions.css.cell.width*(U-B);return $+R>this.dimensions.css.canvas.width&&(R=this.dimensions.css.canvas.width-$),q.style.height=K*this.dimensions.css.cell.height+"px",q.style.top=P*this.dimensions.css.cell.height+"px",q.style.left=`${$}px`,q.style.width=`${R}px`,q}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(const P of this._rowElements)P.replaceChildren()}renderRows(P,B){const U=this._bufferService.buffer,K=U.ybase+U.y,q=Math.min(U.x,this._bufferService.cols-1),$=this._optionsService.rawOptions.cursorBlink,R=this._optionsService.rawOptions.cursorStyle,A=this._optionsService.rawOptions.cursorInactiveStyle;for(let M=P;M<=B;M++){const O=M+U.ydisp,W=this._rowElements[M],F=U.lines.get(O);if(!W||!F)break;W.replaceChildren(...this._rowFactory.createRow(F,O,O===K,R,A,q,$,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${j}${this._terminalClass}`}_handleLinkHover(P){this._setCellUnderline(P.x1,P.x2,P.y1,P.y2,P.cols,!0)}_handleLinkLeave(P){this._setCellUnderline(P.x1,P.x2,P.y1,P.y2,P.cols,!1)}_setCellUnderline(P,B,U,K,q,$){U<0&&(P=0),K<0&&(B=0);const R=this._bufferService.rows-1;U=Math.max(Math.min(U,R),0),K=Math.max(Math.min(K,R),0),q=Math.min(q,this._bufferService.cols);const A=this._bufferService.buffer,M=A.ybase+A.y,O=Math.min(A.x,q-1),W=this._optionsService.rawOptions.cursorBlink,F=this._optionsService.rawOptions.cursorStyle,z=this._optionsService.rawOptions.cursorInactiveStyle;for(let X=U;X<=K;++X){const I=X+A.ydisp,D=this._rowElements[X],V=A.lines.get(I);if(!D||!V)break;D.replaceChildren(...this._rowFactory.createRow(V,I,I===M,F,z,O,W,this.dimensions.css.cell.width,this._widthCache,$?X===U?P:0:-1,$?(X===K?B:q)-1:-1))}}};o.DomRenderer=T=d([m(7,_.IInstantiationService),m(8,p.ICharSizeService),m(9,_.IOptionsService),m(10,_.IBufferService),m(11,p.ICoreBrowserService),m(12,p.IThemeService)],T)},3787:function(y,o,u){var d=this&&this.__decorate||function(b,k,x,N){var E,L=arguments.length,T=L<3?k:N===null?N=Object.getOwnPropertyDescriptor(k,x):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(b,k,x,N);else for(var P=b.length-1;P>=0;P--)(E=b[P])&&(T=(L<3?E(T):L>3?E(k,x,T):E(k,x))||T);return L>3&&T&&Object.defineProperty(k,x,T),T},m=this&&this.__param||function(b,k){return function(x,N){k(x,N,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRendererRowFactory=void 0;const f=u(2223),g=u(643),w=u(511),S=u(2585),v=u(8055),p=u(4725),c=u(4269),a=u(6171),l=u(3734);let _=o.DomRendererRowFactory=class{constructor(b,k,x,N,E,L,T){this._document=b,this._characterJoinerService=k,this._optionsService=x,this._coreBrowserService=N,this._coreService=E,this._decorationService=L,this._themeService=T,this._workCell=new w.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(b,k,x){this._selectionStart=b,this._selectionEnd=k,this._columnSelectMode=x}createRow(b,k,x,N,E,L,T,P,B,U,K){const q=[],$=this._characterJoinerService.getJoinedCharacters(k),R=this._themeService.colors;let A,M=b.getNoBgTrimmedLength();x&&M0&&re===$[0][0]){he=!0;const pe=$.shift();ae=new c.JoinedCellData(this._workCell,b.translateToString(!0,pe[0],pe[1]),pe[1]-pe[0]),Ce=pe[1]-1,ie=ae.getWidth()}const dt=this._isCellInSelection(re,k),wt=x&&re===L,nt=Q&&re>=U&&re<=K;let ft=!1;this._decorationService.forEachDecorationAtCell(re,k,void 0,pe=>{ft=!0});let Ie=ae.getChars()||g.WHITESPACE_CELL_CHAR;if(Ie===" "&&(ae.isUnderline()||ae.isOverline())&&(Ie=" "),H=ie*P-B.get(Ie,ae.isBold(),ae.isItalic()),A){if(O&&(dt&&V||!dt&&!V&&ae.bg===F)&&(dt&&V&&R.selectionForeground||ae.fg===z)&&ae.extended.ext===X&&nt===I&&H===D&&!wt&&!he&&!ft){ae.isInvisible()?W+=g.WHITESPACE_CELL_CHAR:W+=Ie,O++;continue}O&&(A.textContent=W),A=this._document.createElement("span"),O=0,W=""}else A=this._document.createElement("span");if(F=ae.bg,z=ae.fg,X=ae.extended.ext,I=nt,D=H,V=dt,he&&L>=re&&L<=Ce&&(L=re),!this._coreService.isCursorHidden&&wt&&this._coreService.isCursorInitialized){if(J.push("xterm-cursor"),this._coreBrowserService.isFocused)T&&J.push("xterm-cursor-blink"),J.push(N==="bar"?"xterm-cursor-bar":N==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(E)switch(E){case"outline":J.push("xterm-cursor-outline");break;case"block":J.push("xterm-cursor-block");break;case"bar":J.push("xterm-cursor-bar");break;case"underline":J.push("xterm-cursor-underline")}}if(ae.isBold()&&J.push("xterm-bold"),ae.isItalic()&&J.push("xterm-italic"),ae.isDim()&&J.push("xterm-dim"),W=ae.isInvisible()?g.WHITESPACE_CELL_CHAR:ae.getChars()||g.WHITESPACE_CELL_CHAR,ae.isUnderline()&&(J.push(`xterm-underline-${ae.extended.underlineStyle}`),W===" "&&(W=" "),!ae.isUnderlineColorDefault()))if(ae.isUnderlineColorRGB())A.style.textDecorationColor=`rgb(${l.AttributeData.toColorRGB(ae.getUnderlineColor()).join(",")})`;else{let pe=ae.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&ae.isBold()&&pe<8&&(pe+=8),A.style.textDecorationColor=R.ansi[pe].css}ae.isOverline()&&(J.push("xterm-overline"),W===" "&&(W=" ")),ae.isStrikethrough()&&J.push("xterm-strikethrough"),nt&&(A.style.textDecoration="underline");let Le=ae.getFgColor(),Y=ae.getFgColorMode(),te=ae.getBgColor(),Se=ae.getBgColorMode();const Ut=!!ae.isInverse();if(Ut){const pe=Le;Le=te,te=pe;const Ls=Y;Y=Se,Se=Ls}let Te,Rs,bt,Lt=!1;switch(this._decorationService.forEachDecorationAtCell(re,k,void 0,pe=>{pe.options.layer!=="top"&&Lt||(pe.backgroundColorRGB&&(Se=50331648,te=pe.backgroundColorRGB.rgba>>8&16777215,Te=pe.backgroundColorRGB),pe.foregroundColorRGB&&(Y=50331648,Le=pe.foregroundColorRGB.rgba>>8&16777215,Rs=pe.foregroundColorRGB),Lt=pe.options.layer==="top")}),!Lt&&dt&&(Te=this._coreBrowserService.isFocused?R.selectionBackgroundOpaque:R.selectionInactiveBackgroundOpaque,te=Te.rgba>>8&16777215,Se=50331648,Lt=!0,R.selectionForeground&&(Y=50331648,Le=R.selectionForeground.rgba>>8&16777215,Rs=R.selectionForeground)),Lt&&J.push("xterm-decoration-top"),Se){case 16777216:case 33554432:bt=R.ansi[te],J.push(`xterm-bg-${te}`);break;case 50331648:bt=v.channels.toColor(te>>16,te>>8&255,255&te),this._addStyle(A,`background-color:#${j((te>>>0).toString(16),"0",6)}`);break;default:Ut?(bt=R.foreground,J.push(`xterm-bg-${f.INVERTED_DEFAULT_COLOR}`)):bt=R.background}switch(Te||ae.isDim()&&(Te=v.color.multiplyOpacity(bt,.5)),Y){case 16777216:case 33554432:ae.isBold()&&Le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Le+=8),this._applyMinimumContrast(A,bt,R.ansi[Le],ae,Te,void 0)||J.push(`xterm-fg-${Le}`);break;case 50331648:const pe=v.channels.toColor(Le>>16&255,Le>>8&255,255&Le);this._applyMinimumContrast(A,bt,pe,ae,Te,Rs)||this._addStyle(A,`color:#${j(Le.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(A,bt,R.foreground,ae,Te,Rs)||Ut&&J.push(`xterm-fg-${f.INVERTED_DEFAULT_COLOR}`)}J.length&&(A.className=J.join(" "),J.length=0),wt||he||ft?A.textContent=W:O++,H!==this.defaultSpacing&&(A.style.letterSpacing=`${H}px`),q.push(A),re=Ce}return A&&O&&(A.textContent=W),q}_applyMinimumContrast(b,k,x,N,E,L){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,a.treatGlyphAsBackgroundColor)(N.getCode()))return!1;const T=this._getContrastCache(N);let P;if(E||L||(P=T.getColor(k.rgba,x.rgba)),P===void 0){const B=this._optionsService.rawOptions.minimumContrastRatio/(N.isDim()?2:1);P=v.color.ensureContrastRatio(E||k,L||x,B),T.setColor((E||k).rgba,(L||x).rgba,P??null)}return!!P&&(this._addStyle(b,`color:${P.css}`),!0)}_getContrastCache(b){return b.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(b,k){b.setAttribute("style",`${b.getAttribute("style")||""}${k};`)}_isCellInSelection(b,k){const x=this._selectionStart,N=this._selectionEnd;return!(!x||!N)&&(this._columnSelectMode?x[0]<=N[0]?b>=x[0]&&k>=x[1]&&b=x[1]&&b>=N[0]&&k<=N[1]:k>x[1]&&k=x[0]&&b=x[0])}};function j(b,k,x){for(;b.length{Object.defineProperty(o,"__esModule",{value:!0}),o.WidthCache=void 0,o.WidthCache=class{constructor(u,d){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=u.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const m=u.createElement("span");m.classList.add("xterm-char-measure-element");const f=u.createElement("span");f.classList.add("xterm-char-measure-element"),f.style.fontWeight="bold";const g=u.createElement("span");g.classList.add("xterm-char-measure-element"),g.style.fontStyle="italic";const w=u.createElement("span");w.classList.add("xterm-char-measure-element"),w.style.fontWeight="bold",w.style.fontStyle="italic",this._measureElements=[m,f,g,w],this._container.appendChild(m),this._container.appendChild(f),this._container.appendChild(g),this._container.appendChild(w),d.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(u,d,m,f){u===this._font&&d===this._fontSize&&m===this._weight&&f===this._weightBold||(this._font=u,this._fontSize=d,this._weight=m,this._weightBold=f,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${m}`,this._measureElements[1].style.fontWeight=`${f}`,this._measureElements[2].style.fontWeight=`${m}`,this._measureElements[3].style.fontWeight=`${f}`,this.clear())}get(u,d,m){let f=0;if(!d&&!m&&u.length===1&&(f=u.charCodeAt(0))<256){if(this._flat[f]!==-9999)return this._flat[f];const S=this._measure(u,0);return S>0&&(this._flat[f]=S),S}let g=u;d&&(g+="B"),m&&(g+="I");let w=this._holey.get(g);if(w===void 0){let S=0;d&&(S|=1),m&&(S|=2),w=this._measure(u,S),w>0&&this._holey.set(g,w)}return w}_measure(u,d){const m=this._measureElements[d];return m.textContent=u.repeat(32),m.offsetWidth/32}}},2223:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TEXT_BASELINE=o.DIM_OPACITY=o.INVERTED_DEFAULT_COLOR=void 0;const d=u(6114);o.INVERTED_DEFAULT_COLOR=257,o.DIM_OPACITY=.5,o.TEXT_BASELINE=d.isFirefox||d.isLegacyEdge?"bottom":"ideographic"},6171:(y,o)=>{function u(m){return 57508<=m&&m<=57558}function d(m){return m>=128512&&m<=128591||m>=127744&&m<=128511||m>=128640&&m<=128767||m>=9728&&m<=9983||m>=9984&&m<=10175||m>=65024&&m<=65039||m>=129280&&m<=129535||m>=127462&&m<=127487}Object.defineProperty(o,"__esModule",{value:!0}),o.computeNextVariantOffset=o.createRenderDimensions=o.treatGlyphAsBackgroundColor=o.allowRescaling=o.isEmoji=o.isRestrictedPowerlineGlyph=o.isPowerlineGlyph=o.throwIfFalsy=void 0,o.throwIfFalsy=function(m){if(!m)throw new Error("value must not be falsy");return m},o.isPowerlineGlyph=u,o.isRestrictedPowerlineGlyph=function(m){return 57520<=m&&m<=57527},o.isEmoji=d,o.allowRescaling=function(m,f,g,w){return f===1&&g>Math.ceil(1.5*w)&&m!==void 0&&m>255&&!d(m)&&!u(m)&&!function(S){return 57344<=S&&S<=63743}(m)},o.treatGlyphAsBackgroundColor=function(m){return u(m)||function(f){return 9472<=f&&f<=9631}(m)},o.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},o.computeNextVariantOffset=function(m,f,g=0){return(m-(2*Math.round(f)-g))%(2*Math.round(f))}},6052:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createSelectionRenderModel=void 0;class u{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(m,f,g,w=!1){if(this.selectionStart=f,this.selectionEnd=g,!f||!g||f[0]===g[0]&&f[1]===g[1])return void this.clear();const S=m.buffers.active.ydisp,v=f[1]-S,p=g[1]-S,c=Math.max(v,0),a=Math.min(p,m.rows-1);c>=m.rows||a<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=w,this.viewportStartRow=v,this.viewportEndRow=p,this.viewportCappedStartRow=c,this.viewportCappedEndRow=a,this.startCol=f[0],this.endCol=g[0])}isCellSelected(m,f,g){return!!this.hasSelection&&(g-=m.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?f>=this.startCol&&g>=this.viewportCappedStartRow&&f=this.viewportCappedStartRow&&f>=this.endCol&&g<=this.viewportCappedEndRow:g>this.viewportStartRow&&g=this.startCol&&f=this.startCol)}}o.createSelectionRenderModel=function(){return new u}},456:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionModel=void 0,o.SelectionModel=class{constructor(u){this._bufferService=u,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?u%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)-1]:[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[u,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[Math.max(u,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const u=this.selectionStart,d=this.selectionEnd;return!(!u||!d)&&(u[1]>d[1]||u[1]===d[1]&&u[0]>d[0])}handleTrim(u){return this.selectionStart&&(this.selectionStart[1]-=u),this.selectionEnd&&(this.selectionEnd[1]-=u),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharSizeService=void 0;const f=u(2585),g=u(8460),w=u(844);let S=o.CharSizeService=class extends w.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(a,l,_){super(),this._optionsService=_,this.width=0,this.height=0,this._onCharSizeChange=this.register(new g.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new c(this._optionsService))}catch{this._measureStrategy=this.register(new p(a,l,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const a=this._measureStrategy.measure();a.width===this.width&&a.height===this.height||(this.width=a.width,this.height=a.height,this._onCharSizeChange.fire())}};o.CharSizeService=S=d([m(2,f.IOptionsService)],S);class v extends w.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(l,_){l!==void 0&&l>0&&_!==void 0&&_>0&&(this._result.width=l,this._result.height=_)}}class p extends v{constructor(l,_,j){super(),this._document=l,this._parentElement=_,this._optionsService=j,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}}class c extends v{constructor(l){super(),this._optionsService=l,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const _=this._ctx.measureText("W");if(!("width"in _&&"fontBoundingBoxAscent"in _&&"fontBoundingBoxDescent"in _))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const l=this._ctx.measureText("W");return this._validateAndSet(l.width,l.fontBoundingBoxAscent+l.fontBoundingBoxDescent),this._result}}},4269:function(y,o,u){var d=this&&this.__decorate||function(c,a,l,_){var j,b=arguments.length,k=b<3?a:_===null?_=Object.getOwnPropertyDescriptor(a,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(c,a,l,_);else for(var x=c.length-1;x>=0;x--)(j=c[x])&&(k=(b<3?j(k):b>3?j(a,l,k):j(a,l))||k);return b>3&&k&&Object.defineProperty(a,l,k),k},m=this&&this.__param||function(c,a){return function(l,_){a(l,_,c)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharacterJoinerService=o.JoinedCellData=void 0;const f=u(3734),g=u(643),w=u(511),S=u(2585);class v extends f.AttributeData{constructor(a,l,_){super(),this.content=0,this.combinedData="",this.fg=a.fg,this.bg=a.bg,this.combinedData=l,this._width=_}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(a){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.JoinedCellData=v;let p=o.CharacterJoinerService=class kd{constructor(a){this._bufferService=a,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new w.CellData}register(a){const l={id:this._nextCharacterJoinerId++,handler:a};return this._characterJoiners.push(l),l.id}deregister(a){for(let l=0;l1){const T=this._getJoinedRanges(j,x,k,l,b);for(let P=0;P1){const L=this._getJoinedRanges(j,x,k,l,b);for(let T=0;T{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreBrowserService=void 0;const d=u(844),m=u(8460),f=u(3656);class g extends d.Disposable{constructor(v,p,c){super(),this._textarea=v,this._window=p,this.mainDocument=c,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new w(this._window),this._onDprChange=this.register(new m.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new m.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange(a=>this._screenDprMonitor.setWindow(a))),this.register((0,m.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",()=>this._isFocused=!0),this._textarea.addEventListener("blur",()=>this._isFocused=!1)}get window(){return this._window}set window(v){this._window!==v&&(this._window=v,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}}o.CoreBrowserService=g;class w extends d.Disposable{constructor(v){super(),this._parentWindow=v,this._windowResizeListener=this.register(new d.MutableDisposable),this._onDprChange=this.register(new m.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,d.toDisposable)(()=>this.clearListener()))}setWindow(v){this._parentWindow=v,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,f.addDisposableDomListener)(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var v;this._outerListener&&((v=this._resolutionMediaMatchList)==null||v.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)}}},779:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.LinkProviderService=void 0;const d=u(844);class m extends d.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,d.toDisposable)(()=>this.linkProviders.length=0))}registerLinkProvider(g){return this.linkProviders.push(g),{dispose:()=>{const w=this.linkProviders.indexOf(g);w!==-1&&this.linkProviders.splice(w,1)}}}}o.LinkProviderService=m},8934:function(y,o,u){var d=this&&this.__decorate||function(S,v,p,c){var a,l=arguments.length,_=l<3?v:c===null?c=Object.getOwnPropertyDescriptor(v,p):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(S,v,p,c);else for(var j=S.length-1;j>=0;j--)(a=S[j])&&(_=(l<3?a(_):l>3?a(v,p,_):a(v,p))||_);return l>3&&_&&Object.defineProperty(v,p,_),_},m=this&&this.__param||function(S,v){return function(p,c){v(p,c,S)}};Object.defineProperty(o,"__esModule",{value:!0}),o.MouseService=void 0;const f=u(4725),g=u(9806);let w=o.MouseService=class{constructor(S,v){this._renderService=S,this._charSizeService=v}getCoords(S,v,p,c,a){return(0,g.getCoords)(window,S,v,p,c,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(S,v){const p=(0,g.getCoordsRelativeToElement)(window,S,v);if(this._charSizeService.hasValidSize)return p[0]=Math.min(Math.max(p[0],0),this._renderService.dimensions.css.canvas.width-1),p[1]=Math.min(Math.max(p[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(p[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(p[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(p[0]),y:Math.floor(p[1])}}};o.MouseService=w=d([m(0,f.IRenderService),m(1,f.ICharSizeService)],w)},3230:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.RenderService=void 0;const f=u(6193),g=u(4725),w=u(8460),S=u(844),v=u(7226),p=u(2585);let c=o.RenderService=class extends S.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(a,l,_,j,b,k,x,N){super(),this._rowCount=a,this._charSizeService=j,this._renderer=this.register(new S.MutableDisposable),this._pausedResizeTask=new v.DebouncedIdleTask,this._observerDisposable=this.register(new S.MutableDisposable),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 w.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new w.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new w.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new w.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new f.RenderDebouncer((E,L)=>this._renderRows(E,L),x),this.register(this._renderDebouncer),this.register(x.onDprChange(()=>this.handleDevicePixelRatioChange())),this.register(k.onResize(()=>this._fullRefresh())),this.register(k.buffers.onBufferActivate(()=>{var E;return(E=this._renderer.value)==null?void 0:E.clear()})),this.register(_.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(b.onDecorationRegistered(()=>this._fullRefresh())),this.register(b.onDecorationRemoved(()=>this._fullRefresh())),this.register(_.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(k.cols,k.rows),this._fullRefresh()})),this.register(_.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(k.buffer.y,k.buffer.y,!0))),this.register(N.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(x.window,l),this.register(x.onWindowChange(E=>this._registerIntersectionObserver(E,l)))}_registerIntersectionObserver(a,l){if("IntersectionObserver"in a){const _=new a.IntersectionObserver(j=>this._handleIntersectionChange(j[j.length-1]),{threshold:0});_.observe(l),this._observerDisposable.value=(0,S.toDisposable)(()=>_.disconnect())}}_handleIntersectionChange(a){this._isPaused=a.isIntersecting===void 0?a.intersectionRatio===0:!a.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(a,l,_=!1){this._isPaused?this._needsFullRefresh=!0:(_||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(a,l,this._rowCount))}_renderRows(a,l){this._renderer.value&&(a=Math.min(a,this._rowCount-1),l=Math.min(l,this._rowCount-1),this._renderer.value.renderRows(a,l),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:a,end:l}),this._onRender.fire({start:a,end:l}),this._isNextRenderRedrawOnly=!0)}resize(a,l){this._rowCount=l,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(a){this._renderer.value=a,this._renderer.value&&(this._renderer.value.onRequestRedraw(l=>this.refreshRows(l.start,l.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(a){return this._renderDebouncer.addRefreshCallback(a)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var a,l;this._renderer.value&&((l=(a=this._renderer.value).clearTextureAtlas)==null||l.call(a),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(a,l){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var _;return(_=this._renderer.value)==null?void 0:_.handleResize(a,l)}):this._renderer.value.handleResize(a,l),this._fullRefresh())}handleCharSizeChanged(){var a;(a=this._renderer.value)==null||a.handleCharSizeChanged()}handleBlur(){var a;(a=this._renderer.value)==null||a.handleBlur()}handleFocus(){var a;(a=this._renderer.value)==null||a.handleFocus()}handleSelectionChanged(a,l,_){var j;this._selectionState.start=a,this._selectionState.end=l,this._selectionState.columnSelectMode=_,(j=this._renderer.value)==null||j.handleSelectionChanged(a,l,_)}handleCursorMove(){var a;(a=this._renderer.value)==null||a.handleCursorMove()}clear(){var a;(a=this._renderer.value)==null||a.clear()}};o.RenderService=c=d([m(2,p.IOptionsService),m(3,g.ICharSizeService),m(4,p.IDecorationService),m(5,p.IBufferService),m(6,g.ICoreBrowserService),m(7,g.IThemeService)],c)},9312:function(y,o,u){var d=this&&this.__decorate||function(x,N,E,L){var T,P=arguments.length,B=P<3?N:L===null?L=Object.getOwnPropertyDescriptor(N,E):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")B=Reflect.decorate(x,N,E,L);else for(var U=x.length-1;U>=0;U--)(T=x[U])&&(B=(P<3?T(B):P>3?T(N,E,B):T(N,E))||B);return P>3&&B&&Object.defineProperty(N,E,B),B},m=this&&this.__param||function(x,N){return function(E,L){N(E,L,x)}};Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionService=void 0;const f=u(9806),g=u(9504),w=u(456),S=u(4725),v=u(8460),p=u(844),c=u(6114),a=u(4841),l=u(511),_=u(2585),j=" ",b=new RegExp(j,"g");let k=o.SelectionService=class extends p.Disposable{constructor(x,N,E,L,T,P,B,U,K){super(),this._element=x,this._screenElement=N,this._linkifier=E,this._bufferService=L,this._coreService=T,this._mouseService=P,this._optionsService=B,this._renderService=U,this._coreBrowserService=K,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new l.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new v.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new v.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new v.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new v.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=q=>this._handleMouseMove(q),this._mouseUpListener=q=>this._handleMouseUp(q),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(q=>this._handleTrim(q)),this.register(this._bufferService.buffers.onBufferActivate(q=>this._handleBufferActivate(q))),this.enable(),this._model=new w.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,p.toDisposable)(()=>{this._removeMouseDownListeners()}))}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(){const x=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;return!(!x||!N||x[0]===N[0]&&x[1]===N[1])}get selectionText(){const x=this._model.finalSelectionStart,N=this._model.finalSelectionEnd;if(!x||!N)return"";const E=this._bufferService.buffer,L=[];if(this._activeSelectionMode===3){if(x[0]===N[0])return"";const T=x[0]T.replace(b," ")).join(c.isWindows?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(x){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),c.isLinux&&x&&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(x){const N=this._getMouseBufferCoords(x),E=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!!(E&&L&&N)&&this._areCoordsInSelection(N,E,L)}isCellInSelection(x,N){const E=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!(!E||!L)&&this._areCoordsInSelection([x,N],E,L)}_areCoordsInSelection(x,N,E){return x[1]>N[1]&&x[1]=N[0]&&x[0]=N[0]}_selectWordAtCursor(x,N){var T,O;const E=(O=(T=this._linkifier.currentLink)==null?void 0:T.link)==null?void 0:O.range;if(E)return this._model.selectionStart=[E.start.x-1,E.start.y-1],this._model.selectionStartLength=(0,a.getRangeLength)(E,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const L=this._getMouseBufferCoords(x);return!!L&&(this._selectWordAt(L,N),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(x,N){this._model.clearSelection(),x=Math.max(x,0),N=Math.min(N,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,x],this._model.selectionEnd=[this._bufferService.cols,N],this.refresh(),this._onSelectionChange.fire()}_handleTrim(x){this._model.handleTrim(x)&&this.refresh()}_getMouseBufferCoords(x){const N=this._mouseService.getCoords(x,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(N)return N[0]--,N[1]--,N[1]+=this._bufferService.buffer.ydisp,N}_getMouseEventScrollAmount(x){let N=(0,f.getCoordsRelativeToElement)(this._coreBrowserService.window,x,this._screenElement)[1];const E=this._renderService.dimensions.css.canvas.height;return N>=0&&N<=E?0:(N>E&&(N-=E),N=Math.min(Math.max(N,-50),50),N/=50,N/Math.abs(N)+Math.round(14*N))}shouldForceSelection(x){return c.isMac?x.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:x.shiftKey}handleMouseDown(x){if(this._mouseDownTimeStamp=x.timeStamp,(x.button!==2||!this.hasSelection)&&x.button===0){if(!this._enabled){if(!this.shouldForceSelection(x))return;x.stopPropagation()}x.preventDefault(),this._dragScrollAmount=0,this._enabled&&x.shiftKey?this._handleIncrementalClick(x):x.detail===1?this._handleSingleClick(x):x.detail===2?this._handleDoubleClick(x):x.detail===3&&this._handleTripleClick(x),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(),50)}_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(x){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(x))}_handleSingleClick(x){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(x)?3:0,this._model.selectionStart=this._getMouseBufferCoords(x),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const N=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);N&&N.length!==this._model.selectionStart[0]&&N.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(x){this._selectWordAtCursor(x,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(x){const N=this._getMouseBufferCoords(x);N&&(this._activeSelectionMode=2,this._selectLineAt(N[1]))}shouldColumnSelect(x){return x.altKey&&!(c.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(x){if(x.stopImmediatePropagation(),!this._model.selectionStart)return;const N=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(x),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const E=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(x.ydisp+this._bufferService.rows,x.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=x.ydisp),this.refresh()}}_handleMouseUp(x){const N=x.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&N<500&&x.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const E=this._mouseService.getCoords(x,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(E&&E[0]!==void 0&&E[1]!==void 0){const L=(0,g.moveToCellSequence)(E[0]-1,E[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(L,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const x=this._model.finalSelectionStart,N=this._model.finalSelectionEnd,E=!(!x||!N||x[0]===N[0]&&x[1]===N[1]);E?x&&N&&(this._oldSelectionStart&&this._oldSelectionEnd&&x[0]===this._oldSelectionStart[0]&&x[1]===this._oldSelectionStart[1]&&N[0]===this._oldSelectionEnd[0]&&N[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(x,N,E)):this._oldHasSelection&&this._fireOnSelectionChange(x,N,E)}_fireOnSelectionChange(x,N,E){this._oldSelectionStart=x,this._oldSelectionEnd=N,this._oldHasSelection=E,this._onSelectionChange.fire()}_handleBufferActivate(x){this.clearSelection(),this._trimListener.dispose(),this._trimListener=x.activeBuffer.lines.onTrim(N=>this._handleTrim(N))}_convertViewportColToCharacterIndex(x,N){let E=N;for(let L=0;N>=L;L++){const T=x.loadCell(L,this._workCell).getChars().length;this._workCell.getWidth()===0?E--:T>1&&N!==L&&(E+=T-1)}return E}setSelection(x,N,E){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[x,N],this._model.selectionStartLength=E,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(x){this._isClickInSelection(x)||(this._selectWordAtCursor(x,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(x,N,E=!0,L=!0){if(x[0]>=this._bufferService.cols)return;const T=this._bufferService.buffer,O=T.lines.get(x[1]);if(!O)return;const B=T.translateBufferLineToString(x[1],!1);let F=this._convertViewportColToCharacterIndex(O,x[0]),z=F;const K=x[0]-F;let $=0,R=0,D=0,M=0;if(B.charAt(F)===" "){for(;F>0&&B.charAt(F-1)===" ";)F--;for(;z1&&(M+=J-1,z+=J-1);Y>0&&F>0&&!this._isCharWordSeparator(O.loadCell(Y-1,this._workCell));){O.loadCell(Y-1,this._workCell);const I=this._workCell.getChars().length;this._workCell.getWidth()===0?($++,Y--):I>1&&(D+=I-1,F-=I-1),F--,Y--}for(;H1&&(M+=I-1,z+=I-1),z++,H++}}z++;let P=F+K-$+D,U=Math.min(this._bufferService.cols,z-F+$+R-D-M);if(N||B.slice(F,z).trim()!==""){if(E&&P===0&&O.getCodePoint(0)!==32){const Y=T.lines.get(x[1]-1);if(Y&&O.isWrapped&&Y.getCodePoint(this._bufferService.cols-1)!==32){const H=this._getWordAt([this._bufferService.cols-1,x[1]-1],!1,!0,!1);if(H){const J=this._bufferService.cols-H.start;P-=J,U+=J}}}if(L&&P+U===this._bufferService.cols&&O.getCodePoint(this._bufferService.cols-1)!==32){const Y=T.lines.get(x[1]+1);if(Y!=null&&Y.isWrapped&&Y.getCodePoint(0)!==32){const H=this._getWordAt([0,x[1]+1],!1,!1,!0);H&&(U+=H.length)}}return{start:P,length:U}}}_selectWordAt(x,N){const E=this._getWordAt(x,N);if(E){for(;E.start<0;)E.start+=this._bufferService.cols,x[1]--;this._model.selectionStart=[E.start,x[1]],this._model.selectionStartLength=E.length}}_selectToWordAt(x){const N=this._getWordAt(x,!0);if(N){let E=x[1];for(;N.start<0;)N.start+=this._bufferService.cols,E--;if(!this._model.areSelectionValuesReversed())for(;N.start+N.length>this._bufferService.cols;)N.length-=this._bufferService.cols,E++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?N.start:N.start+N.length,E]}}_isCharWordSeparator(x){return x.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(x.getChars())>=0}_selectLineAt(x){const N=this._bufferService.buffer.getWrappedRangeForLine(x),E={start:{x:0,y:N.first},end:{x:this._bufferService.cols-1,y:N.last}};this._model.selectionStart=[0,N.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,a.getRangeLength)(E,this._bufferService.cols)}};o.SelectionService=k=d([m(3,_.IBufferService),m(4,_.ICoreService),m(5,S.IMouseService),m(6,_.IOptionsService),m(7,S.IRenderService),m(8,S.ICoreBrowserService)],k)},4725:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ILinkProviderService=o.IThemeService=o.ICharacterJoinerService=o.ISelectionService=o.IRenderService=o.IMouseService=o.ICoreBrowserService=o.ICharSizeService=void 0;const d=u(8343);o.ICharSizeService=(0,d.createDecorator)("CharSizeService"),o.ICoreBrowserService=(0,d.createDecorator)("CoreBrowserService"),o.IMouseService=(0,d.createDecorator)("MouseService"),o.IRenderService=(0,d.createDecorator)("RenderService"),o.ISelectionService=(0,d.createDecorator)("SelectionService"),o.ICharacterJoinerService=(0,d.createDecorator)("CharacterJoinerService"),o.IThemeService=(0,d.createDecorator)("ThemeService"),o.ILinkProviderService=(0,d.createDecorator)("LinkProviderService")},6731:function(y,o,u){var d=this&&this.__decorate||function(k,x,N,E){var L,T=arguments.length,O=T<3?x:E===null?E=Object.getOwnPropertyDescriptor(x,N):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(k,x,N,E);else for(var B=k.length-1;B>=0;B--)(L=k[B])&&(O=(T<3?L(O):T>3?L(x,N,O):L(x,N))||O);return T>3&&O&&Object.defineProperty(x,N,O),O},m=this&&this.__param||function(k,x){return function(N,E){x(N,E,k)}};Object.defineProperty(o,"__esModule",{value:!0}),o.ThemeService=o.DEFAULT_ANSI_COLORS=void 0;const f=u(7239),g=u(8055),w=u(8460),S=u(844),v=u(2585),p=g.css.toColor("#ffffff"),c=g.css.toColor("#000000"),a=g.css.toColor("#ffffff"),l=g.css.toColor("#000000"),_={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};o.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const k=[g.css.toColor("#2e3436"),g.css.toColor("#cc0000"),g.css.toColor("#4e9a06"),g.css.toColor("#c4a000"),g.css.toColor("#3465a4"),g.css.toColor("#75507b"),g.css.toColor("#06989a"),g.css.toColor("#d3d7cf"),g.css.toColor("#555753"),g.css.toColor("#ef2929"),g.css.toColor("#8ae234"),g.css.toColor("#fce94f"),g.css.toColor("#729fcf"),g.css.toColor("#ad7fa8"),g.css.toColor("#34e2e2"),g.css.toColor("#eeeeec")],x=[0,95,135,175,215,255];for(let N=0;N<216;N++){const E=x[N/36%6|0],L=x[N/6%6|0],T=x[N%6];k.push({css:g.channels.toCss(E,L,T),rgba:g.channels.toRgba(E,L,T)})}for(let N=0;N<24;N++){const E=8+10*N;k.push({css:g.channels.toCss(E,E,E),rgba:g.channels.toRgba(E,E,E)})}return k})());let j=o.ThemeService=class extends S.Disposable{get colors(){return this._colors}constructor(k){super(),this._optionsService=k,this._contrastCache=new f.ColorContrastCache,this._halfContrastCache=new f.ColorContrastCache,this._onChangeColors=this.register(new w.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:p,background:c,cursor:a,cursorAccent:l,selectionForeground:void 0,selectionBackgroundTransparent:_,selectionBackgroundOpaque:g.color.blend(c,_),selectionInactiveBackgroundTransparent:_,selectionInactiveBackgroundOpaque:g.color.blend(c,_),ansi:o.DEFAULT_ANSI_COLORS.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)))}_setTheme(k={}){const x=this._colors;if(x.foreground=b(k.foreground,p),x.background=b(k.background,c),x.cursor=b(k.cursor,a),x.cursorAccent=b(k.cursorAccent,l),x.selectionBackgroundTransparent=b(k.selectionBackground,_),x.selectionBackgroundOpaque=g.color.blend(x.background,x.selectionBackgroundTransparent),x.selectionInactiveBackgroundTransparent=b(k.selectionInactiveBackground,x.selectionBackgroundTransparent),x.selectionInactiveBackgroundOpaque=g.color.blend(x.background,x.selectionInactiveBackgroundTransparent),x.selectionForeground=k.selectionForeground?b(k.selectionForeground,g.NULL_COLOR):void 0,x.selectionForeground===g.NULL_COLOR&&(x.selectionForeground=void 0),g.color.isOpaque(x.selectionBackgroundTransparent)&&(x.selectionBackgroundTransparent=g.color.opacity(x.selectionBackgroundTransparent,.3)),g.color.isOpaque(x.selectionInactiveBackgroundTransparent)&&(x.selectionInactiveBackgroundTransparent=g.color.opacity(x.selectionInactiveBackgroundTransparent,.3)),x.ansi=o.DEFAULT_ANSI_COLORS.slice(),x.ansi[0]=b(k.black,o.DEFAULT_ANSI_COLORS[0]),x.ansi[1]=b(k.red,o.DEFAULT_ANSI_COLORS[1]),x.ansi[2]=b(k.green,o.DEFAULT_ANSI_COLORS[2]),x.ansi[3]=b(k.yellow,o.DEFAULT_ANSI_COLORS[3]),x.ansi[4]=b(k.blue,o.DEFAULT_ANSI_COLORS[4]),x.ansi[5]=b(k.magenta,o.DEFAULT_ANSI_COLORS[5]),x.ansi[6]=b(k.cyan,o.DEFAULT_ANSI_COLORS[6]),x.ansi[7]=b(k.white,o.DEFAULT_ANSI_COLORS[7]),x.ansi[8]=b(k.brightBlack,o.DEFAULT_ANSI_COLORS[8]),x.ansi[9]=b(k.brightRed,o.DEFAULT_ANSI_COLORS[9]),x.ansi[10]=b(k.brightGreen,o.DEFAULT_ANSI_COLORS[10]),x.ansi[11]=b(k.brightYellow,o.DEFAULT_ANSI_COLORS[11]),x.ansi[12]=b(k.brightBlue,o.DEFAULT_ANSI_COLORS[12]),x.ansi[13]=b(k.brightMagenta,o.DEFAULT_ANSI_COLORS[13]),x.ansi[14]=b(k.brightCyan,o.DEFAULT_ANSI_COLORS[14]),x.ansi[15]=b(k.brightWhite,o.DEFAULT_ANSI_COLORS[15]),k.extendedAnsi){const N=Math.min(x.ansi.length-16,k.extendedAnsi.length);for(let E=0;E{Object.defineProperty(o,"__esModule",{value:!0}),o.CircularList=void 0;const d=u(8460),m=u(844);class f extends m.Disposable{constructor(w){super(),this._maxLength=w,this.onDeleteEmitter=this.register(new d.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new d.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new d.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(w){if(this._maxLength===w)return;const S=new Array(w);for(let v=0;vthis._length)for(let S=this._length;S=w;p--)this._array[this._getCyclicIndex(p+v.length)]=this._array[this._getCyclicIndex(p)];for(let p=0;pthis._maxLength){const p=this._length+v.length-this._maxLength;this._startIndex+=p,this._length=this._maxLength,this.onTrimEmitter.fire(p)}else this._length+=v.length}trimStart(w){w>this._length&&(w=this._length),this._startIndex+=w,this._length-=w,this.onTrimEmitter.fire(w)}shiftElements(w,S,v){if(!(S<=0)){if(w<0||w>=this._length)throw new Error("start argument out of range");if(w+v<0)throw new Error("Cannot shift elements in list beyond index 0");if(v>0){for(let c=S-1;c>=0;c--)this.set(w+c+v,this.get(w+c));const p=w+S+v-this._length;if(p>0)for(this._length+=p;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let p=0;p{Object.defineProperty(o,"__esModule",{value:!0}),o.clone=void 0,o.clone=function u(d,m=5){if(typeof d!="object")return d;const f=Array.isArray(d)?[]:{};for(const g in d)f[g]=m<=1?d[g]:d[g]&&u(d[g],m-1);return f}},8055:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.contrastRatio=o.toPaddedHex=o.rgba=o.rgb=o.css=o.color=o.channels=o.NULL_COLOR=void 0;let u=0,d=0,m=0,f=0;var g,w,S,v,p;function c(l){const _=l.toString(16);return _.length<2?"0"+_:_}function a(l,_){return l<_?(_+.05)/(l+.05):(l+.05)/(_+.05)}o.NULL_COLOR={css:"#00000000",rgba:0},function(l){l.toCss=function(_,j,b,k){return k!==void 0?`#${c(_)}${c(j)}${c(b)}${c(k)}`:`#${c(_)}${c(j)}${c(b)}`},l.toRgba=function(_,j,b,k=255){return(_<<24|j<<16|b<<8|k)>>>0},l.toColor=function(_,j,b,k){return{css:l.toCss(_,j,b,k),rgba:l.toRgba(_,j,b,k)}}}(g||(o.channels=g={})),function(l){function _(j,b){return f=Math.round(255*b),[u,d,m]=p.toChannels(j.rgba),{css:g.toCss(u,d,m,f),rgba:g.toRgba(u,d,m,f)}}l.blend=function(j,b){if(f=(255&b.rgba)/255,f===1)return{css:b.css,rgba:b.rgba};const k=b.rgba>>24&255,x=b.rgba>>16&255,N=b.rgba>>8&255,E=j.rgba>>24&255,L=j.rgba>>16&255,T=j.rgba>>8&255;return u=E+Math.round((k-E)*f),d=L+Math.round((x-L)*f),m=T+Math.round((N-T)*f),{css:g.toCss(u,d,m),rgba:g.toRgba(u,d,m)}},l.isOpaque=function(j){return(255&j.rgba)==255},l.ensureContrastRatio=function(j,b,k){const x=p.ensureContrastRatio(j.rgba,b.rgba,k);if(x)return g.toColor(x>>24&255,x>>16&255,x>>8&255)},l.opaque=function(j){const b=(255|j.rgba)>>>0;return[u,d,m]=p.toChannels(b),{css:g.toCss(u,d,m),rgba:b}},l.opacity=_,l.multiplyOpacity=function(j,b){return f=255&j.rgba,_(j,f*b/255)},l.toColorRGB=function(j){return[j.rgba>>24&255,j.rgba>>16&255,j.rgba>>8&255]}}(w||(o.color=w={})),function(l){let _,j;try{const b=document.createElement("canvas");b.width=1,b.height=1;const k=b.getContext("2d",{willReadFrequently:!0});k&&(_=k,_.globalCompositeOperation="copy",j=_.createLinearGradient(0,0,1,1))}catch{}l.toColor=function(b){if(b.match(/#[\da-f]{3,8}/i))switch(b.length){case 4:return u=parseInt(b.slice(1,2).repeat(2),16),d=parseInt(b.slice(2,3).repeat(2),16),m=parseInt(b.slice(3,4).repeat(2),16),g.toColor(u,d,m);case 5:return u=parseInt(b.slice(1,2).repeat(2),16),d=parseInt(b.slice(2,3).repeat(2),16),m=parseInt(b.slice(3,4).repeat(2),16),f=parseInt(b.slice(4,5).repeat(2),16),g.toColor(u,d,m,f);case 7:return{css:b,rgba:(parseInt(b.slice(1),16)<<8|255)>>>0};case 9:return{css:b,rgba:parseInt(b.slice(1),16)>>>0}}const k=b.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(k)return u=parseInt(k[1]),d=parseInt(k[2]),m=parseInt(k[3]),f=Math.round(255*(k[5]===void 0?1:parseFloat(k[5]))),g.toColor(u,d,m,f);if(!_||!j)throw new Error("css.toColor: Unsupported css format");if(_.fillStyle=j,_.fillStyle=b,typeof _.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(_.fillRect(0,0,1,1),[u,d,m,f]=_.getImageData(0,0,1,1).data,f!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(u,d,m,f),css:b}}}(S||(o.css=S={})),function(l){function _(j,b,k){const x=j/255,N=b/255,E=k/255;return .2126*(x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4))+.7152*(N<=.03928?N/12.92:Math.pow((N+.055)/1.055,2.4))+.0722*(E<=.03928?E/12.92:Math.pow((E+.055)/1.055,2.4))}l.relativeLuminance=function(j){return _(j>>16&255,j>>8&255,255&j)},l.relativeLuminance2=_}(v||(o.rgb=v={})),function(l){function _(b,k,x){const N=b>>24&255,E=b>>16&255,L=b>>8&255;let T=k>>24&255,O=k>>16&255,B=k>>8&255,F=a(v.relativeLuminance2(T,O,B),v.relativeLuminance2(N,E,L));for(;F0||O>0||B>0);)T-=Math.max(0,Math.ceil(.1*T)),O-=Math.max(0,Math.ceil(.1*O)),B-=Math.max(0,Math.ceil(.1*B)),F=a(v.relativeLuminance2(T,O,B),v.relativeLuminance2(N,E,L));return(T<<24|O<<16|B<<8|255)>>>0}function j(b,k,x){const N=b>>24&255,E=b>>16&255,L=b>>8&255;let T=k>>24&255,O=k>>16&255,B=k>>8&255,F=a(v.relativeLuminance2(T,O,B),v.relativeLuminance2(N,E,L));for(;F>>0}l.blend=function(b,k){if(f=(255&k)/255,f===1)return k;const x=k>>24&255,N=k>>16&255,E=k>>8&255,L=b>>24&255,T=b>>16&255,O=b>>8&255;return u=L+Math.round((x-L)*f),d=T+Math.round((N-T)*f),m=O+Math.round((E-O)*f),g.toRgba(u,d,m)},l.ensureContrastRatio=function(b,k,x){const N=v.relativeLuminance(b>>8),E=v.relativeLuminance(k>>8);if(a(N,E)>8));if(Ba(N,v.relativeLuminance(F>>8))?O:F}return O}const L=j(b,k,x),T=a(N,v.relativeLuminance(L>>8));if(Ta(N,v.relativeLuminance(O>>8))?L:O}return L}},l.reduceLuminance=_,l.increaseLuminance=j,l.toChannels=function(b){return[b>>24&255,b>>16&255,b>>8&255,255&b]}}(p||(o.rgba=p={})),o.toPaddedHex=c,o.contrastRatio=a},8969:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreTerminal=void 0;const d=u(844),m=u(2585),f=u(4348),g=u(7866),w=u(744),S=u(7302),v=u(6975),p=u(8460),c=u(1753),a=u(1480),l=u(7994),_=u(9282),j=u(5435),b=u(5981),k=u(2660);let x=!1;class N extends d.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new p.EventEmitter),this._onScroll.event(L=>{var T;(T=this._onScrollApi)==null||T.fire(L.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(L){for(const T in L)this.optionsService.options[T]=L[T]}constructor(L){super(),this._windowsWrappingHeuristics=this.register(new d.MutableDisposable),this._onBinary=this.register(new p.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new p.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new p.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new p.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new p.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new p.EventEmitter),this._instantiationService=new f.InstantiationService,this.optionsService=this.register(new S.OptionsService(L)),this._instantiationService.setService(m.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(w.BufferService)),this._instantiationService.setService(m.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(g.LogService)),this._instantiationService.setService(m.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(v.CoreService)),this._instantiationService.setService(m.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(c.CoreMouseService)),this._instantiationService.setService(m.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(a.UnicodeService)),this._instantiationService.setService(m.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(l.CharsetService),this._instantiationService.setService(m.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(k.OscLinkService),this._instantiationService.setService(m.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new j.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,p.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,p.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,p.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,p.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(T=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(T=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new b.WriteBuffer((T,O)=>this._inputHandler.parse(T,O))),this.register((0,p.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(L,T){this._writeBuffer.write(L,T)}writeSync(L,T){this._logService.logLevel<=m.LogLevelEnum.WARN&&!x&&(this._logService.warn("writeSync is unreliable and will be removed soon."),x=!0),this._writeBuffer.writeSync(L,T)}input(L,T=!0){this.coreService.triggerDataEvent(L,T)}resize(L,T){isNaN(L)||isNaN(T)||(L=Math.max(L,w.MINIMUM_COLS),T=Math.max(T,w.MINIMUM_ROWS),this._bufferService.resize(L,T))}scroll(L,T=!1){this._bufferService.scroll(L,T)}scrollLines(L,T,O){this._bufferService.scrollLines(L,T,O)}scrollPages(L){this.scrollLines(L*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(L){const T=L-this._bufferService.buffer.ydisp;T!==0&&this.scrollLines(T)}registerEscHandler(L,T){return this._inputHandler.registerEscHandler(L,T)}registerDcsHandler(L,T){return this._inputHandler.registerDcsHandler(L,T)}registerCsiHandler(L,T){return this._inputHandler.registerCsiHandler(L,T)}registerOscHandler(L,T){return this._inputHandler.registerOscHandler(L,T)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let L=!1;const T=this.optionsService.rawOptions.windowsPty;T&&T.buildNumber!==void 0&&T.buildNumber!==void 0?L=T.backend==="conpty"&&T.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(L=!0),L?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const L=[];L.push(this.onLineFeed(_.updateWindowsModeWrappedState.bind(null,this._bufferService))),L.push(this.registerCsiHandler({final:"H"},()=>((0,_.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,d.toDisposable)(()=>{for(const T of L)T.dispose()})}}}o.CoreTerminal=N},8460:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.runAndSubscribe=o.forwardEvent=o.EventEmitter=void 0,o.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=u=>(this._listeners.push(u),{dispose:()=>{if(!this._disposed){for(let d=0;dd.fire(m))},o.runAndSubscribe=function(u,d){return d(void 0),u(m=>d(m))}},5435:function(y,o,u){var d=this&&this.__decorate||function($,R,D,M){var P,U=arguments.length,Y=U<3?R:M===null?M=Object.getOwnPropertyDescriptor(R,D):M;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")Y=Reflect.decorate($,R,D,M);else for(var H=$.length-1;H>=0;H--)(P=$[H])&&(Y=(U<3?P(Y):U>3?P(R,D,Y):P(R,D))||Y);return U>3&&Y&&Object.defineProperty(R,D,Y),Y},m=this&&this.__param||function($,R){return function(D,M){R(D,M,$)}};Object.defineProperty(o,"__esModule",{value:!0}),o.InputHandler=o.WindowsOptionsReportType=void 0;const f=u(2584),g=u(7116),w=u(2015),S=u(844),v=u(482),p=u(8437),c=u(8460),a=u(643),l=u(511),_=u(3734),j=u(2585),b=u(1480),k=u(6242),x=u(6351),N=u(5941),E={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function T($,R){if($>24)return R.setWinLines||!1;switch($){case 1:return!!R.restoreWin;case 2:return!!R.minimizeWin;case 3:return!!R.setWinPosition;case 4:return!!R.setWinSizePixels;case 5:return!!R.raiseWin;case 6:return!!R.lowerWin;case 7:return!!R.refreshWin;case 8:return!!R.setWinSizeChars;case 9:return!!R.maximizeWin;case 10:return!!R.fullscreenWin;case 11:return!!R.getWinState;case 13:return!!R.getWinPosition;case 14:return!!R.getWinSizePixels;case 15:return!!R.getScreenSizePixels;case 16:return!!R.getCellSizePixels;case 18:return!!R.getWinSizeChars;case 19:return!!R.getScreenSizeChars;case 20:return!!R.getIconTitle;case 21:return!!R.getWinTitle;case 22:return!!R.pushTitle;case 23:return!!R.popTitle;case 24:return!!R.setWinLines}return!1}var O;(function($){$[$.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",$[$.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(O||(o.WindowsOptionsReportType=O={}));let B=0;class F extends S.Disposable{getAttrData(){return this._curAttrData}constructor(R,D,M,P,U,Y,H,J,I=new w.EscapeSequenceParser){super(),this._bufferService=R,this._charsetService=D,this._coreService=M,this._logService=P,this._optionsService=U,this._oscLinkService=Y,this._coreMouseService=H,this._unicodeService=J,this._parser=I,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new v.StringToUtf32,this._utf8Decoder=new v.Utf8ToUtf32,this._workCell=new l.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=p.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=p.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new c.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new c.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new c.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new c.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new c.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new c.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new c.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new c.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new c.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new c.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new c.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new c.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new c.EventEmitter),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 z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(A=>this._activeBuffer=A.activeBuffer)),this._parser.setCsiHandlerFallback((A,q)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(A),params:q.toArray()})}),this._parser.setEscHandlerFallback(A=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(A)})}),this._parser.setExecuteHandlerFallback(A=>{this._logService.debug("Unknown EXECUTE code: ",{code:A})}),this._parser.setOscHandlerFallback((A,q,W)=>{this._logService.debug("Unknown OSC code: ",{identifier:A,action:q,data:W})}),this._parser.setDcsHandlerFallback((A,q,W)=>{q==="HOOK"&&(W=W.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(A),action:q,payload:W})}),this._parser.setPrintHandler((A,q,W)=>this.print(A,q,W)),this._parser.registerCsiHandler({final:"@"},A=>this.insertChars(A)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},A=>this.scrollLeft(A)),this._parser.registerCsiHandler({final:"A"},A=>this.cursorUp(A)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},A=>this.scrollRight(A)),this._parser.registerCsiHandler({final:"B"},A=>this.cursorDown(A)),this._parser.registerCsiHandler({final:"C"},A=>this.cursorForward(A)),this._parser.registerCsiHandler({final:"D"},A=>this.cursorBackward(A)),this._parser.registerCsiHandler({final:"E"},A=>this.cursorNextLine(A)),this._parser.registerCsiHandler({final:"F"},A=>this.cursorPrecedingLine(A)),this._parser.registerCsiHandler({final:"G"},A=>this.cursorCharAbsolute(A)),this._parser.registerCsiHandler({final:"H"},A=>this.cursorPosition(A)),this._parser.registerCsiHandler({final:"I"},A=>this.cursorForwardTab(A)),this._parser.registerCsiHandler({final:"J"},A=>this.eraseInDisplay(A,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},A=>this.eraseInDisplay(A,!0)),this._parser.registerCsiHandler({final:"K"},A=>this.eraseInLine(A,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},A=>this.eraseInLine(A,!0)),this._parser.registerCsiHandler({final:"L"},A=>this.insertLines(A)),this._parser.registerCsiHandler({final:"M"},A=>this.deleteLines(A)),this._parser.registerCsiHandler({final:"P"},A=>this.deleteChars(A)),this._parser.registerCsiHandler({final:"S"},A=>this.scrollUp(A)),this._parser.registerCsiHandler({final:"T"},A=>this.scrollDown(A)),this._parser.registerCsiHandler({final:"X"},A=>this.eraseChars(A)),this._parser.registerCsiHandler({final:"Z"},A=>this.cursorBackwardTab(A)),this._parser.registerCsiHandler({final:"`"},A=>this.charPosAbsolute(A)),this._parser.registerCsiHandler({final:"a"},A=>this.hPositionRelative(A)),this._parser.registerCsiHandler({final:"b"},A=>this.repeatPrecedingCharacter(A)),this._parser.registerCsiHandler({final:"c"},A=>this.sendDeviceAttributesPrimary(A)),this._parser.registerCsiHandler({prefix:">",final:"c"},A=>this.sendDeviceAttributesSecondary(A)),this._parser.registerCsiHandler({final:"d"},A=>this.linePosAbsolute(A)),this._parser.registerCsiHandler({final:"e"},A=>this.vPositionRelative(A)),this._parser.registerCsiHandler({final:"f"},A=>this.hVPosition(A)),this._parser.registerCsiHandler({final:"g"},A=>this.tabClear(A)),this._parser.registerCsiHandler({final:"h"},A=>this.setMode(A)),this._parser.registerCsiHandler({prefix:"?",final:"h"},A=>this.setModePrivate(A)),this._parser.registerCsiHandler({final:"l"},A=>this.resetMode(A)),this._parser.registerCsiHandler({prefix:"?",final:"l"},A=>this.resetModePrivate(A)),this._parser.registerCsiHandler({final:"m"},A=>this.charAttributes(A)),this._parser.registerCsiHandler({final:"n"},A=>this.deviceStatus(A)),this._parser.registerCsiHandler({prefix:"?",final:"n"},A=>this.deviceStatusPrivate(A)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},A=>this.softReset(A)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},A=>this.setCursorStyle(A)),this._parser.registerCsiHandler({final:"r"},A=>this.setScrollRegion(A)),this._parser.registerCsiHandler({final:"s"},A=>this.saveCursor(A)),this._parser.registerCsiHandler({final:"t"},A=>this.windowOptions(A)),this._parser.registerCsiHandler({final:"u"},A=>this.restoreCursor(A)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},A=>this.insertColumns(A)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},A=>this.deleteColumns(A)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},A=>this.selectProtected(A)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},A=>this.requestMode(A,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},A=>this.requestMode(A,!1)),this._parser.setExecuteHandler(f.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(f.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(f.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(f.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(f.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(f.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(f.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(f.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(f.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(f.C1.IND,()=>this.index()),this._parser.setExecuteHandler(f.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(f.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new k.OscHandler(A=>(this.setTitle(A),this.setIconName(A),!0))),this._parser.registerOscHandler(1,new k.OscHandler(A=>this.setIconName(A))),this._parser.registerOscHandler(2,new k.OscHandler(A=>this.setTitle(A))),this._parser.registerOscHandler(4,new k.OscHandler(A=>this.setOrReportIndexedColor(A))),this._parser.registerOscHandler(8,new k.OscHandler(A=>this.setHyperlink(A))),this._parser.registerOscHandler(10,new k.OscHandler(A=>this.setOrReportFgColor(A))),this._parser.registerOscHandler(11,new k.OscHandler(A=>this.setOrReportBgColor(A))),this._parser.registerOscHandler(12,new k.OscHandler(A=>this.setOrReportCursorColor(A))),this._parser.registerOscHandler(104,new k.OscHandler(A=>this.restoreIndexedColor(A))),this._parser.registerOscHandler(110,new k.OscHandler(A=>this.restoreFgColor(A))),this._parser.registerOscHandler(111,new k.OscHandler(A=>this.restoreBgColor(A))),this._parser.registerOscHandler(112,new k.OscHandler(A=>this.restoreCursorColor(A))),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(const A in g.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:A},()=>this.selectCharset("("+A)),this._parser.registerEscHandler({intermediates:")",final:A},()=>this.selectCharset(")"+A)),this._parser.registerEscHandler({intermediates:"*",final:A},()=>this.selectCharset("*"+A)),this._parser.registerEscHandler({intermediates:"+",final:A},()=>this.selectCharset("+"+A)),this._parser.registerEscHandler({intermediates:"-",final:A},()=>this.selectCharset("-"+A)),this._parser.registerEscHandler({intermediates:".",final:A},()=>this.selectCharset("."+A)),this._parser.registerEscHandler({intermediates:"/",final:A},()=>this.selectCharset("/"+A));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(A=>(this._logService.error("Parsing error: ",A),A)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new x.DcsHandler((A,q)=>this.requestStatusString(A,q)))}_preserveStack(R,D,M,P){this._parseStack.paused=!0,this._parseStack.cursorStartX=R,this._parseStack.cursorStartY=D,this._parseStack.decodedLength=M,this._parseStack.position=P}_logSlowResolvingAsync(R){this._logService.logLevel<=j.LogLevelEnum.WARN&&Promise.race([R,new Promise((D,M)=>setTimeout(()=>M("#SLOW_TIMEOUT"),5e3))]).catch(D=>{if(D!=="#SLOW_TIMEOUT")throw D;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(R,D){let M,P=this._activeBuffer.x,U=this._activeBuffer.y,Y=0;const H=this._parseStack.paused;if(H){if(M=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,D))return this._logSlowResolvingAsync(M),M;P=this._parseStack.cursorStartX,U=this._parseStack.cursorStartY,this._parseStack.paused=!1,R.length>L&&(Y=this._parseStack.position+L)}if(this._logService.logLevel<=j.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof R=="string"?` "${R}"`:` "${Array.prototype.map.call(R,A=>String.fromCharCode(A)).join("")}"`),typeof R=="string"?R.split("").map(A=>A.charCodeAt(0)):R),this._parseBuffer.lengthL)for(let A=Y;A0&&W.getWidth(this._activeBuffer.x-1)===2&&W.setCellFromCodepoint(this._activeBuffer.x-1,0,1,q);let X=this._parser.precedingJoinState;for(let Q=D;QJ){if(I){const Ce=W;let ae=this._activeBuffer.x-he;for(this._activeBuffer.x=he,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),W=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),he>0&&W instanceof p.BufferLine&&W.copyCellsFrom(Ce,ae,0,he,!1);ae=0;)W.setCellFromCodepoint(this._activeBuffer.x++,0,0,q)}else if(A&&(W.insertCells(this._activeBuffer.x,U-he,this._activeBuffer.getNullCell(q)),W.getWidth(J-1)===2&&W.setCellFromCodepoint(J-1,a.NULL_CELL_CODE,a.NULL_CELL_WIDTH,q)),W.setCellFromCodepoint(this._activeBuffer.x++,P,U,q),U>0)for(;--U;)W.setCellFromCodepoint(this._activeBuffer.x++,0,0,q)}this._parser.precedingJoinState=X,this._activeBuffer.x0&&W.getWidth(this._activeBuffer.x)===0&&!W.hasContent(this._activeBuffer.x)&&W.setCellFromCodepoint(this._activeBuffer.x,0,1,q),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(R,D){return R.final!=="t"||R.prefix||R.intermediates?this._parser.registerCsiHandler(R,D):this._parser.registerCsiHandler(R,M=>!T(M.params[0],this._optionsService.rawOptions.windowOptions)||D(M))}registerDcsHandler(R,D){return this._parser.registerDcsHandler(R,new x.DcsHandler(D))}registerEscHandler(R,D){return this._parser.registerEscHandler(R,D)}registerOscHandler(R,D){return this._parser.registerOscHandler(R,new k.OscHandler(D))}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(){var R;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&&((R=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&R.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);D.hasWidth(this._activeBuffer.x)&&!D.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const R=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-R),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(R=this._bufferService.cols-1){this._activeBuffer.x=Math.min(R,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(R,D){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=R,this._activeBuffer.y=this._activeBuffer.scrollTop+D):(this._activeBuffer.x=R,this._activeBuffer.y=D),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(R,D){this._restrictCursor(),this._setCursor(this._activeBuffer.x+R,this._activeBuffer.y+D)}cursorUp(R){const D=this._activeBuffer.y-this._activeBuffer.scrollTop;return D>=0?this._moveCursor(0,-Math.min(D,R.params[0]||1)):this._moveCursor(0,-(R.params[0]||1)),!0}cursorDown(R){const D=this._activeBuffer.scrollBottom-this._activeBuffer.y;return D>=0?this._moveCursor(0,Math.min(D,R.params[0]||1)):this._moveCursor(0,R.params[0]||1),!0}cursorForward(R){return this._moveCursor(R.params[0]||1,0),!0}cursorBackward(R){return this._moveCursor(-(R.params[0]||1),0),!0}cursorNextLine(R){return this.cursorDown(R),this._activeBuffer.x=0,!0}cursorPrecedingLine(R){return this.cursorUp(R),this._activeBuffer.x=0,!0}cursorCharAbsolute(R){return this._setCursor((R.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(R){return this._setCursor(R.length>=2?(R.params[1]||1)-1:0,(R.params[0]||1)-1),!0}charPosAbsolute(R){return this._setCursor((R.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(R){return this._moveCursor(R.params[0]||1,0),!0}linePosAbsolute(R){return this._setCursor(this._activeBuffer.x,(R.params[0]||1)-1),!0}vPositionRelative(R){return this._moveCursor(0,R.params[0]||1),!0}hVPosition(R){return this.cursorPosition(R),!0}tabClear(R){const D=R.params[0];return D===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:D===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(R){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=R.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(R){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=R.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(R){const D=R.params[0];return D===1&&(this._curAttrData.bg|=536870912),D!==2&&D!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(R,D,M,P=!1,U=!1){const Y=this._activeBuffer.lines.get(this._activeBuffer.ybase+R);Y.replaceCells(D,M,this._activeBuffer.getNullCell(this._eraseAttrData()),U),P&&(Y.isWrapped=!1)}_resetBufferLine(R,D=!1){const M=this._activeBuffer.lines.get(this._activeBuffer.ybase+R);M&&(M.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),D),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+R),M.isWrapped=!1)}eraseInDisplay(R,D=!1){let M;switch(this._restrictCursor(this._bufferService.cols),R.params[0]){case 0:for(M=this._activeBuffer.y,this._dirtyRowTracker.markDirty(M),this._eraseInBufferLine(M++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);M=this._bufferService.cols&&(this._activeBuffer.lines.get(M+1).isWrapped=!1);M--;)this._resetBufferLine(M,D);this._dirtyRowTracker.markDirty(0);break;case 2:for(M=this._bufferService.rows,this._dirtyRowTracker.markDirty(M-1);M--;)this._resetBufferLine(M,D);this._dirtyRowTracker.markDirty(0);break;case 3:const P=this._activeBuffer.lines.length-this._bufferService.rows;P>0&&(this._activeBuffer.lines.trimStart(P),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-P,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-P,0),this._onScroll.fire(0))}return!0}eraseInLine(R,D=!1){switch(this._restrictCursor(this._bufferService.cols),R.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,D);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,D)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(R){this._restrictCursor();let D=R.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 I=J;for(let A=1;A0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(f.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(f.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(R){return R.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(f.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(f.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(R.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(f.C0.ESC+"[>83;40003;0c")),!0}_is(R){return(this._optionsService.rawOptions.termName+"").indexOf(R)===0}setMode(R){for(let D=0;Die?1:2,X=R.params[0];return Q=X,re=D?X===2?4:X===4?W(Y.modes.insertMode):X===12?3:X===20?W(q.convertEol):0:X===1?W(M.applicationCursorKeys):X===3?q.windowOptions.setWinLines?J===80?2:J===132?1:0:0:X===6?W(M.origin):X===7?W(M.wraparound):X===8?3:X===9?W(P==="X10"):X===12?W(q.cursorBlink):X===25?W(!Y.isCursorHidden):X===45?W(M.reverseWraparound):X===66?W(M.applicationKeypad):X===67?4:X===1e3?W(P==="VT200"):X===1002?W(P==="DRAG"):X===1003?W(P==="ANY"):X===1004?W(M.sendFocus):X===1005?4:X===1006?W(U==="SGR"):X===1015?4:X===1016?W(U==="SGR_PIXELS"):X===1048?1:X===47||X===1047||X===1049?W(I===A):X===2004?W(M.bracketedPasteMode):0,Y.triggerDataEvent(`${f.C0.ESC}[${D?"":"?"}${Q};${re}$y`),!0;var Q,re}_updateAttrColor(R,D,M,P,U){return D===2?(R|=50331648,R&=-16777216,R|=_.AttributeData.fromColorRGB([M,P,U])):D===5&&(R&=-50331904,R|=33554432|255&M),R}_extractColor(R,D,M){const P=[0,0,-1,0,0,0];let U=0,Y=0;do{if(P[Y+U]=R.params[D+Y],R.hasSubParams(D+Y)){const H=R.getSubParams(D+Y);let J=0;do P[1]===5&&(U=1),P[Y+J+1+U]=H[J];while(++J=2||P[1]===2&&Y+U>=5)break;P[1]&&(U=1)}while(++Y+D5)&&(R=1),D.extended.underlineStyle=R,D.fg|=268435456,R===0&&(D.fg&=-268435457),D.updateExtended()}_processSGR0(R){R.fg=p.DEFAULT_ATTR_DATA.fg,R.bg=p.DEFAULT_ATTR_DATA.bg,R.extended=R.extended.clone(),R.extended.underlineStyle=0,R.extended.underlineColor&=-67108864,R.updateExtended()}charAttributes(R){if(R.length===1&&R.params[0]===0)return this._processSGR0(this._curAttrData),!0;const D=R.length;let M;const P=this._curAttrData;for(let U=0;U=30&&M<=37?(P.fg&=-50331904,P.fg|=16777216|M-30):M>=40&&M<=47?(P.bg&=-50331904,P.bg|=16777216|M-40):M>=90&&M<=97?(P.fg&=-50331904,P.fg|=16777224|M-90):M>=100&&M<=107?(P.bg&=-50331904,P.bg|=16777224|M-100):M===0?this._processSGR0(P):M===1?P.fg|=134217728:M===3?P.bg|=67108864:M===4?(P.fg|=268435456,this._processUnderline(R.hasSubParams(U)?R.getSubParams(U)[0]:1,P)):M===5?P.fg|=536870912:M===7?P.fg|=67108864:M===8?P.fg|=1073741824:M===9?P.fg|=2147483648:M===2?P.bg|=134217728:M===21?this._processUnderline(2,P):M===22?(P.fg&=-134217729,P.bg&=-134217729):M===23?P.bg&=-67108865:M===24?(P.fg&=-268435457,this._processUnderline(0,P)):M===25?P.fg&=-536870913:M===27?P.fg&=-67108865:M===28?P.fg&=-1073741825:M===29?P.fg&=2147483647:M===39?(P.fg&=-67108864,P.fg|=16777215&p.DEFAULT_ATTR_DATA.fg):M===49?(P.bg&=-67108864,P.bg|=16777215&p.DEFAULT_ATTR_DATA.bg):M===38||M===48||M===58?U+=this._extractColor(R,U,P):M===53?P.bg|=1073741824:M===55?P.bg&=-1073741825:M===59?(P.extended=P.extended.clone(),P.extended.underlineColor=-1,P.updateExtended()):M===100?(P.fg&=-67108864,P.fg|=16777215&p.DEFAULT_ATTR_DATA.fg,P.bg&=-67108864,P.bg|=16777215&p.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",M);return!0}deviceStatus(R){switch(R.params[0]){case 5:this._coreService.triggerDataEvent(`${f.C0.ESC}[0n`);break;case 6:const D=this._activeBuffer.y+1,M=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${f.C0.ESC}[${D};${M}R`)}return!0}deviceStatusPrivate(R){if(R.params[0]===6){const D=this._activeBuffer.y+1,M=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${f.C0.ESC}[?${D};${M}R`)}return!0}softReset(R){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=p.DEFAULT_ATTR_DATA.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(R){const D=R.params[0]||1;switch(D){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const M=D%2==1;return this._optionsService.options.cursorBlink=M,!0}setScrollRegion(R){const D=R.params[0]||1;let M;return(R.length<2||(M=R.params[1])>this._bufferService.rows||M===0)&&(M=this._bufferService.rows),M>D&&(this._activeBuffer.scrollTop=D-1,this._activeBuffer.scrollBottom=M-1,this._setCursor(0,0)),!0}windowOptions(R){if(!T(R.params[0],this._optionsService.rawOptions.windowOptions))return!0;const D=R.length>1?R.params[1]:0;switch(R.params[0]){case 14:D!==2&&this._onRequestWindowsOptionsReport.fire(O.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(O.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${f.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:D!==0&&D!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),D!==0&&D!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:D!==0&&D!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),D!==0&&D!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(R){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(R){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(R){return this._windowTitle=R,this._onTitleChange.fire(R),!0}setIconName(R){return this._iconName=R,!0}setOrReportIndexedColor(R){const D=[],M=R.split(";");for(;M.length>1;){const P=M.shift(),U=M.shift();if(/^\d+$/.exec(P)){const Y=parseInt(P);if(K(Y))if(U==="?")D.push({type:0,index:Y});else{const H=(0,N.parseColor)(U);H&&D.push({type:1,index:Y,color:H})}}}return D.length&&this._onColor.fire(D),!0}setHyperlink(R){const D=R.split(";");return!(D.length<2)&&(D[1]?this._createHyperlink(D[0],D[1]):!D[0]&&this._finishHyperlink())}_createHyperlink(R,D){this._getCurrentLinkId()&&this._finishHyperlink();const M=R.split(":");let P;const U=M.findIndex(Y=>Y.startsWith("id="));return U!==-1&&(P=M[U].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:P,uri:D}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(R,D){const M=R.split(";");for(let P=0;P=this._specialColors.length);++P,++D)if(M[P]==="?")this._onColor.fire([{type:0,index:this._specialColors[D]}]);else{const U=(0,N.parseColor)(M[P]);U&&this._onColor.fire([{type:1,index:this._specialColors[D],color:U}])}return!0}setOrReportFgColor(R){return this._setOrReportSpecialColor(R,0)}setOrReportBgColor(R){return this._setOrReportSpecialColor(R,1)}setOrReportCursorColor(R){return this._setOrReportSpecialColor(R,2)}restoreIndexedColor(R){if(!R)return this._onColor.fire([{type:2}]),!0;const D=[],M=R.split(";");for(let P=0;P=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){const R=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,R,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=p.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=p.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(R){return this._charsetService.setgLevel(R),!0}screenAlignmentPattern(){const R=new l.CellData;R.content=4194373,R.fg=this._curAttrData.fg,R.bg=this._curAttrData.bg,this._setCursor(0,0);for(let D=0;D(this._coreService.triggerDataEvent(`${f.C0.ESC}${U}${f.C0.ESC}\\`),!0))(R==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:R==='"p'?'P1$r61;1"p':R==="r"?`P1$r${M.scrollTop+1};${M.scrollBottom+1}r`:R==="m"?"P1$r0m":R===" q"?`P1$r${{block:2,underline:4,bar:6}[P.cursorStyle]-(P.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(R,D){this._dirtyRowTracker.markRangeDirty(R,D)}}o.InputHandler=F;let z=class{constructor($){this._bufferService=$,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty($){$this.end&&(this.end=$)}markRangeDirty($,R){$>R&&(B=$,$=R,R=B),$this.end&&(this.end=R)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function K($){return 0<=$&&$<256}z=d([m(0,j.IBufferService)],z)},844:(y,o)=>{function u(d){for(const m of d)m.dispose();d.length=0}Object.defineProperty(o,"__esModule",{value:!0}),o.getDisposeArrayDisposable=o.disposeArray=o.toDisposable=o.MutableDisposable=o.Disposable=void 0,o.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const d of this._disposables)d.dispose();this._disposables.length=0}register(d){return this._disposables.push(d),d}unregister(d){const m=this._disposables.indexOf(d);m!==-1&&this._disposables.splice(m,1)}},o.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(d){var m;this._isDisposed||d===this._value||((m=this._value)==null||m.dispose(),this._value=d)}clear(){this.value=void 0}dispose(){var d;this._isDisposed=!0,(d=this._value)==null||d.dispose(),this._value=void 0}},o.toDisposable=function(d){return{dispose:d}},o.disposeArray=u,o.getDisposeArrayDisposable=function(d){return{dispose:()=>u(d)}}},1505:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.FourKeyMap=o.TwoKeyMap=void 0;class u{constructor(){this._data={}}set(m,f,g){this._data[m]||(this._data[m]={}),this._data[m][f]=g}get(m,f){return this._data[m]?this._data[m][f]:void 0}clear(){this._data={}}}o.TwoKeyMap=u,o.FourKeyMap=class{constructor(){this._data=new u}set(d,m,f,g,w){this._data.get(d,m)||this._data.set(d,m,new u),this._data.get(d,m).set(f,g,w)}get(d,m,f,g){var w;return(w=this._data.get(d,m))==null?void 0:w.get(f,g)}clear(){this._data.clear()}}},6114:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.isChromeOS=o.isLinux=o.isWindows=o.isIphone=o.isIpad=o.isMac=o.getSafariVersion=o.isSafari=o.isLegacyEdge=o.isFirefox=o.isNode=void 0,o.isNode=typeof process<"u"&&"title"in process;const u=o.isNode?"node":navigator.userAgent,d=o.isNode?"node":navigator.platform;o.isFirefox=u.includes("Firefox"),o.isLegacyEdge=u.includes("Edge"),o.isSafari=/^((?!chrome|android).)*safari/i.test(u),o.getSafariVersion=function(){if(!o.isSafari)return 0;const m=u.match(/Version\/(\d+)/);return m===null||m.length<2?0:parseInt(m[1])},o.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(d),o.isIpad=d==="iPad",o.isIphone=d==="iPhone",o.isWindows=["Windows","Win16","Win32","WinCE"].includes(d),o.isLinux=d.indexOf("Linux")>=0,o.isChromeOS=/\bCrOS\b/.test(u)},6106:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SortedList=void 0;let u=0;o.SortedList=class{constructor(d){this._getKey=d,this._array=[]}clear(){this._array.length=0}insert(d){this._array.length!==0?(u=this._search(this._getKey(d)),this._array.splice(u,0,d)):this._array.push(d)}delete(d){if(this._array.length===0)return!1;const m=this._getKey(d);if(m===void 0||(u=this._search(m),u===-1)||this._getKey(this._array[u])!==m)return!1;do if(this._array[u]===d)return this._array.splice(u,1),!0;while(++u=this._array.length)&&this._getKey(this._array[u])===d))do yield this._array[u];while(++u=this._array.length)&&this._getKey(this._array[u])===d))do m(this._array[u]);while(++u=m;){let g=m+f>>1;const w=this._getKey(this._array[g]);if(w>d)f=g-1;else{if(!(w0&&this._getKey(this._array[g-1])===d;)g--;return g}m=g+1}}return m}}},7226:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DebouncedIdleTask=o.IdleTaskQueue=o.PriorityTaskQueue=void 0;const d=u(6114);class m{constructor(){this._tasks=[],this._i=0}enqueue(w){this._tasks.push(w),this._start()}flush(){for(;this._ic)return p-S<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(p-S))}ms`),void this._start();p=c}this.clear()}}class f extends m{_requestCallback(w){return setTimeout(()=>w(this._createDeadline(16)))}_cancelCallback(w){clearTimeout(w)}_createDeadline(w){const S=Date.now()+w;return{timeRemaining:()=>Math.max(0,S-Date.now())}}}o.PriorityTaskQueue=f,o.IdleTaskQueue=!d.isNode&&"requestIdleCallback"in window?class extends m{_requestCallback(g){return requestIdleCallback(g)}_cancelCallback(g){cancelIdleCallback(g)}}:f,o.DebouncedIdleTask=class{constructor(){this._queue=new o.IdleTaskQueue}set(g){this._queue.clear(),this._queue.enqueue(g)}flush(){this._queue.flush()}}},9282:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.updateWindowsModeWrappedState=void 0;const d=u(643);o.updateWindowsModeWrappedState=function(m){const f=m.buffer.lines.get(m.buffer.ybase+m.buffer.y-1),g=f==null?void 0:f.get(m.cols-1),w=m.buffer.lines.get(m.buffer.ybase+m.buffer.y);w&&g&&(w.isWrapped=g[d.CHAR_DATA_CODE_INDEX]!==d.NULL_CELL_CODE&&g[d.CHAR_DATA_CODE_INDEX]!==d.WHITESPACE_CELL_CODE)}},3734:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ExtendedAttrs=o.AttributeData=void 0;class u{constructor(){this.fg=0,this.bg=0,this.extended=new d}static toColorRGB(f){return[f>>>16&255,f>>>8&255,255&f]}static fromColorRGB(f){return(255&f[0])<<16|(255&f[1])<<8|255&f[2]}clone(){const f=new u;return f.fg=this.fg,f.bg=this.bg,f.extended=this.extended.clone(),f}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}o.AttributeData=u;class d{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(f){this._ext=f}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(f){this._ext&=-469762049,this._ext|=f<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(f){this._ext&=-67108864,this._ext|=67108863&f}get urlId(){return this._urlId}set urlId(f){this._urlId=f}get underlineVariantOffset(){const f=(3758096384&this._ext)>>29;return f<0?4294967288^f:f}set underlineVariantOffset(f){this._ext&=536870911,this._ext|=f<<29&3758096384}constructor(f=0,g=0){this._ext=0,this._urlId=0,this._ext=f,this._urlId=g}clone(){return new d(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}o.ExtendedAttrs=d},9092:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Buffer=o.MAX_BUFFER_SIZE=void 0;const d=u(6349),m=u(7226),f=u(3734),g=u(8437),w=u(4634),S=u(511),v=u(643),p=u(4863),c=u(7116);o.MAX_BUFFER_SIZE=4294967295,o.Buffer=class{constructor(a,l,_){this._hasScrollback=a,this._optionsService=l,this._bufferService=_,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=g.DEFAULT_ATTR_DATA.clone(),this.savedCharset=c.DEFAULT_CHARSET,this.markers=[],this._nullCell=S.CellData.fromCharData([0,v.NULL_CELL_CHAR,v.NULL_CELL_WIDTH,v.NULL_CELL_CODE]),this._whitespaceCell=S.CellData.fromCharData([0,v.WHITESPACE_CELL_CHAR,v.WHITESPACE_CELL_WIDTH,v.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new m.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new d.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(a){return a?(this._nullCell.fg=a.fg,this._nullCell.bg=a.bg,this._nullCell.extended=a.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new f.ExtendedAttrs),this._nullCell}getWhitespaceCell(a){return a?(this._whitespaceCell.fg=a.fg,this._whitespaceCell.bg=a.bg,this._whitespaceCell.extended=a.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new f.ExtendedAttrs),this._whitespaceCell}getBlankLine(a,l){return new g.BufferLine(this._bufferService.cols,this.getNullCell(a),l)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const a=this.ybase+this.y-this.ydisp;return a>=0&&ao.MAX_BUFFER_SIZE?o.MAX_BUFFER_SIZE:l}fillViewportRows(a){if(this.lines.length===0){a===void 0&&(a=g.DEFAULT_ATTR_DATA);let l=this._rows;for(;l--;)this.lines.push(this.getBlankLine(a))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new d.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(a,l){const _=this.getNullCell(g.DEFAULT_ATTR_DATA);let j=0;const b=this._getCorrectBufferLength(l);if(b>this.lines.maxLength&&(this.lines.maxLength=b),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new g.BufferLine(a,_)));else for(let x=this._rows;x>l;x--)this.lines.length>l+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(b0&&(this.lines.trimStart(x),this.ybase=Math.max(this.ybase-x,0),this.ydisp=Math.max(this.ydisp-x,0),this.savedY=Math.max(this.savedY-x,0)),this.lines.maxLength=b}this.x=Math.min(this.x,a-1),this.y=Math.min(this.y,l-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,a-1),this.scrollTop=0}if(this.scrollBottom=l-1,this._isReflowEnabled&&(this._reflow(a,l),this._cols>a))for(let k=0;k.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let a=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,a=!1);let l=0;for(;this._memoryCleanupPosition100)return!0;return a}get _isReflowEnabled(){const a=this._optionsService.rawOptions.windowsPty;return a&&a.buildNumber?this._hasScrollback&&a.backend==="conpty"&&a.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(a,l){this._cols!==a&&(a>this._cols?this._reflowLarger(a,l):this._reflowSmaller(a,l))}_reflowLarger(a,l){const _=(0,w.reflowLargerGetLinesToRemove)(this.lines,this._cols,a,this.ybase+this.y,this.getNullCell(g.DEFAULT_ATTR_DATA));if(_.length>0){const j=(0,w.reflowLargerCreateNewLayout)(this.lines,_);(0,w.reflowLargerApplyNewLayout)(this.lines,j.layout),this._reflowLargerAdjustViewport(a,l,j.countRemoved)}}_reflowLargerAdjustViewport(a,l,_){const j=this.getNullCell(g.DEFAULT_ATTR_DATA);let b=_;for(;b-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;k--){let x=this.lines.get(k);if(!x||!x.isWrapped&&x.getTrimmedLength()<=a)continue;const N=[x];for(;x.isWrapped&&k>0;)x=this.lines.get(--k),N.unshift(x);const E=this.ybase+this.y;if(E>=k&&E0&&(j.push({start:k+N.length+b,newLines:F}),b+=F.length),N.push(...F);let z=T.length-1,K=T[z];K===0&&(z--,K=T[z]);let $=N.length-O-1,R=L;for(;$>=0;){const M=Math.min(R,K);if(N[z]===void 0)break;if(N[z].copyCellsFrom(N[$],R-M,K-M,M,!0),K-=M,K===0&&(z--,K=T[z]),R-=M,R===0){$--;const P=Math.max($,0);R=(0,w.getWrappedLineTrimmedLength)(N,P,this._cols)}}for(let M=0;M0;)this.ybase===0?this.y0){const k=[],x=[];for(let z=0;z=0;z--)if(T&&T.start>E+O){for(let K=T.newLines.length-1;K>=0;K--)this.lines.set(z--,T.newLines[K]);z++,k.push({index:E+1,amount:T.newLines.length}),O+=T.newLines.length,T=j[++L]}else this.lines.set(z,x[E--]);let B=0;for(let z=k.length-1;z>=0;z--)k[z].index+=B,this.lines.onInsertEmitter.fire(k[z]),B+=k[z].amount;const F=Math.max(0,N+b-this.lines.maxLength);F>0&&this.lines.onTrimEmitter.fire(F)}}translateBufferLineToString(a,l,_=0,j){const b=this.lines.get(a);return b?b.translateToString(l,_,j):""}getWrappedRangeForLine(a){let l=a,_=a;for(;l>0&&this.lines.get(l).isWrapped;)l--;for(;_+10;);return a>=this._cols?this._cols-1:a<0?0:a}nextStop(a){for(a==null&&(a=this.x);!this.tabs[++a]&&a=this._cols?this._cols-1:a<0?0:a}clearMarkers(a){this._isClearing=!0;for(let l=0;l{l.line-=_,l.line<0&&l.dispose()})),l.register(this.lines.onInsert(_=>{l.line>=_.index&&(l.line+=_.amount)})),l.register(this.lines.onDelete(_=>{l.line>=_.index&&l.line<_.index+_.amount&&l.dispose(),l.line>_.index&&(l.line-=_.amount)})),l.register(l.onDispose(()=>this._removeMarker(l))),l}_removeMarker(a){this._isClearing||this.markers.splice(this.markers.indexOf(a),1)}}},8437:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLine=o.DEFAULT_ATTR_DATA=void 0;const d=u(3734),m=u(511),f=u(643),g=u(482);o.DEFAULT_ATTR_DATA=Object.freeze(new d.AttributeData);let w=0;class S{constructor(p,c,a=!1){this.isWrapped=a,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*p);const l=c||m.CellData.fromCharData([0,f.NULL_CELL_CHAR,f.NULL_CELL_WIDTH,f.NULL_CELL_CODE]);for(let _=0;_>22,2097152&c?this._combined[p].charCodeAt(this._combined[p].length-1):a]}set(p,c){this._data[3*p+1]=c[f.CHAR_DATA_ATTR_INDEX],c[f.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[p]=c[1],this._data[3*p+0]=2097152|p|c[f.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*p+0]=c[f.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|c[f.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(p){return this._data[3*p+0]>>22}hasWidth(p){return 12582912&this._data[3*p+0]}getFg(p){return this._data[3*p+1]}getBg(p){return this._data[3*p+2]}hasContent(p){return 4194303&this._data[3*p+0]}getCodePoint(p){const c=this._data[3*p+0];return 2097152&c?this._combined[p].charCodeAt(this._combined[p].length-1):2097151&c}isCombined(p){return 2097152&this._data[3*p+0]}getString(p){const c=this._data[3*p+0];return 2097152&c?this._combined[p]:2097151&c?(0,g.stringFromCodePoint)(2097151&c):""}isProtected(p){return 536870912&this._data[3*p+2]}loadCell(p,c){return w=3*p,c.content=this._data[w+0],c.fg=this._data[w+1],c.bg=this._data[w+2],2097152&c.content&&(c.combinedData=this._combined[p]),268435456&c.bg&&(c.extended=this._extendedAttrs[p]),c}setCell(p,c){2097152&c.content&&(this._combined[p]=c.combinedData),268435456&c.bg&&(this._extendedAttrs[p]=c.extended),this._data[3*p+0]=c.content,this._data[3*p+1]=c.fg,this._data[3*p+2]=c.bg}setCellFromCodepoint(p,c,a,l){268435456&l.bg&&(this._extendedAttrs[p]=l.extended),this._data[3*p+0]=c|a<<22,this._data[3*p+1]=l.fg,this._data[3*p+2]=l.bg}addCodepointToCell(p,c,a){let l=this._data[3*p+0];2097152&l?this._combined[p]+=(0,g.stringFromCodePoint)(c):2097151&l?(this._combined[p]=(0,g.stringFromCodePoint)(2097151&l)+(0,g.stringFromCodePoint)(c),l&=-2097152,l|=2097152):l=c|4194304,a&&(l&=-12582913,l|=a<<22),this._data[3*p+0]=l}insertCells(p,c,a){if((p%=this.length)&&this.getWidth(p-1)===2&&this.setCellFromCodepoint(p-1,0,1,a),c=0;--_)this.setCell(p+c+_,this.loadCell(p+_,l));for(let _=0;_this.length){if(this._data.buffer.byteLength>=4*a)this._data=new Uint32Array(this._data.buffer,0,a);else{const l=new Uint32Array(a);l.set(this._data),this._data=l}for(let l=this.length;l=p&&delete this._combined[b]}const _=Object.keys(this._extendedAttrs);for(let j=0;j<_.length;j++){const b=parseInt(_[j],10);b>=p&&delete this._extendedAttrs[b]}}return this.length=p,4*a*2=0;--p)if(4194303&this._data[3*p+0])return p+(this._data[3*p+0]>>22);return 0}getNoBgTrimmedLength(){for(let p=this.length-1;p>=0;--p)if(4194303&this._data[3*p+0]||50331648&this._data[3*p+2])return p+(this._data[3*p+0]>>22);return 0}copyCellsFrom(p,c,a,l,_){const j=p._data;if(_)for(let k=l-1;k>=0;k--){for(let x=0;x<3;x++)this._data[3*(a+k)+x]=j[3*(c+k)+x];268435456&j[3*(c+k)+2]&&(this._extendedAttrs[a+k]=p._extendedAttrs[c+k])}else for(let k=0;k=c&&(this._combined[x-c+a]=p._combined[x])}}translateToString(p,c,a,l){c=c??0,a=a??this.length,p&&(a=Math.min(a,this.getTrimmedLength())),l&&(l.length=0);let _="";for(;c>22||1}return l&&l.push(c),_}}o.BufferLine=S},4841:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.getRangeLength=void 0,o.getRangeLength=function(u,d){if(u.start.y>u.end.y)throw new Error(`Buffer range end (${u.end.x}, ${u.end.y}) cannot be before start (${u.start.x}, ${u.start.y})`);return d*(u.end.y-u.start.y)+(u.end.x-u.start.x+1)}},4634:(y,o)=>{function u(d,m,f){if(m===d.length-1)return d[m].getTrimmedLength();const g=!d[m].hasContent(f-1)&&d[m].getWidth(f-1)===1,w=d[m+1].getWidth(0)===2;return g&&w?f-1:f}Object.defineProperty(o,"__esModule",{value:!0}),o.getWrappedLineTrimmedLength=o.reflowSmallerGetNewLineLengths=o.reflowLargerApplyNewLayout=o.reflowLargerCreateNewLayout=o.reflowLargerGetLinesToRemove=void 0,o.reflowLargerGetLinesToRemove=function(d,m,f,g,w){const S=[];for(let v=0;v=v&&g0&&(x>l||a[x].getTrimmedLength()===0);x--)k++;k>0&&(S.push(v+a.length-k),S.push(k)),v+=a.length-1}return S},o.reflowLargerCreateNewLayout=function(d,m){const f=[];let g=0,w=m[g],S=0;for(let v=0;vu(d,a,m)).reduce((c,a)=>c+a);let S=0,v=0,p=0;for(;pc&&(S-=c,v++);const a=d[v].getWidth(S-1)===2;a&&S--;const l=a?f-1:f;g.push(l),p+=l}return g},o.getWrappedLineTrimmedLength=u},5295:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferSet=void 0;const d=u(8460),m=u(844),f=u(9092);class g extends m.Disposable{constructor(S,v){super(),this._optionsService=S,this._bufferService=v,this._onBufferActivate=this.register(new d.EventEmitter),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 f.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new f.Buffer(!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(S){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(S),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(S,v){this._normal.resize(S,v),this._alt.resize(S,v),this.setupTabStops(S)}setupTabStops(S){this._normal.setupTabStops(S),this._alt.setupTabStops(S)}}o.BufferSet=g},511:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CellData=void 0;const d=u(482),m=u(643),f=u(3734);class g extends f.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new f.ExtendedAttrs,this.combinedData=""}static fromCharData(S){const v=new g;return v.setFromCharData(S),v}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,d.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(S){this.fg=S[m.CHAR_DATA_ATTR_INDEX],this.bg=0;let v=!1;if(S[m.CHAR_DATA_CHAR_INDEX].length>2)v=!0;else if(S[m.CHAR_DATA_CHAR_INDEX].length===2){const p=S[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=p&&p<=56319){const c=S[m.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=c&&c<=57343?this.content=1024*(p-55296)+c-56320+65536|S[m.CHAR_DATA_WIDTH_INDEX]<<22:v=!0}else v=!0}else this.content=S[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|S[m.CHAR_DATA_WIDTH_INDEX]<<22;v&&(this.combinedData=S[m.CHAR_DATA_CHAR_INDEX],this.content=2097152|S[m.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.CellData=g},643:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WHITESPACE_CELL_CODE=o.WHITESPACE_CELL_WIDTH=o.WHITESPACE_CELL_CHAR=o.NULL_CELL_CODE=o.NULL_CELL_WIDTH=o.NULL_CELL_CHAR=o.CHAR_DATA_CODE_INDEX=o.CHAR_DATA_WIDTH_INDEX=o.CHAR_DATA_CHAR_INDEX=o.CHAR_DATA_ATTR_INDEX=o.DEFAULT_EXT=o.DEFAULT_ATTR=o.DEFAULT_COLOR=void 0,o.DEFAULT_COLOR=0,o.DEFAULT_ATTR=256|o.DEFAULT_COLOR<<9,o.DEFAULT_EXT=0,o.CHAR_DATA_ATTR_INDEX=0,o.CHAR_DATA_CHAR_INDEX=1,o.CHAR_DATA_WIDTH_INDEX=2,o.CHAR_DATA_CODE_INDEX=3,o.NULL_CELL_CHAR="",o.NULL_CELL_WIDTH=1,o.NULL_CELL_CODE=0,o.WHITESPACE_CELL_CHAR=" ",o.WHITESPACE_CELL_WIDTH=1,o.WHITESPACE_CELL_CODE=32},4863:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Marker=void 0;const d=u(8460),m=u(844);class f{get id(){return this._id}constructor(w){this.line=w,this.isDisposed=!1,this._disposables=[],this._id=f._nextId++,this._onDispose=this.register(new d.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,m.disposeArray)(this._disposables),this._disposables.length=0)}register(w){return this._disposables.push(w),w}}o.Marker=f,f._nextId=1},7116:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DEFAULT_CHARSET=o.CHARSETS=void 0,o.CHARSETS={},o.DEFAULT_CHARSET=o.CHARSETS.B,o.CHARSETS[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:"≥","{":"π","|":"≠","}":"£","~":"·"},o.CHARSETS.A={"#":"£"},o.CHARSETS.B=void 0,o.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},o.CHARSETS.C=o.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},o.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},o.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},o.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},o.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},o.CHARSETS.E=o.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},o.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},o.CHARSETS.H=o.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},o.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(y,o)=>{var u,d,m;Object.defineProperty(o,"__esModule",{value:!0}),o.C1_ESCAPED=o.C1=o.C0=void 0,function(f){f.NUL="\0",f.SOH="",f.STX="",f.ETX="",f.EOT="",f.ENQ="",f.ACK="",f.BEL="\x07",f.BS="\b",f.HT=" ",f.LF=` -`,f.VT="\v",f.FF="\f",f.CR="\r",f.SO="",f.SI="",f.DLE="",f.DC1="",f.DC2="",f.DC3="",f.DC4="",f.NAK="",f.SYN="",f.ETB="",f.CAN="",f.EM="",f.SUB="",f.ESC="\x1B",f.FS="",f.GS="",f.RS="",f.US="",f.SP=" ",f.DEL=""}(u||(o.C0=u={})),function(f){f.PAD="€",f.HOP="",f.BPH="‚",f.NBH="ƒ",f.IND="„",f.NEL="…",f.SSA="†",f.ESA="‡",f.HTS="ˆ",f.HTJ="‰",f.VTS="Š",f.PLD="‹",f.PLU="Œ",f.RI="",f.SS2="Ž",f.SS3="",f.DCS="",f.PU1="‘",f.PU2="’",f.STS="“",f.CCH="”",f.MW="•",f.SPA="–",f.EPA="—",f.SOS="˜",f.SGCI="™",f.SCI="š",f.CSI="›",f.ST="œ",f.OSC="",f.PM="ž",f.APC="Ÿ"}(d||(o.C1=d={})),function(f){f.ST=`${u.ESC}\\`}(m||(o.C1_ESCAPED=m={}))},7399:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.evaluateKeyboardEvent=void 0;const d=u(2584),m={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:["'",'"']};o.evaluateKeyboardEvent=function(f,g,w,S){const v={type:0,cancel:!1,key:void 0},p=(f.shiftKey?1:0)|(f.altKey?2:0)|(f.ctrlKey?4:0)|(f.metaKey?8:0);switch(f.keyCode){case 0:f.key==="UIKeyInputUpArrow"?v.key=g?d.C0.ESC+"OA":d.C0.ESC+"[A":f.key==="UIKeyInputLeftArrow"?v.key=g?d.C0.ESC+"OD":d.C0.ESC+"[D":f.key==="UIKeyInputRightArrow"?v.key=g?d.C0.ESC+"OC":d.C0.ESC+"[C":f.key==="UIKeyInputDownArrow"&&(v.key=g?d.C0.ESC+"OB":d.C0.ESC+"[B");break;case 8:v.key=f.ctrlKey?"\b":d.C0.DEL,f.altKey&&(v.key=d.C0.ESC+v.key);break;case 9:if(f.shiftKey){v.key=d.C0.ESC+"[Z";break}v.key=d.C0.HT,v.cancel=!0;break;case 13:v.key=f.altKey?d.C0.ESC+d.C0.CR:d.C0.CR,v.cancel=!0;break;case 27:v.key=d.C0.ESC,f.altKey&&(v.key=d.C0.ESC+d.C0.ESC),v.cancel=!0;break;case 37:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"D",v.key===d.C0.ESC+"[1;3D"&&(v.key=d.C0.ESC+(w?"b":"[1;5D"))):v.key=g?d.C0.ESC+"OD":d.C0.ESC+"[D";break;case 39:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"C",v.key===d.C0.ESC+"[1;3C"&&(v.key=d.C0.ESC+(w?"f":"[1;5C"))):v.key=g?d.C0.ESC+"OC":d.C0.ESC+"[C";break;case 38:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"A",w||v.key!==d.C0.ESC+"[1;3A"||(v.key=d.C0.ESC+"[1;5A")):v.key=g?d.C0.ESC+"OA":d.C0.ESC+"[A";break;case 40:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"B",w||v.key!==d.C0.ESC+"[1;3B"||(v.key=d.C0.ESC+"[1;5B")):v.key=g?d.C0.ESC+"OB":d.C0.ESC+"[B";break;case 45:f.shiftKey||f.ctrlKey||(v.key=d.C0.ESC+"[2~");break;case 46:v.key=p?d.C0.ESC+"[3;"+(p+1)+"~":d.C0.ESC+"[3~";break;case 36:v.key=p?d.C0.ESC+"[1;"+(p+1)+"H":g?d.C0.ESC+"OH":d.C0.ESC+"[H";break;case 35:v.key=p?d.C0.ESC+"[1;"+(p+1)+"F":g?d.C0.ESC+"OF":d.C0.ESC+"[F";break;case 33:f.shiftKey?v.type=2:f.ctrlKey?v.key=d.C0.ESC+"[5;"+(p+1)+"~":v.key=d.C0.ESC+"[5~";break;case 34:f.shiftKey?v.type=3:f.ctrlKey?v.key=d.C0.ESC+"[6;"+(p+1)+"~":v.key=d.C0.ESC+"[6~";break;case 112:v.key=p?d.C0.ESC+"[1;"+(p+1)+"P":d.C0.ESC+"OP";break;case 113:v.key=p?d.C0.ESC+"[1;"+(p+1)+"Q":d.C0.ESC+"OQ";break;case 114:v.key=p?d.C0.ESC+"[1;"+(p+1)+"R":d.C0.ESC+"OR";break;case 115:v.key=p?d.C0.ESC+"[1;"+(p+1)+"S":d.C0.ESC+"OS";break;case 116:v.key=p?d.C0.ESC+"[15;"+(p+1)+"~":d.C0.ESC+"[15~";break;case 117:v.key=p?d.C0.ESC+"[17;"+(p+1)+"~":d.C0.ESC+"[17~";break;case 118:v.key=p?d.C0.ESC+"[18;"+(p+1)+"~":d.C0.ESC+"[18~";break;case 119:v.key=p?d.C0.ESC+"[19;"+(p+1)+"~":d.C0.ESC+"[19~";break;case 120:v.key=p?d.C0.ESC+"[20;"+(p+1)+"~":d.C0.ESC+"[20~";break;case 121:v.key=p?d.C0.ESC+"[21;"+(p+1)+"~":d.C0.ESC+"[21~";break;case 122:v.key=p?d.C0.ESC+"[23;"+(p+1)+"~":d.C0.ESC+"[23~";break;case 123:v.key=p?d.C0.ESC+"[24;"+(p+1)+"~":d.C0.ESC+"[24~";break;default:if(!f.ctrlKey||f.shiftKey||f.altKey||f.metaKey)if(w&&!S||!f.altKey||f.metaKey)!w||f.altKey||f.ctrlKey||f.shiftKey||!f.metaKey?f.key&&!f.ctrlKey&&!f.altKey&&!f.metaKey&&f.keyCode>=48&&f.key.length===1?v.key=f.key:f.key&&f.ctrlKey&&(f.key==="_"&&(v.key=d.C0.US),f.key==="@"&&(v.key=d.C0.NUL)):f.keyCode===65&&(v.type=1);else{const c=m[f.keyCode],a=c==null?void 0:c[f.shiftKey?1:0];if(a)v.key=d.C0.ESC+a;else if(f.keyCode>=65&&f.keyCode<=90){const l=f.ctrlKey?f.keyCode-64:f.keyCode+32;let _=String.fromCharCode(l);f.shiftKey&&(_=_.toUpperCase()),v.key=d.C0.ESC+_}else if(f.keyCode===32)v.key=d.C0.ESC+(f.ctrlKey?d.C0.NUL:" ");else if(f.key==="Dead"&&f.code.startsWith("Key")){let l=f.code.slice(3,4);f.shiftKey||(l=l.toLowerCase()),v.key=d.C0.ESC+l,v.cancel=!0}}else f.keyCode>=65&&f.keyCode<=90?v.key=String.fromCharCode(f.keyCode-64):f.keyCode===32?v.key=d.C0.NUL:f.keyCode>=51&&f.keyCode<=55?v.key=String.fromCharCode(f.keyCode-51+27):f.keyCode===56?v.key=d.C0.DEL:f.keyCode===219?v.key=d.C0.ESC:f.keyCode===220?v.key=d.C0.FS:f.keyCode===221&&(v.key=d.C0.GS)}return v}},482:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Utf8ToUtf32=o.StringToUtf32=o.utf32ToString=o.stringFromCodePoint=void 0,o.stringFromCodePoint=function(u){return u>65535?(u-=65536,String.fromCharCode(55296+(u>>10))+String.fromCharCode(u%1024+56320)):String.fromCharCode(u)},o.utf32ToString=function(u,d=0,m=u.length){let f="";for(let g=d;g65535?(w-=65536,f+=String.fromCharCode(55296+(w>>10))+String.fromCharCode(w%1024+56320)):f+=String.fromCharCode(w)}return f},o.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(u,d){const m=u.length;if(!m)return 0;let f=0,g=0;if(this._interim){const w=u.charCodeAt(g++);56320<=w&&w<=57343?d[f++]=1024*(this._interim-55296)+w-56320+65536:(d[f++]=this._interim,d[f++]=w),this._interim=0}for(let w=g;w=m)return this._interim=S,f;const v=u.charCodeAt(w);56320<=v&&v<=57343?d[f++]=1024*(S-55296)+v-56320+65536:(d[f++]=S,d[f++]=v)}else S!==65279&&(d[f++]=S)}return f}},o.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(u,d){const m=u.length;if(!m)return 0;let f,g,w,S,v=0,p=0,c=0;if(this.interim[0]){let _=!1,j=this.interim[0];j&=(224&j)==192?31:(240&j)==224?15:7;let b,k=0;for(;(b=63&this.interim[++k])&&k<4;)j<<=6,j|=b;const x=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,N=x-k;for(;c=m)return 0;if(b=u[c++],(192&b)!=128){c--,_=!0;break}this.interim[k++]=b,j<<=6,j|=63&b}_||(x===2?j<128?c--:d[v++]=j:x===3?j<2048||j>=55296&&j<=57343||j===65279||(d[v++]=j):j<65536||j>1114111||(d[v++]=j)),this.interim.fill(0)}const a=m-4;let l=c;for(;l=m)return this.interim[0]=f,v;if(g=u[l++],(192&g)!=128){l--;continue}if(p=(31&f)<<6|63&g,p<128){l--;continue}d[v++]=p}else if((240&f)==224){if(l>=m)return this.interim[0]=f,v;if(g=u[l++],(192&g)!=128){l--;continue}if(l>=m)return this.interim[0]=f,this.interim[1]=g,v;if(w=u[l++],(192&w)!=128){l--;continue}if(p=(15&f)<<12|(63&g)<<6|63&w,p<2048||p>=55296&&p<=57343||p===65279)continue;d[v++]=p}else if((248&f)==240){if(l>=m)return this.interim[0]=f,v;if(g=u[l++],(192&g)!=128){l--;continue}if(l>=m)return this.interim[0]=f,this.interim[1]=g,v;if(w=u[l++],(192&w)!=128){l--;continue}if(l>=m)return this.interim[0]=f,this.interim[1]=g,this.interim[2]=w,v;if(S=u[l++],(192&S)!=128){l--;continue}if(p=(7&f)<<18|(63&g)<<12|(63&w)<<6|63&S,p<65536||p>1114111)continue;d[v++]=p}}return v}}},225:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeV6=void 0;const d=u(1480),m=[[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]],f=[[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]];let g;o.UnicodeV6=class{constructor(){if(this.version="6",!g){g=new Uint8Array(65536),g.fill(1),g[0]=0,g.fill(0,1,32),g.fill(0,127,160),g.fill(2,4352,4448),g[9001]=2,g[9002]=2,g.fill(2,11904,42192),g[12351]=1,g.fill(2,44032,55204),g.fill(2,63744,64256),g.fill(2,65040,65050),g.fill(2,65072,65136),g.fill(2,65280,65377),g.fill(2,65504,65511);for(let w=0;wv[a][1])return!1;for(;a>=c;)if(p=c+a>>1,S>v[p][1])c=p+1;else{if(!(S=131072&&w<=196605||w>=196608&&w<=262141?2:1}charProperties(w,S){let v=this.wcwidth(w),p=v===0&&S!==0;if(p){const c=d.UnicodeService.extractWidth(S);c===0?p=!1:c>v&&(v=c)}return d.UnicodeService.createPropertyValue(0,v,p)}}},5981:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WriteBuffer=void 0;const d=u(8460),m=u(844);class f extends m.Disposable{constructor(w){super(),this._action=w,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new d.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(w,S){if(S!==void 0&&this._syncCalls>S)return void(this._syncCalls=0);if(this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let v;for(this._isSyncWriting=!0;v=this._writeBuffer.shift();){this._action(v);const p=this._callbacks.shift();p&&p()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(w,S){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(S),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(S)}_innerWrite(w=0,S=!0){const v=w||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const p=this._writeBuffer[this._bufferOffset],c=this._action(p,S);if(c){const l=_=>Date.now()-v>=12?setTimeout(()=>this._innerWrite(0,_)):this._innerWrite(v,_);return void c.catch(_=>(queueMicrotask(()=>{throw _}),Promise.resolve(!1))).then(l)}const a=this._callbacks[this._bufferOffset];if(a&&a(),this._bufferOffset++,this._pendingData-=p.length,Date.now()-v>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(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()}}o.WriteBuffer=f},5941:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.toRgbString=o.parseColor=void 0;const u=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,d=/^[\da-f]+$/;function m(f,g){const w=f.toString(16),S=w.length<2?"0"+w:w;switch(g){case 4:return w[0];case 8:return S;case 12:return(S+S).slice(0,3);default:return S+S}}o.parseColor=function(f){if(!f)return;let g=f.toLowerCase();if(g.indexOf("rgb:")===0){g=g.slice(4);const w=u.exec(g);if(w){const S=w[1]?15:w[4]?255:w[7]?4095:65535;return[Math.round(parseInt(w[1]||w[4]||w[7]||w[10],16)/S*255),Math.round(parseInt(w[2]||w[5]||w[8]||w[11],16)/S*255),Math.round(parseInt(w[3]||w[6]||w[9]||w[12],16)/S*255)]}}else if(g.indexOf("#")===0&&(g=g.slice(1),d.exec(g)&&[3,6,9,12].includes(g.length))){const w=g.length/3,S=[0,0,0];for(let v=0;v<3;++v){const p=parseInt(g.slice(w*v,w*v+w),16);S[v]=w===1?p<<4:w===2?p:w===3?p>>4:p>>8}return S}},o.toRgbString=function(f,g=16){const[w,S,v]=f;return`rgb:${m(w,g)}/${m(S,g)}/${m(v,g)}`}},5770:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.PAYLOAD_LIMIT=void 0,o.PAYLOAD_LIMIT=1e7},6351:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DcsHandler=o.DcsParser=void 0;const d=u(482),m=u(8742),f=u(5770),g=[];o.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=g,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=g}registerHandler(S,v){this._handlers[S]===void 0&&(this._handlers[S]=[]);const p=this._handlers[S];return p.push(v),{dispose:()=>{const c=p.indexOf(v);c!==-1&&p.splice(c,1)}}}clearHandler(S){this._handlers[S]&&delete this._handlers[S]}setHandlerFallback(S){this._handlerFb=S}reset(){if(this._active.length)for(let S=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;S>=0;--S)this._active[S].unhook(!1);this._stack.paused=!1,this._active=g,this._ident=0}hook(S,v){if(this.reset(),this._ident=S,this._active=this._handlers[S]||g,this._active.length)for(let p=this._active.length-1;p>=0;p--)this._active[p].hook(v);else this._handlerFb(this._ident,"HOOK",v)}put(S,v,p){if(this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].put(S,v,p);else this._handlerFb(this._ident,"PUT",(0,d.utf32ToString)(S,v,p))}unhook(S,v=!0){if(this._active.length){let p=!1,c=this._active.length-1,a=!1;if(this._stack.paused&&(c=this._stack.loopPosition-1,p=v,a=this._stack.fallThrough,this._stack.paused=!1),!a&&p===!1){for(;c>=0&&(p=this._active[c].unhook(S),p!==!0);c--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=c,this._stack.fallThrough=!1,p;c--}for(;c>=0;c--)if(p=this._active[c].unhook(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=c,this._stack.fallThrough=!0,p}else this._handlerFb(this._ident,"UNHOOK",S);this._active=g,this._ident=0}};const w=new m.Params;w.addParam(0),o.DcsHandler=class{constructor(S){this._handler=S,this._data="",this._params=w,this._hitLimit=!1}hook(S){this._params=S.length>1||S.params[0]?S.clone():w,this._data="",this._hitLimit=!1}put(S,v,p){this._hitLimit||(this._data+=(0,d.utf32ToString)(S,v,p),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(S){let v=!1;if(this._hitLimit)v=!1;else if(S&&(v=this._handler(this._data,this._params),v instanceof Promise))return v.then(p=>(this._params=w,this._data="",this._hitLimit=!1,p));return this._params=w,this._data="",this._hitLimit=!1,v}}},2015:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.EscapeSequenceParser=o.VT500_TRANSITION_TABLE=o.TransitionTable=void 0;const d=u(844),m=u(8742),f=u(6242),g=u(6351);class w{constructor(c){this.table=new Uint8Array(c)}setDefault(c,a){this.table.fill(c<<4|a)}add(c,a,l,_){this.table[a<<8|c]=l<<4|_}addMany(c,a,l,_){for(let j=0;jx),a=(k,x)=>c.slice(k,x),l=a(32,127),_=a(0,24);_.push(25),_.push.apply(_,a(28,32));const j=a(0,14);let b;for(b in p.setDefault(1,0),p.addMany(l,0,2,0),j)p.addMany([24,26,153,154],b,3,0),p.addMany(a(128,144),b,3,0),p.addMany(a(144,152),b,3,0),p.add(156,b,0,0),p.add(27,b,11,1),p.add(157,b,4,8),p.addMany([152,158,159],b,0,7),p.add(155,b,11,3),p.add(144,b,11,9);return p.addMany(_,0,3,0),p.addMany(_,1,3,1),p.add(127,1,0,1),p.addMany(_,8,0,8),p.addMany(_,3,3,3),p.add(127,3,0,3),p.addMany(_,4,3,4),p.add(127,4,0,4),p.addMany(_,6,3,6),p.addMany(_,5,3,5),p.add(127,5,0,5),p.addMany(_,2,3,2),p.add(127,2,0,2),p.add(93,1,4,8),p.addMany(l,8,5,8),p.add(127,8,5,8),p.addMany([156,27,24,26,7],8,6,0),p.addMany(a(28,32),8,0,8),p.addMany([88,94,95],1,0,7),p.addMany(l,7,0,7),p.addMany(_,7,0,7),p.add(156,7,0,0),p.add(127,7,0,7),p.add(91,1,11,3),p.addMany(a(64,127),3,7,0),p.addMany(a(48,60),3,8,4),p.addMany([60,61,62,63],3,9,4),p.addMany(a(48,60),4,8,4),p.addMany(a(64,127),4,7,0),p.addMany([60,61,62,63],4,0,6),p.addMany(a(32,64),6,0,6),p.add(127,6,0,6),p.addMany(a(64,127),6,0,0),p.addMany(a(32,48),3,9,5),p.addMany(a(32,48),5,9,5),p.addMany(a(48,64),5,0,6),p.addMany(a(64,127),5,7,0),p.addMany(a(32,48),4,9,5),p.addMany(a(32,48),1,9,2),p.addMany(a(32,48),2,9,2),p.addMany(a(48,127),2,10,0),p.addMany(a(48,80),1,10,0),p.addMany(a(81,88),1,10,0),p.addMany([89,90,92],1,10,0),p.addMany(a(96,127),1,10,0),p.add(80,1,11,9),p.addMany(_,9,0,9),p.add(127,9,0,9),p.addMany(a(28,32),9,0,9),p.addMany(a(32,48),9,9,12),p.addMany(a(48,60),9,8,10),p.addMany([60,61,62,63],9,9,10),p.addMany(_,11,0,11),p.addMany(a(32,128),11,0,11),p.addMany(a(28,32),11,0,11),p.addMany(_,10,0,10),p.add(127,10,0,10),p.addMany(a(28,32),10,0,10),p.addMany(a(48,60),10,8,10),p.addMany([60,61,62,63],10,0,11),p.addMany(a(32,48),10,9,12),p.addMany(_,12,0,12),p.add(127,12,0,12),p.addMany(a(28,32),12,0,12),p.addMany(a(32,48),12,9,12),p.addMany(a(48,64),12,0,11),p.addMany(a(64,127),12,12,13),p.addMany(a(64,127),10,12,13),p.addMany(a(64,127),9,12,13),p.addMany(_,13,13,13),p.addMany(l,13,13,13),p.add(127,13,0,13),p.addMany([27,156,24,26],13,14,0),p.add(S,0,2,0),p.add(S,8,5,8),p.add(S,6,0,6),p.add(S,11,0,11),p.add(S,13,13,13),p}();class v extends d.Disposable{constructor(c=o.VT500_TRANSITION_TABLE){super(),this._transitions=c,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new m.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(a,l,_)=>{},this._executeHandlerFb=a=>{},this._csiHandlerFb=(a,l)=>{},this._escHandlerFb=a=>{},this._errorHandlerFb=a=>a,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,d.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new f.OscParser),this._dcsParser=this.register(new g.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(c,a=[64,126]){let l=0;if(c.prefix){if(c.prefix.length>1)throw new Error("only one byte as prefix supported");if(l=c.prefix.charCodeAt(0),l&&60>l||l>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(c.intermediates){if(c.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let j=0;jb||b>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");l<<=8,l|=b}}if(c.final.length!==1)throw new Error("final must be a single byte");const _=c.final.charCodeAt(0);if(a[0]>_||_>a[1])throw new Error(`final must be in range ${a[0]} .. ${a[1]}`);return l<<=8,l|=_,l}identToString(c){const a=[];for(;c;)a.push(String.fromCharCode(255&c)),c>>=8;return a.reverse().join("")}setPrintHandler(c){this._printHandler=c}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(c,a){const l=this._identifier(c,[48,126]);this._escHandlers[l]===void 0&&(this._escHandlers[l]=[]);const _=this._escHandlers[l];return _.push(a),{dispose:()=>{const j=_.indexOf(a);j!==-1&&_.splice(j,1)}}}clearEscHandler(c){this._escHandlers[this._identifier(c,[48,126])]&&delete this._escHandlers[this._identifier(c,[48,126])]}setEscHandlerFallback(c){this._escHandlerFb=c}setExecuteHandler(c,a){this._executeHandlers[c.charCodeAt(0)]=a}clearExecuteHandler(c){this._executeHandlers[c.charCodeAt(0)]&&delete this._executeHandlers[c.charCodeAt(0)]}setExecuteHandlerFallback(c){this._executeHandlerFb=c}registerCsiHandler(c,a){const l=this._identifier(c);this._csiHandlers[l]===void 0&&(this._csiHandlers[l]=[]);const _=this._csiHandlers[l];return _.push(a),{dispose:()=>{const j=_.indexOf(a);j!==-1&&_.splice(j,1)}}}clearCsiHandler(c){this._csiHandlers[this._identifier(c)]&&delete this._csiHandlers[this._identifier(c)]}setCsiHandlerFallback(c){this._csiHandlerFb=c}registerDcsHandler(c,a){return this._dcsParser.registerHandler(this._identifier(c),a)}clearDcsHandler(c){this._dcsParser.clearHandler(this._identifier(c))}setDcsHandlerFallback(c){this._dcsParser.setHandlerFallback(c)}registerOscHandler(c,a){return this._oscParser.registerHandler(c,a)}clearOscHandler(c){this._oscParser.clearHandler(c)}setOscHandlerFallback(c){this._oscParser.setHandlerFallback(c)}setErrorHandler(c){this._errorHandler=c}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(c,a,l,_,j){this._parseStack.state=c,this._parseStack.handlers=a,this._parseStack.handlerPos=l,this._parseStack.transition=_,this._parseStack.chunkPos=j}parse(c,a,l){let _,j=0,b=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(l===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const x=this._parseStack.handlers;let N=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(l===!1&&N>-1){for(;N>=0&&(_=x[N](this._params),_!==!0);N--)if(_ instanceof Promise)return this._parseStack.handlerPos=N,_}this._parseStack.handlers=[];break;case 4:if(l===!1&&N>-1){for(;N>=0&&(_=x[N](),_!==!0);N--)if(_ instanceof Promise)return this._parseStack.handlerPos=N,_}this._parseStack.handlers=[];break;case 6:if(j=c[this._parseStack.chunkPos],_=this._dcsParser.unhook(j!==24&&j!==26,l),_)return _;j===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(j=c[this._parseStack.chunkPos],_=this._oscParser.end(j!==24&&j!==26,l),_)return _;j===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let x=k;x>4){case 2:for(let O=x+1;;++O){if(O>=a||(j=c[O])<32||j>126&&j=a||(j=c[O])<32||j>126&&j=a||(j=c[O])<32||j>126&&j=a||(j=c[O])<32||j>126&&j=0&&(_=N[E](this._params),_!==!0);E--)if(_ instanceof Promise)return this._preserveStack(3,N,E,b,x),_;E<0&&this._csiHandlerFb(this._collect<<8|j,this._params),this.precedingJoinState=0;break;case 8:do switch(j){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(j-48)}while(++x47&&j<60);x--;break;case 9:this._collect<<=8,this._collect|=j;break;case 10:const L=this._escHandlers[this._collect<<8|j];let T=L?L.length-1:-1;for(;T>=0&&(_=L[T](),_!==!0);T--)if(_ instanceof Promise)return this._preserveStack(4,L,T,b,x),_;T<0&&this._escHandlerFb(this._collect<<8|j),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|j,this._params);break;case 13:for(let O=x+1;;++O)if(O>=a||(j=c[O])===24||j===26||j===27||j>127&&j=a||(j=c[O])<32||j>127&&j{Object.defineProperty(o,"__esModule",{value:!0}),o.OscHandler=o.OscParser=void 0;const d=u(5770),m=u(482),f=[];o.OscParser=class{constructor(){this._state=0,this._active=f,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(g,w){this._handlers[g]===void 0&&(this._handlers[g]=[]);const S=this._handlers[g];return S.push(w),{dispose:()=>{const v=S.indexOf(w);v!==-1&&S.splice(v,1)}}}clearHandler(g){this._handlers[g]&&delete this._handlers[g]}setHandlerFallback(g){this._handlerFb=g}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=f}reset(){if(this._state===2)for(let g=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;g>=0;--g)this._active[g].end(!1);this._stack.paused=!1,this._active=f,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||f,this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].start();else this._handlerFb(this._id,"START")}_put(g,w,S){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(g,w,S);else this._handlerFb(this._id,"PUT",(0,m.utf32ToString)(g,w,S))}start(){this.reset(),this._state=1}put(g,w,S){if(this._state!==3){if(this._state===1)for(;w0&&this._put(g,w,S)}}end(g,w=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let S=!1,v=this._active.length-1,p=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,S=w,p=this._stack.fallThrough,this._stack.paused=!1),!p&&S===!1){for(;v>=0&&(S=this._active[v].end(g),S!==!0);v--)if(S instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,S;v--}for(;v>=0;v--)if(S=this._active[v].end(!1),S instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,S}else this._handlerFb(this._id,"END",g);this._active=f,this._id=-1,this._state=0}}},o.OscHandler=class{constructor(g){this._handler=g,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(g,w,S){this._hitLimit||(this._data+=(0,m.utf32ToString)(g,w,S),this._data.length>d.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(g){let w=!1;if(this._hitLimit)w=!1;else if(g&&(w=this._handler(this._data),w instanceof Promise))return w.then(S=>(this._data="",this._hitLimit=!1,S));return this._data="",this._hitLimit=!1,w}}},8742:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Params=void 0;const u=2147483647;class d{static fromArray(f){const g=new d;if(!f.length)return g;for(let w=Array.isArray(f[0])?1:0;w256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(f),this.length=0,this._subParams=new Int32Array(g),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(f),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const f=new d(this.maxLength,this.maxSubParamsLength);return f.params.set(this.params),f.length=this.length,f._subParams.set(this._subParams),f._subParamsLength=this._subParamsLength,f._subParamsIdx.set(this._subParamsIdx),f._rejectDigits=this._rejectDigits,f._rejectSubDigits=this._rejectSubDigits,f._digitIsSub=this._digitIsSub,f}toArray(){const f=[];for(let g=0;g>8,S=255&this._subParamsIdx[g];S-w>0&&f.push(Array.prototype.slice.call(this._subParams,w,S))}return f}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(f){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(f<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=f>u?u:f}}addSubParam(f){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(f<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=f>u?u:f,this._subParamsIdx[this.length-1]++}}hasSubParams(f){return(255&this._subParamsIdx[f])-(this._subParamsIdx[f]>>8)>0}getSubParams(f){const g=this._subParamsIdx[f]>>8,w=255&this._subParamsIdx[f];return w-g>0?this._subParams.subarray(g,w):null}getSubParamsAll(){const f={};for(let g=0;g>8,S=255&this._subParamsIdx[g];S-w>0&&(f[g]=this._subParams.slice(w,S))}return f}addDigit(f){let g;if(this._rejectDigits||!(g=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const w=this._digitIsSub?this._subParams:this.params,S=w[g-1];w[g-1]=~S?Math.min(10*S+f,u):f}}o.Params=d},5741:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.AddonManager=void 0,o.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let u=this._addons.length-1;u>=0;u--)this._addons[u].instance.dispose()}loadAddon(u,d){const m={instance:d,dispose:d.dispose,isDisposed:!1};this._addons.push(m),d.dispose=()=>this._wrappedAddonDispose(m),d.activate(u)}_wrappedAddonDispose(u){if(u.isDisposed)return;let d=-1;for(let m=0;m{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferApiView=void 0;const d=u(3785),m=u(511);o.BufferApiView=class{constructor(f,g){this._buffer=f,this.type=g}init(f){return this._buffer=f,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(f){const g=this._buffer.lines.get(f);if(g)return new d.BufferLineApiView(g)}getNullCell(){return new m.CellData}}},3785:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLineApiView=void 0;const d=u(511);o.BufferLineApiView=class{constructor(m){this._line=m}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(m,f){if(!(m<0||m>=this._line.length))return f?(this._line.loadCell(m,f),f):this._line.loadCell(m,new d.CellData)}translateToString(m,f,g){return this._line.translateToString(m,f,g)}}},8285:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferNamespaceApi=void 0;const d=u(8771),m=u(8460),f=u(844);class g extends f.Disposable{constructor(S){super(),this._core=S,this._onBufferChange=this.register(new m.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new d.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new d.BufferApiView(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)}}o.BufferNamespaceApi=g},7975:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ParserApi=void 0,o.ParserApi=class{constructor(u){this._core=u}registerCsiHandler(u,d){return this._core.registerCsiHandler(u,m=>d(m.toArray()))}addCsiHandler(u,d){return this.registerCsiHandler(u,d)}registerDcsHandler(u,d){return this._core.registerDcsHandler(u,(m,f)=>d(m,f.toArray()))}addDcsHandler(u,d){return this.registerDcsHandler(u,d)}registerEscHandler(u,d){return this._core.registerEscHandler(u,d)}addEscHandler(u,d){return this.registerEscHandler(u,d)}registerOscHandler(u,d){return this._core.registerOscHandler(u,d)}addOscHandler(u,d){return this.registerOscHandler(u,d)}}},7090:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeApi=void 0,o.UnicodeApi=class{constructor(u){this._core=u}register(u){this._core.unicodeService.register(u)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(u){this._core.unicodeService.activeVersion=u}}},744:function(y,o,u){var d=this&&this.__decorate||function(p,c,a,l){var _,j=arguments.length,b=j<3?c:l===null?l=Object.getOwnPropertyDescriptor(c,a):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(p,c,a,l);else for(var k=p.length-1;k>=0;k--)(_=p[k])&&(b=(j<3?_(b):j>3?_(c,a,b):_(c,a))||b);return j>3&&b&&Object.defineProperty(c,a,b),b},m=this&&this.__param||function(p,c){return function(a,l){c(a,l,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferService=o.MINIMUM_ROWS=o.MINIMUM_COLS=void 0;const f=u(8460),g=u(844),w=u(5295),S=u(2585);o.MINIMUM_COLS=2,o.MINIMUM_ROWS=1;let v=o.BufferService=class extends g.Disposable{get buffer(){return this.buffers.active}constructor(p){super(),this.isUserScrolling=!1,this._onResize=this.register(new f.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new f.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(p.rawOptions.cols||0,o.MINIMUM_COLS),this.rows=Math.max(p.rawOptions.rows||0,o.MINIMUM_ROWS),this.buffers=this.register(new w.BufferSet(p,this))}resize(p,c){this.cols=p,this.rows=c,this.buffers.resize(p,c),this._onResize.fire({cols:p,rows:c})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(p,c=!1){const a=this.buffer;let l;l=this._cachedBlankLine,l&&l.length===this.cols&&l.getFg(0)===p.fg&&l.getBg(0)===p.bg||(l=a.getBlankLine(p,c),this._cachedBlankLine=l),l.isWrapped=c;const _=a.ybase+a.scrollTop,j=a.ybase+a.scrollBottom;if(a.scrollTop===0){const b=a.lines.isFull;j===a.lines.length-1?b?a.lines.recycle().copyFrom(l):a.lines.push(l.clone()):a.lines.splice(j+1,0,l.clone()),b?this.isUserScrolling&&(a.ydisp=Math.max(a.ydisp-1,0)):(a.ybase++,this.isUserScrolling||a.ydisp++)}else{const b=j-_+1;a.lines.shiftElements(_+1,b-1,-1),a.lines.set(j,l.clone())}this.isUserScrolling||(a.ydisp=a.ybase),this._onScroll.fire(a.ydisp)}scrollLines(p,c,a){const l=this.buffer;if(p<0){if(l.ydisp===0)return;this.isUserScrolling=!0}else p+l.ydisp>=l.ybase&&(this.isUserScrolling=!1);const _=l.ydisp;l.ydisp=Math.max(Math.min(l.ydisp+p,l.ybase),0),_!==l.ydisp&&(c||this._onScroll.fire(l.ydisp))}};o.BufferService=v=d([m(0,S.IOptionsService)],v)},7994:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CharsetService=void 0,o.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(u){this.glevel=u,this.charset=this._charsets[u]}setgCharset(u,d){this._charsets[u]=d,this.glevel===u&&(this.charset=d)}}},1753:function(y,o,u){var d=this&&this.__decorate||function(l,_,j,b){var k,x=arguments.length,N=x<3?_:b===null?b=Object.getOwnPropertyDescriptor(_,j):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(l,_,j,b);else for(var E=l.length-1;E>=0;E--)(k=l[E])&&(N=(x<3?k(N):x>3?k(_,j,N):k(_,j))||N);return x>3&&N&&Object.defineProperty(_,j,N),N},m=this&&this.__param||function(l,_){return function(j,b){_(j,b,l)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreMouseService=void 0;const f=u(2585),g=u(8460),w=u(844),S={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:l=>l.button!==4&&l.action===1&&(l.ctrl=!1,l.alt=!1,l.shift=!1,!0)},VT200:{events:19,restrict:l=>l.action!==32},DRAG:{events:23,restrict:l=>l.action!==32||l.button!==3},ANY:{events:31,restrict:l=>!0}};function v(l,_){let j=(l.ctrl?16:0)|(l.shift?4:0)|(l.alt?8:0);return l.button===4?(j|=64,j|=l.action):(j|=3&l.button,4&l.button&&(j|=64),8&l.button&&(j|=128),l.action===32?j|=32:l.action!==0||_||(j|=3)),j}const p=String.fromCharCode,c={DEFAULT:l=>{const _=[v(l,!1)+32,l.col+32,l.row+32];return _[0]>255||_[1]>255||_[2]>255?"":`\x1B[M${p(_[0])}${p(_[1])}${p(_[2])}`},SGR:l=>{const _=l.action===0&&l.button!==4?"m":"M";return`\x1B[<${v(l,!0)};${l.col};${l.row}${_}`},SGR_PIXELS:l=>{const _=l.action===0&&l.button!==4?"m":"M";return`\x1B[<${v(l,!0)};${l.x};${l.y}${_}`}};let a=o.CoreMouseService=class extends w.Disposable{constructor(l,_){super(),this._bufferService=l,this._coreService=_,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new g.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const j of Object.keys(S))this.addProtocol(j,S[j]);for(const j of Object.keys(c))this.addEncoding(j,c[j]);this.reset()}addProtocol(l,_){this._protocols[l]=_}addEncoding(l,_){this._encodings[l]=_}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(l){if(!this._protocols[l])throw new Error(`unknown protocol "${l}"`);this._activeProtocol=l,this._onProtocolChange.fire(this._protocols[l].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(l){if(!this._encodings[l])throw new Error(`unknown encoding "${l}"`);this._activeEncoding=l}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(l){if(l.col<0||l.col>=this._bufferService.cols||l.row<0||l.row>=this._bufferService.rows||l.button===4&&l.action===32||l.button===3&&l.action!==32||l.button!==4&&(l.action===2||l.action===3)||(l.col++,l.row++,l.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,l,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(l))return!1;const _=this._encodings[this._activeEncoding](l);return _&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(_):this._coreService.triggerDataEvent(_,!0)),this._lastEvent=l,!0}explainEvents(l){return{down:!!(1&l),up:!!(2&l),drag:!!(4&l),move:!!(8&l),wheel:!!(16&l)}}_equalEvents(l,_,j){if(j){if(l.x!==_.x||l.y!==_.y)return!1}else if(l.col!==_.col||l.row!==_.row)return!1;return l.button===_.button&&l.action===_.action&&l.ctrl===_.ctrl&&l.alt===_.alt&&l.shift===_.shift}};o.CoreMouseService=a=d([m(0,f.IBufferService),m(1,f.ICoreService)],a)},6975:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreService=void 0;const f=u(1439),g=u(8460),w=u(844),S=u(2585),v=Object.freeze({insertMode:!1}),p=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let c=o.CoreService=class extends w.Disposable{constructor(a,l,_){super(),this._bufferService=a,this._logService=l,this._optionsService=_,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new g.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new g.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new g.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new g.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,f.clone)(v),this.decPrivateModes=(0,f.clone)(p)}reset(){this.modes=(0,f.clone)(v),this.decPrivateModes=(0,f.clone)(p)}triggerDataEvent(a,l=!1){if(this._optionsService.rawOptions.disableStdin)return;const _=this._bufferService.buffer;l&&this._optionsService.rawOptions.scrollOnUserInput&&_.ybase!==_.ydisp&&this._onRequestScrollToBottom.fire(),l&&this._onUserInput.fire(),this._logService.debug(`sending data "${a}"`,()=>a.split("").map(j=>j.charCodeAt(0))),this._onData.fire(a)}triggerBinaryEvent(a){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${a}"`,()=>a.split("").map(l=>l.charCodeAt(0))),this._onBinary.fire(a))}};o.CoreService=c=d([m(0,S.IBufferService),m(1,S.ILogService),m(2,S.IOptionsService)],c)},9074:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DecorationService=void 0;const d=u(8055),m=u(8460),f=u(844),g=u(6106);let w=0,S=0;class v extends f.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new g.SortedList(a=>a==null?void 0:a.marker.line),this._onDecorationRegistered=this.register(new m.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new m.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,f.toDisposable)(()=>this.reset()))}registerDecoration(a){if(a.marker.isDisposed)return;const l=new p(a);if(l){const _=l.marker.onDispose(()=>l.dispose());l.onDispose(()=>{l&&(this._decorations.delete(l)&&this._onDecorationRemoved.fire(l),_.dispose())}),this._decorations.insert(l),this._onDecorationRegistered.fire(l)}return l}reset(){for(const a of this._decorations.values())a.dispose();this._decorations.clear()}*getDecorationsAtCell(a,l,_){let j=0,b=0;for(const k of this._decorations.getKeyIterator(l))j=k.options.x??0,b=j+(k.options.width??1),a>=j&&a{w=b.options.x??0,S=w+(b.options.width??1),a>=w&&a{Object.defineProperty(o,"__esModule",{value:!0}),o.InstantiationService=o.ServiceCollection=void 0;const d=u(2585),m=u(8343);class f{constructor(...w){this._entries=new Map;for(const[S,v]of w)this.set(S,v)}set(w,S){const v=this._entries.get(w);return this._entries.set(w,S),v}forEach(w){for(const[S,v]of this._entries.entries())w(S,v)}has(w){return this._entries.has(w)}get(w){return this._entries.get(w)}}o.ServiceCollection=f,o.InstantiationService=class{constructor(){this._services=new f,this._services.set(d.IInstantiationService,this)}setService(g,w){this._services.set(g,w)}getService(g){return this._services.get(g)}createInstance(g,...w){const S=(0,m.getServiceDependencies)(g).sort((c,a)=>c.index-a.index),v=[];for(const c of S){const a=this._services.get(c.id);if(!a)throw new Error(`[createInstance] ${g.name} depends on UNKNOWN service ${c.id}.`);v.push(a)}const p=S.length>0?S[0].index:w.length;if(w.length!==p)throw new Error(`[createInstance] First service dependency of ${g.name} at position ${p+1} conflicts with ${w.length} static arguments`);return new g(...w,...v)}}},7866:function(y,o,u){var d=this&&this.__decorate||function(p,c,a,l){var _,j=arguments.length,b=j<3?c:l===null?l=Object.getOwnPropertyDescriptor(c,a):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(p,c,a,l);else for(var k=p.length-1;k>=0;k--)(_=p[k])&&(b=(j<3?_(b):j>3?_(c,a,b):_(c,a))||b);return j>3&&b&&Object.defineProperty(c,a,b),b},m=this&&this.__param||function(p,c){return function(a,l){c(a,l,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.traceCall=o.setTraceLogger=o.LogService=void 0;const f=u(844),g=u(2585),w={trace:g.LogLevelEnum.TRACE,debug:g.LogLevelEnum.DEBUG,info:g.LogLevelEnum.INFO,warn:g.LogLevelEnum.WARN,error:g.LogLevelEnum.ERROR,off:g.LogLevelEnum.OFF};let S,v=o.LogService=class extends f.Disposable{get logLevel(){return this._logLevel}constructor(p){super(),this._optionsService=p,this._logLevel=g.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),S=this}_updateLogLevel(){this._logLevel=w[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(p){for(let c=0;cJSON.stringify(b)).join(", ")})`);const j=l.apply(this,_);return S.trace(`GlyphRenderer#${l.name} return`,j),j}}},7302:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.OptionsService=o.DEFAULT_OPTIONS=void 0;const d=u(8460),m=u(844),f=u(6114);o.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:f.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const g=["normal","bold","100","200","300","400","500","600","700","800","900"];class w extends m.Disposable{constructor(v){super(),this._onOptionChange=this.register(new d.EventEmitter),this.onOptionChange=this._onOptionChange.event;const p={...o.DEFAULT_OPTIONS};for(const c in v)if(c in p)try{const a=v[c];p[c]=this._sanitizeAndValidateOption(c,a)}catch(a){console.error(a)}this.rawOptions=p,this.options={...p},this._setupOptions(),this.register((0,m.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(v,p){return this.onOptionChange(c=>{c===v&&p(this.rawOptions[v])})}onMultipleOptionChange(v,p){return this.onOptionChange(c=>{v.indexOf(c)!==-1&&p()})}_setupOptions(){const v=c=>{if(!(c in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${c}"`);return this.rawOptions[c]},p=(c,a)=>{if(!(c in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${c}"`);a=this._sanitizeAndValidateOption(c,a),this.rawOptions[c]!==a&&(this.rawOptions[c]=a,this._onOptionChange.fire(c))};for(const c in this.rawOptions){const a={get:v.bind(this,c),set:p.bind(this,c)};Object.defineProperty(this.options,c,a)}}_sanitizeAndValidateOption(v,p){switch(v){case"cursorStyle":if(p||(p=o.DEFAULT_OPTIONS[v]),!function(c){return c==="block"||c==="underline"||c==="bar"}(p))throw new Error(`"${p}" is not a valid value for ${v}`);break;case"wordSeparator":p||(p=o.DEFAULT_OPTIONS[v]);break;case"fontWeight":case"fontWeightBold":if(typeof p=="number"&&1<=p&&p<=1e3)break;p=g.includes(p)?p:o.DEFAULT_OPTIONS[v];break;case"cursorWidth":p=Math.floor(p);case"lineHeight":case"tabStopWidth":if(p<1)throw new Error(`${v} cannot be less than 1, value: ${p}`);break;case"minimumContrastRatio":p=Math.max(1,Math.min(21,Math.round(10*p)/10));break;case"scrollback":if((p=Math.min(p,4294967295))<0)throw new Error(`${v} cannot be less than 0, value: ${p}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(p<=0)throw new Error(`${v} cannot be less than or equal to 0, value: ${p}`);break;case"rows":case"cols":if(!p&&p!==0)throw new Error(`${v} must be numeric, value: ${p}`);break;case"windowsPty":p=p??{}}return p}}o.OptionsService=w},2660:function(y,o,u){var d=this&&this.__decorate||function(w,S,v,p){var c,a=arguments.length,l=a<3?S:p===null?p=Object.getOwnPropertyDescriptor(S,v):p;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(w,S,v,p);else for(var _=w.length-1;_>=0;_--)(c=w[_])&&(l=(a<3?c(l):a>3?c(S,v,l):c(S,v))||l);return a>3&&l&&Object.defineProperty(S,v,l),l},m=this&&this.__param||function(w,S){return function(v,p){S(v,p,w)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkService=void 0;const f=u(2585);let g=o.OscLinkService=class{constructor(w){this._bufferService=w,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(w){const S=this._bufferService.buffer;if(w.id===void 0){const _=S.addMarker(S.ybase+S.y),j={data:w,id:this._nextId++,lines:[_]};return _.onDispose(()=>this._removeMarkerFromLink(j,_)),this._dataByLinkId.set(j.id,j),j.id}const v=w,p=this._getEntryIdKey(v),c=this._entriesWithId.get(p);if(c)return this.addLineToLink(c.id,S.ybase+S.y),c.id;const a=S.addMarker(S.ybase+S.y),l={id:this._nextId++,key:this._getEntryIdKey(v),data:v,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(l,a)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(w,S){const v=this._dataByLinkId.get(w);if(v&&v.lines.every(p=>p.line!==S)){const p=this._bufferService.buffer.addMarker(S);v.lines.push(p),p.onDispose(()=>this._removeMarkerFromLink(v,p))}}getLinkData(w){var S;return(S=this._dataByLinkId.get(w))==null?void 0:S.data}_getEntryIdKey(w){return`${w.id};;${w.uri}`}_removeMarkerFromLink(w,S){const v=w.lines.indexOf(S);v!==-1&&(w.lines.splice(v,1),w.lines.length===0&&(w.data.id!==void 0&&this._entriesWithId.delete(w.key),this._dataByLinkId.delete(w.id)))}};o.OscLinkService=g=d([m(0,f.IBufferService)],g)},8343:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createDecorator=o.getServiceDependencies=o.serviceRegistry=void 0;const u="di$target",d="di$dependencies";o.serviceRegistry=new Map,o.getServiceDependencies=function(m){return m[d]||[]},o.createDecorator=function(m){if(o.serviceRegistry.has(m))return o.serviceRegistry.get(m);const f=function(g,w,S){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(v,p,c){p[u]===p?p[d].push({id:v,index:c}):(p[d]=[{id:v,index:c}],p[u]=p)})(f,g,S)};return f.toString=()=>m,o.serviceRegistry.set(m,f),f}},2585:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.IDecorationService=o.IUnicodeService=o.IOscLinkService=o.IOptionsService=o.ILogService=o.LogLevelEnum=o.IInstantiationService=o.ICharsetService=o.ICoreService=o.ICoreMouseService=o.IBufferService=void 0;const d=u(8343);var m;o.IBufferService=(0,d.createDecorator)("BufferService"),o.ICoreMouseService=(0,d.createDecorator)("CoreMouseService"),o.ICoreService=(0,d.createDecorator)("CoreService"),o.ICharsetService=(0,d.createDecorator)("CharsetService"),o.IInstantiationService=(0,d.createDecorator)("InstantiationService"),function(f){f[f.TRACE=0]="TRACE",f[f.DEBUG=1]="DEBUG",f[f.INFO=2]="INFO",f[f.WARN=3]="WARN",f[f.ERROR=4]="ERROR",f[f.OFF=5]="OFF"}(m||(o.LogLevelEnum=m={})),o.ILogService=(0,d.createDecorator)("LogService"),o.IOptionsService=(0,d.createDecorator)("OptionsService"),o.IOscLinkService=(0,d.createDecorator)("OscLinkService"),o.IUnicodeService=(0,d.createDecorator)("UnicodeService"),o.IDecorationService=(0,d.createDecorator)("DecorationService")},1480:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeService=void 0;const d=u(8460),m=u(225);class f{static extractShouldJoin(w){return(1&w)!=0}static extractWidth(w){return w>>1&3}static extractCharKind(w){return w>>3}static createPropertyValue(w,S,v=!1){return(16777215&w)<<3|(3&S)<<1|(v?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new d.EventEmitter,this.onChange=this._onChange.event;const w=new m.UnicodeV6;this.register(w),this._active=w.version,this._activeProvider=w}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(w){if(!this._providers[w])throw new Error(`unknown Unicode version "${w}"`);this._active=w,this._activeProvider=this._providers[w],this._onChange.fire(w)}register(w){this._providers[w.version]=w}wcwidth(w){return this._activeProvider.wcwidth(w)}getStringCellWidth(w){let S=0,v=0;const p=w.length;for(let c=0;c=p)return S+this.wcwidth(a);const j=w.charCodeAt(c);56320<=j&&j<=57343?a=1024*(a-55296)+j-56320+65536:S+=this.wcwidth(j)}const l=this.charProperties(a,v);let _=f.extractWidth(l);f.extractShouldJoin(l)&&(_-=f.extractWidth(v)),S+=_,v=l}return S}charProperties(w,S){return this._activeProvider.charProperties(w,S)}}o.UnicodeService=f}},n={};function i(y){var o=n[y];if(o!==void 0)return o.exports;var u=n[y]={exports:{}};return r[y].call(u.exports,u,u.exports,i),u.exports}var h={};return(()=>{var y=h;Object.defineProperty(y,"__esModule",{value:!0}),y.Terminal=void 0;const o=i(9042),u=i(3236),d=i(844),m=i(5741),f=i(8285),g=i(7975),w=i(7090),S=["cols","rows"];class v extends d.Disposable{constructor(c){super(),this._core=this.register(new u.Terminal(c)),this._addonManager=this.register(new m.AddonManager),this._publicOptions={...this._core.options};const a=_=>this._core.options[_],l=(_,j)=>{this._checkReadonlyOptions(_),this._core.options[_]=j};for(const _ in this._core.options){const j={get:a.bind(this,_),set:l.bind(this,_)};Object.defineProperty(this._publicOptions,_,j)}}_checkReadonlyOptions(c){if(S.includes(c))throw new Error(`Option "${c}" 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 g.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new w.UnicodeApi(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 f.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const c=this._core.coreService.decPrivateModes;let a="none";switch(this._core.coreMouseService.activeProtocol){case"X10":a="x10";break;case"VT200":a="vt200";break;case"DRAG":a="drag";break;case"ANY":a="any"}return{applicationCursorKeysMode:c.applicationCursorKeys,applicationKeypadMode:c.applicationKeypad,bracketedPasteMode:c.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:a,originMode:c.origin,reverseWraparoundMode:c.reverseWraparound,sendFocusMode:c.sendFocus,wraparoundMode:c.wraparound}}get options(){return this._publicOptions}set options(c){for(const a in c)this._publicOptions[a]=c[a]}blur(){this._core.blur()}focus(){this._core.focus()}input(c,a=!0){this._core.input(c,a)}resize(c,a){this._verifyIntegers(c,a),this._core.resize(c,a)}open(c){this._core.open(c)}attachCustomKeyEventHandler(c){this._core.attachCustomKeyEventHandler(c)}attachCustomWheelEventHandler(c){this._core.attachCustomWheelEventHandler(c)}registerLinkProvider(c){return this._core.registerLinkProvider(c)}registerCharacterJoiner(c){return this._checkProposedApi(),this._core.registerCharacterJoiner(c)}deregisterCharacterJoiner(c){this._checkProposedApi(),this._core.deregisterCharacterJoiner(c)}registerMarker(c=0){return this._verifyIntegers(c),this._core.registerMarker(c)}registerDecoration(c){return this._checkProposedApi(),this._verifyPositiveIntegers(c.x??0,c.width??0,c.height??0),this._core.registerDecoration(c)}hasSelection(){return this._core.hasSelection()}select(c,a,l){this._verifyIntegers(c,a,l),this._core.select(c,a,l)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(c,a){this._verifyIntegers(c,a),this._core.selectLines(c,a)}dispose(){super.dispose()}scrollLines(c){this._verifyIntegers(c),this._core.scrollLines(c)}scrollPages(c){this._verifyIntegers(c),this._core.scrollPages(c)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(c){this._verifyIntegers(c),this._core.scrollToLine(c)}clear(){this._core.clear()}write(c,a){this._core.write(c,a)}writeln(c,a){this._core.write(c),this._core.write(`\r +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(x){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),c.isLinux&&x&&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(x){const N=this._getMouseBufferCoords(x),E=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!!(E&&L&&N)&&this._areCoordsInSelection(N,E,L)}isCellInSelection(x,N){const E=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!(!E||!L)&&this._areCoordsInSelection([x,N],E,L)}_areCoordsInSelection(x,N,E){return x[1]>N[1]&&x[1]=N[0]&&x[0]=N[0]}_selectWordAtCursor(x,N){var T,P;const E=(P=(T=this._linkifier.currentLink)==null?void 0:T.link)==null?void 0:P.range;if(E)return this._model.selectionStart=[E.start.x-1,E.start.y-1],this._model.selectionStartLength=(0,a.getRangeLength)(E,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const L=this._getMouseBufferCoords(x);return!!L&&(this._selectWordAt(L,N),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(x,N){this._model.clearSelection(),x=Math.max(x,0),N=Math.min(N,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,x],this._model.selectionEnd=[this._bufferService.cols,N],this.refresh(),this._onSelectionChange.fire()}_handleTrim(x){this._model.handleTrim(x)&&this.refresh()}_getMouseBufferCoords(x){const N=this._mouseService.getCoords(x,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(N)return N[0]--,N[1]--,N[1]+=this._bufferService.buffer.ydisp,N}_getMouseEventScrollAmount(x){let N=(0,f.getCoordsRelativeToElement)(this._coreBrowserService.window,x,this._screenElement)[1];const E=this._renderService.dimensions.css.canvas.height;return N>=0&&N<=E?0:(N>E&&(N-=E),N=Math.min(Math.max(N,-50),50),N/=50,N/Math.abs(N)+Math.round(14*N))}shouldForceSelection(x){return c.isMac?x.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:x.shiftKey}handleMouseDown(x){if(this._mouseDownTimeStamp=x.timeStamp,(x.button!==2||!this.hasSelection)&&x.button===0){if(!this._enabled){if(!this.shouldForceSelection(x))return;x.stopPropagation()}x.preventDefault(),this._dragScrollAmount=0,this._enabled&&x.shiftKey?this._handleIncrementalClick(x):x.detail===1?this._handleSingleClick(x):x.detail===2?this._handleDoubleClick(x):x.detail===3&&this._handleTripleClick(x),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(),50)}_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(x){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(x))}_handleSingleClick(x){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(x)?3:0,this._model.selectionStart=this._getMouseBufferCoords(x),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const N=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);N&&N.length!==this._model.selectionStart[0]&&N.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(x){this._selectWordAtCursor(x,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(x){const N=this._getMouseBufferCoords(x);N&&(this._activeSelectionMode=2,this._selectLineAt(N[1]))}shouldColumnSelect(x){return x.altKey&&!(c.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(x){if(x.stopImmediatePropagation(),!this._model.selectionStart)return;const N=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(x),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const E=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(x.ydisp+this._bufferService.rows,x.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=x.ydisp),this.refresh()}}_handleMouseUp(x){const N=x.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&N<500&&x.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const E=this._mouseService.getCoords(x,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(E&&E[0]!==void 0&&E[1]!==void 0){const L=(0,g.moveToCellSequence)(E[0]-1,E[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(L,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const x=this._model.finalSelectionStart,N=this._model.finalSelectionEnd,E=!(!x||!N||x[0]===N[0]&&x[1]===N[1]);E?x&&N&&(this._oldSelectionStart&&this._oldSelectionEnd&&x[0]===this._oldSelectionStart[0]&&x[1]===this._oldSelectionStart[1]&&N[0]===this._oldSelectionEnd[0]&&N[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(x,N,E)):this._oldHasSelection&&this._fireOnSelectionChange(x,N,E)}_fireOnSelectionChange(x,N,E){this._oldSelectionStart=x,this._oldSelectionEnd=N,this._oldHasSelection=E,this._onSelectionChange.fire()}_handleBufferActivate(x){this.clearSelection(),this._trimListener.dispose(),this._trimListener=x.activeBuffer.lines.onTrim(N=>this._handleTrim(N))}_convertViewportColToCharacterIndex(x,N){let E=N;for(let L=0;N>=L;L++){const T=x.loadCell(L,this._workCell).getChars().length;this._workCell.getWidth()===0?E--:T>1&&N!==L&&(E+=T-1)}return E}setSelection(x,N,E){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[x,N],this._model.selectionStartLength=E,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(x){this._isClickInSelection(x)||(this._selectWordAtCursor(x,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(x,N,E=!0,L=!0){if(x[0]>=this._bufferService.cols)return;const T=this._bufferService.buffer,P=T.lines.get(x[1]);if(!P)return;const B=T.translateBufferLineToString(x[1],!1);let U=this._convertViewportColToCharacterIndex(P,x[0]),K=U;const q=x[0]-U;let $=0,R=0,A=0,M=0;if(B.charAt(U)===" "){for(;U>0&&B.charAt(U-1)===" ";)U--;for(;K1&&(M+=X-1,K+=X-1);F>0&&U>0&&!this._isCharWordSeparator(P.loadCell(F-1,this._workCell));){P.loadCell(F-1,this._workCell);const I=this._workCell.getChars().length;this._workCell.getWidth()===0?($++,F--):I>1&&(A+=I-1,U-=I-1),U--,F--}for(;z1&&(M+=I-1,K+=I-1),K++,z++}}K++;let O=U+q-$+A,W=Math.min(this._bufferService.cols,K-U+$+R-A-M);if(N||B.slice(U,K).trim()!==""){if(E&&O===0&&P.getCodePoint(0)!==32){const F=T.lines.get(x[1]-1);if(F&&P.isWrapped&&F.getCodePoint(this._bufferService.cols-1)!==32){const z=this._getWordAt([this._bufferService.cols-1,x[1]-1],!1,!0,!1);if(z){const X=this._bufferService.cols-z.start;O-=X,W+=X}}}if(L&&O+W===this._bufferService.cols&&P.getCodePoint(this._bufferService.cols-1)!==32){const F=T.lines.get(x[1]+1);if(F!=null&&F.isWrapped&&F.getCodePoint(0)!==32){const z=this._getWordAt([0,x[1]+1],!1,!1,!0);z&&(W+=z.length)}}return{start:O,length:W}}}_selectWordAt(x,N){const E=this._getWordAt(x,N);if(E){for(;E.start<0;)E.start+=this._bufferService.cols,x[1]--;this._model.selectionStart=[E.start,x[1]],this._model.selectionStartLength=E.length}}_selectToWordAt(x){const N=this._getWordAt(x,!0);if(N){let E=x[1];for(;N.start<0;)N.start+=this._bufferService.cols,E--;if(!this._model.areSelectionValuesReversed())for(;N.start+N.length>this._bufferService.cols;)N.length-=this._bufferService.cols,E++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?N.start:N.start+N.length,E]}}_isCharWordSeparator(x){return x.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(x.getChars())>=0}_selectLineAt(x){const N=this._bufferService.buffer.getWrappedRangeForLine(x),E={start:{x:0,y:N.first},end:{x:this._bufferService.cols-1,y:N.last}};this._model.selectionStart=[0,N.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,a.getRangeLength)(E,this._bufferService.cols)}};o.SelectionService=k=d([m(3,_.IBufferService),m(4,_.ICoreService),m(5,S.IMouseService),m(6,_.IOptionsService),m(7,S.IRenderService),m(8,S.ICoreBrowserService)],k)},4725:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ILinkProviderService=o.IThemeService=o.ICharacterJoinerService=o.ISelectionService=o.IRenderService=o.IMouseService=o.ICoreBrowserService=o.ICharSizeService=void 0;const d=u(8343);o.ICharSizeService=(0,d.createDecorator)("CharSizeService"),o.ICoreBrowserService=(0,d.createDecorator)("CoreBrowserService"),o.IMouseService=(0,d.createDecorator)("MouseService"),o.IRenderService=(0,d.createDecorator)("RenderService"),o.ISelectionService=(0,d.createDecorator)("SelectionService"),o.ICharacterJoinerService=(0,d.createDecorator)("CharacterJoinerService"),o.IThemeService=(0,d.createDecorator)("ThemeService"),o.ILinkProviderService=(0,d.createDecorator)("LinkProviderService")},6731:function(y,o,u){var d=this&&this.__decorate||function(k,x,N,E){var L,T=arguments.length,P=T<3?x:E===null?E=Object.getOwnPropertyDescriptor(x,N):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(k,x,N,E);else for(var B=k.length-1;B>=0;B--)(L=k[B])&&(P=(T<3?L(P):T>3?L(x,N,P):L(x,N))||P);return T>3&&P&&Object.defineProperty(x,N,P),P},m=this&&this.__param||function(k,x){return function(N,E){x(N,E,k)}};Object.defineProperty(o,"__esModule",{value:!0}),o.ThemeService=o.DEFAULT_ANSI_COLORS=void 0;const f=u(7239),g=u(8055),w=u(8460),S=u(844),v=u(2585),p=g.css.toColor("#ffffff"),c=g.css.toColor("#000000"),a=g.css.toColor("#ffffff"),l=g.css.toColor("#000000"),_={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};o.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const k=[g.css.toColor("#2e3436"),g.css.toColor("#cc0000"),g.css.toColor("#4e9a06"),g.css.toColor("#c4a000"),g.css.toColor("#3465a4"),g.css.toColor("#75507b"),g.css.toColor("#06989a"),g.css.toColor("#d3d7cf"),g.css.toColor("#555753"),g.css.toColor("#ef2929"),g.css.toColor("#8ae234"),g.css.toColor("#fce94f"),g.css.toColor("#729fcf"),g.css.toColor("#ad7fa8"),g.css.toColor("#34e2e2"),g.css.toColor("#eeeeec")],x=[0,95,135,175,215,255];for(let N=0;N<216;N++){const E=x[N/36%6|0],L=x[N/6%6|0],T=x[N%6];k.push({css:g.channels.toCss(E,L,T),rgba:g.channels.toRgba(E,L,T)})}for(let N=0;N<24;N++){const E=8+10*N;k.push({css:g.channels.toCss(E,E,E),rgba:g.channels.toRgba(E,E,E)})}return k})());let j=o.ThemeService=class extends S.Disposable{get colors(){return this._colors}constructor(k){super(),this._optionsService=k,this._contrastCache=new f.ColorContrastCache,this._halfContrastCache=new f.ColorContrastCache,this._onChangeColors=this.register(new w.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:p,background:c,cursor:a,cursorAccent:l,selectionForeground:void 0,selectionBackgroundTransparent:_,selectionBackgroundOpaque:g.color.blend(c,_),selectionInactiveBackgroundTransparent:_,selectionInactiveBackgroundOpaque:g.color.blend(c,_),ansi:o.DEFAULT_ANSI_COLORS.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)))}_setTheme(k={}){const x=this._colors;if(x.foreground=b(k.foreground,p),x.background=b(k.background,c),x.cursor=b(k.cursor,a),x.cursorAccent=b(k.cursorAccent,l),x.selectionBackgroundTransparent=b(k.selectionBackground,_),x.selectionBackgroundOpaque=g.color.blend(x.background,x.selectionBackgroundTransparent),x.selectionInactiveBackgroundTransparent=b(k.selectionInactiveBackground,x.selectionBackgroundTransparent),x.selectionInactiveBackgroundOpaque=g.color.blend(x.background,x.selectionInactiveBackgroundTransparent),x.selectionForeground=k.selectionForeground?b(k.selectionForeground,g.NULL_COLOR):void 0,x.selectionForeground===g.NULL_COLOR&&(x.selectionForeground=void 0),g.color.isOpaque(x.selectionBackgroundTransparent)&&(x.selectionBackgroundTransparent=g.color.opacity(x.selectionBackgroundTransparent,.3)),g.color.isOpaque(x.selectionInactiveBackgroundTransparent)&&(x.selectionInactiveBackgroundTransparent=g.color.opacity(x.selectionInactiveBackgroundTransparent,.3)),x.ansi=o.DEFAULT_ANSI_COLORS.slice(),x.ansi[0]=b(k.black,o.DEFAULT_ANSI_COLORS[0]),x.ansi[1]=b(k.red,o.DEFAULT_ANSI_COLORS[1]),x.ansi[2]=b(k.green,o.DEFAULT_ANSI_COLORS[2]),x.ansi[3]=b(k.yellow,o.DEFAULT_ANSI_COLORS[3]),x.ansi[4]=b(k.blue,o.DEFAULT_ANSI_COLORS[4]),x.ansi[5]=b(k.magenta,o.DEFAULT_ANSI_COLORS[5]),x.ansi[6]=b(k.cyan,o.DEFAULT_ANSI_COLORS[6]),x.ansi[7]=b(k.white,o.DEFAULT_ANSI_COLORS[7]),x.ansi[8]=b(k.brightBlack,o.DEFAULT_ANSI_COLORS[8]),x.ansi[9]=b(k.brightRed,o.DEFAULT_ANSI_COLORS[9]),x.ansi[10]=b(k.brightGreen,o.DEFAULT_ANSI_COLORS[10]),x.ansi[11]=b(k.brightYellow,o.DEFAULT_ANSI_COLORS[11]),x.ansi[12]=b(k.brightBlue,o.DEFAULT_ANSI_COLORS[12]),x.ansi[13]=b(k.brightMagenta,o.DEFAULT_ANSI_COLORS[13]),x.ansi[14]=b(k.brightCyan,o.DEFAULT_ANSI_COLORS[14]),x.ansi[15]=b(k.brightWhite,o.DEFAULT_ANSI_COLORS[15]),k.extendedAnsi){const N=Math.min(x.ansi.length-16,k.extendedAnsi.length);for(let E=0;E{Object.defineProperty(o,"__esModule",{value:!0}),o.CircularList=void 0;const d=u(8460),m=u(844);class f extends m.Disposable{constructor(w){super(),this._maxLength=w,this.onDeleteEmitter=this.register(new d.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new d.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new d.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(w){if(this._maxLength===w)return;const S=new Array(w);for(let v=0;vthis._length)for(let S=this._length;S=w;p--)this._array[this._getCyclicIndex(p+v.length)]=this._array[this._getCyclicIndex(p)];for(let p=0;pthis._maxLength){const p=this._length+v.length-this._maxLength;this._startIndex+=p,this._length=this._maxLength,this.onTrimEmitter.fire(p)}else this._length+=v.length}trimStart(w){w>this._length&&(w=this._length),this._startIndex+=w,this._length-=w,this.onTrimEmitter.fire(w)}shiftElements(w,S,v){if(!(S<=0)){if(w<0||w>=this._length)throw new Error("start argument out of range");if(w+v<0)throw new Error("Cannot shift elements in list beyond index 0");if(v>0){for(let c=S-1;c>=0;c--)this.set(w+c+v,this.get(w+c));const p=w+S+v-this._length;if(p>0)for(this._length+=p;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let p=0;p{Object.defineProperty(o,"__esModule",{value:!0}),o.clone=void 0,o.clone=function u(d,m=5){if(typeof d!="object")return d;const f=Array.isArray(d)?[]:{};for(const g in d)f[g]=m<=1?d[g]:d[g]&&u(d[g],m-1);return f}},8055:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.contrastRatio=o.toPaddedHex=o.rgba=o.rgb=o.css=o.color=o.channels=o.NULL_COLOR=void 0;let u=0,d=0,m=0,f=0;var g,w,S,v,p;function c(l){const _=l.toString(16);return _.length<2?"0"+_:_}function a(l,_){return l<_?(_+.05)/(l+.05):(l+.05)/(_+.05)}o.NULL_COLOR={css:"#00000000",rgba:0},function(l){l.toCss=function(_,j,b,k){return k!==void 0?`#${c(_)}${c(j)}${c(b)}${c(k)}`:`#${c(_)}${c(j)}${c(b)}`},l.toRgba=function(_,j,b,k=255){return(_<<24|j<<16|b<<8|k)>>>0},l.toColor=function(_,j,b,k){return{css:l.toCss(_,j,b,k),rgba:l.toRgba(_,j,b,k)}}}(g||(o.channels=g={})),function(l){function _(j,b){return f=Math.round(255*b),[u,d,m]=p.toChannels(j.rgba),{css:g.toCss(u,d,m,f),rgba:g.toRgba(u,d,m,f)}}l.blend=function(j,b){if(f=(255&b.rgba)/255,f===1)return{css:b.css,rgba:b.rgba};const k=b.rgba>>24&255,x=b.rgba>>16&255,N=b.rgba>>8&255,E=j.rgba>>24&255,L=j.rgba>>16&255,T=j.rgba>>8&255;return u=E+Math.round((k-E)*f),d=L+Math.round((x-L)*f),m=T+Math.round((N-T)*f),{css:g.toCss(u,d,m),rgba:g.toRgba(u,d,m)}},l.isOpaque=function(j){return(255&j.rgba)==255},l.ensureContrastRatio=function(j,b,k){const x=p.ensureContrastRatio(j.rgba,b.rgba,k);if(x)return g.toColor(x>>24&255,x>>16&255,x>>8&255)},l.opaque=function(j){const b=(255|j.rgba)>>>0;return[u,d,m]=p.toChannels(b),{css:g.toCss(u,d,m),rgba:b}},l.opacity=_,l.multiplyOpacity=function(j,b){return f=255&j.rgba,_(j,f*b/255)},l.toColorRGB=function(j){return[j.rgba>>24&255,j.rgba>>16&255,j.rgba>>8&255]}}(w||(o.color=w={})),function(l){let _,j;try{const b=document.createElement("canvas");b.width=1,b.height=1;const k=b.getContext("2d",{willReadFrequently:!0});k&&(_=k,_.globalCompositeOperation="copy",j=_.createLinearGradient(0,0,1,1))}catch{}l.toColor=function(b){if(b.match(/#[\da-f]{3,8}/i))switch(b.length){case 4:return u=parseInt(b.slice(1,2).repeat(2),16),d=parseInt(b.slice(2,3).repeat(2),16),m=parseInt(b.slice(3,4).repeat(2),16),g.toColor(u,d,m);case 5:return u=parseInt(b.slice(1,2).repeat(2),16),d=parseInt(b.slice(2,3).repeat(2),16),m=parseInt(b.slice(3,4).repeat(2),16),f=parseInt(b.slice(4,5).repeat(2),16),g.toColor(u,d,m,f);case 7:return{css:b,rgba:(parseInt(b.slice(1),16)<<8|255)>>>0};case 9:return{css:b,rgba:parseInt(b.slice(1),16)>>>0}}const k=b.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(k)return u=parseInt(k[1]),d=parseInt(k[2]),m=parseInt(k[3]),f=Math.round(255*(k[5]===void 0?1:parseFloat(k[5]))),g.toColor(u,d,m,f);if(!_||!j)throw new Error("css.toColor: Unsupported css format");if(_.fillStyle=j,_.fillStyle=b,typeof _.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(_.fillRect(0,0,1,1),[u,d,m,f]=_.getImageData(0,0,1,1).data,f!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(u,d,m,f),css:b}}}(S||(o.css=S={})),function(l){function _(j,b,k){const x=j/255,N=b/255,E=k/255;return .2126*(x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4))+.7152*(N<=.03928?N/12.92:Math.pow((N+.055)/1.055,2.4))+.0722*(E<=.03928?E/12.92:Math.pow((E+.055)/1.055,2.4))}l.relativeLuminance=function(j){return _(j>>16&255,j>>8&255,255&j)},l.relativeLuminance2=_}(v||(o.rgb=v={})),function(l){function _(b,k,x){const N=b>>24&255,E=b>>16&255,L=b>>8&255;let T=k>>24&255,P=k>>16&255,B=k>>8&255,U=a(v.relativeLuminance2(T,P,B),v.relativeLuminance2(N,E,L));for(;U0||P>0||B>0);)T-=Math.max(0,Math.ceil(.1*T)),P-=Math.max(0,Math.ceil(.1*P)),B-=Math.max(0,Math.ceil(.1*B)),U=a(v.relativeLuminance2(T,P,B),v.relativeLuminance2(N,E,L));return(T<<24|P<<16|B<<8|255)>>>0}function j(b,k,x){const N=b>>24&255,E=b>>16&255,L=b>>8&255;let T=k>>24&255,P=k>>16&255,B=k>>8&255,U=a(v.relativeLuminance2(T,P,B),v.relativeLuminance2(N,E,L));for(;U>>0}l.blend=function(b,k){if(f=(255&k)/255,f===1)return k;const x=k>>24&255,N=k>>16&255,E=k>>8&255,L=b>>24&255,T=b>>16&255,P=b>>8&255;return u=L+Math.round((x-L)*f),d=T+Math.round((N-T)*f),m=P+Math.round((E-P)*f),g.toRgba(u,d,m)},l.ensureContrastRatio=function(b,k,x){const N=v.relativeLuminance(b>>8),E=v.relativeLuminance(k>>8);if(a(N,E)>8));if(Ba(N,v.relativeLuminance(U>>8))?P:U}return P}const L=j(b,k,x),T=a(N,v.relativeLuminance(L>>8));if(Ta(N,v.relativeLuminance(P>>8))?L:P}return L}},l.reduceLuminance=_,l.increaseLuminance=j,l.toChannels=function(b){return[b>>24&255,b>>16&255,b>>8&255,255&b]}}(p||(o.rgba=p={})),o.toPaddedHex=c,o.contrastRatio=a},8969:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreTerminal=void 0;const d=u(844),m=u(2585),f=u(4348),g=u(7866),w=u(744),S=u(7302),v=u(6975),p=u(8460),c=u(1753),a=u(1480),l=u(7994),_=u(9282),j=u(5435),b=u(5981),k=u(2660);let x=!1;class N extends d.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new p.EventEmitter),this._onScroll.event(L=>{var T;(T=this._onScrollApi)==null||T.fire(L.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(L){for(const T in L)this.optionsService.options[T]=L[T]}constructor(L){super(),this._windowsWrappingHeuristics=this.register(new d.MutableDisposable),this._onBinary=this.register(new p.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new p.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new p.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new p.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new p.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new p.EventEmitter),this._instantiationService=new f.InstantiationService,this.optionsService=this.register(new S.OptionsService(L)),this._instantiationService.setService(m.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(w.BufferService)),this._instantiationService.setService(m.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(g.LogService)),this._instantiationService.setService(m.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(v.CoreService)),this._instantiationService.setService(m.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(c.CoreMouseService)),this._instantiationService.setService(m.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(a.UnicodeService)),this._instantiationService.setService(m.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(l.CharsetService),this._instantiationService.setService(m.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(k.OscLinkService),this._instantiationService.setService(m.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new j.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,p.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,p.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,p.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,p.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(T=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(T=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new b.WriteBuffer((T,P)=>this._inputHandler.parse(T,P))),this.register((0,p.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(L,T){this._writeBuffer.write(L,T)}writeSync(L,T){this._logService.logLevel<=m.LogLevelEnum.WARN&&!x&&(this._logService.warn("writeSync is unreliable and will be removed soon."),x=!0),this._writeBuffer.writeSync(L,T)}input(L,T=!0){this.coreService.triggerDataEvent(L,T)}resize(L,T){isNaN(L)||isNaN(T)||(L=Math.max(L,w.MINIMUM_COLS),T=Math.max(T,w.MINIMUM_ROWS),this._bufferService.resize(L,T))}scroll(L,T=!1){this._bufferService.scroll(L,T)}scrollLines(L,T,P){this._bufferService.scrollLines(L,T,P)}scrollPages(L){this.scrollLines(L*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(L){const T=L-this._bufferService.buffer.ydisp;T!==0&&this.scrollLines(T)}registerEscHandler(L,T){return this._inputHandler.registerEscHandler(L,T)}registerDcsHandler(L,T){return this._inputHandler.registerDcsHandler(L,T)}registerCsiHandler(L,T){return this._inputHandler.registerCsiHandler(L,T)}registerOscHandler(L,T){return this._inputHandler.registerOscHandler(L,T)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let L=!1;const T=this.optionsService.rawOptions.windowsPty;T&&T.buildNumber!==void 0&&T.buildNumber!==void 0?L=T.backend==="conpty"&&T.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(L=!0),L?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const L=[];L.push(this.onLineFeed(_.updateWindowsModeWrappedState.bind(null,this._bufferService))),L.push(this.registerCsiHandler({final:"H"},()=>((0,_.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,d.toDisposable)(()=>{for(const T of L)T.dispose()})}}}o.CoreTerminal=N},8460:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.runAndSubscribe=o.forwardEvent=o.EventEmitter=void 0,o.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=u=>(this._listeners.push(u),{dispose:()=>{if(!this._disposed){for(let d=0;dd.fire(m))},o.runAndSubscribe=function(u,d){return d(void 0),u(m=>d(m))}},5435:function(y,o,u){var d=this&&this.__decorate||function($,R,A,M){var O,W=arguments.length,F=W<3?R:M===null?M=Object.getOwnPropertyDescriptor(R,A):M;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")F=Reflect.decorate($,R,A,M);else for(var z=$.length-1;z>=0;z--)(O=$[z])&&(F=(W<3?O(F):W>3?O(R,A,F):O(R,A))||F);return W>3&&F&&Object.defineProperty(R,A,F),F},m=this&&this.__param||function($,R){return function(A,M){R(A,M,$)}};Object.defineProperty(o,"__esModule",{value:!0}),o.InputHandler=o.WindowsOptionsReportType=void 0;const f=u(2584),g=u(7116),w=u(2015),S=u(844),v=u(482),p=u(8437),c=u(8460),a=u(643),l=u(511),_=u(3734),j=u(2585),b=u(1480),k=u(6242),x=u(6351),N=u(5941),E={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function T($,R){if($>24)return R.setWinLines||!1;switch($){case 1:return!!R.restoreWin;case 2:return!!R.minimizeWin;case 3:return!!R.setWinPosition;case 4:return!!R.setWinSizePixels;case 5:return!!R.raiseWin;case 6:return!!R.lowerWin;case 7:return!!R.refreshWin;case 8:return!!R.setWinSizeChars;case 9:return!!R.maximizeWin;case 10:return!!R.fullscreenWin;case 11:return!!R.getWinState;case 13:return!!R.getWinPosition;case 14:return!!R.getWinSizePixels;case 15:return!!R.getScreenSizePixels;case 16:return!!R.getCellSizePixels;case 18:return!!R.getWinSizeChars;case 19:return!!R.getScreenSizeChars;case 20:return!!R.getIconTitle;case 21:return!!R.getWinTitle;case 22:return!!R.pushTitle;case 23:return!!R.popTitle;case 24:return!!R.setWinLines}return!1}var P;(function($){$[$.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",$[$.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(P||(o.WindowsOptionsReportType=P={}));let B=0;class U extends S.Disposable{getAttrData(){return this._curAttrData}constructor(R,A,M,O,W,F,z,X,I=new w.EscapeSequenceParser){super(),this._bufferService=R,this._charsetService=A,this._coreService=M,this._logService=O,this._optionsService=W,this._oscLinkService=F,this._coreMouseService=z,this._unicodeService=X,this._parser=I,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new v.StringToUtf32,this._utf8Decoder=new v.Utf8ToUtf32,this._workCell=new l.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=p.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=p.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new c.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new c.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new c.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new c.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new c.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new c.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new c.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new c.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new c.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new c.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new c.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new c.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new c.EventEmitter),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 K(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(D=>this._activeBuffer=D.activeBuffer)),this._parser.setCsiHandlerFallback((D,V)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(D),params:V.toArray()})}),this._parser.setEscHandlerFallback(D=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(D)})}),this._parser.setExecuteHandlerFallback(D=>{this._logService.debug("Unknown EXECUTE code: ",{code:D})}),this._parser.setOscHandlerFallback((D,V,H)=>{this._logService.debug("Unknown OSC code: ",{identifier:D,action:V,data:H})}),this._parser.setDcsHandlerFallback((D,V,H)=>{V==="HOOK"&&(H=H.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(D),action:V,payload:H})}),this._parser.setPrintHandler((D,V,H)=>this.print(D,V,H)),this._parser.registerCsiHandler({final:"@"},D=>this.insertChars(D)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},D=>this.scrollLeft(D)),this._parser.registerCsiHandler({final:"A"},D=>this.cursorUp(D)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},D=>this.scrollRight(D)),this._parser.registerCsiHandler({final:"B"},D=>this.cursorDown(D)),this._parser.registerCsiHandler({final:"C"},D=>this.cursorForward(D)),this._parser.registerCsiHandler({final:"D"},D=>this.cursorBackward(D)),this._parser.registerCsiHandler({final:"E"},D=>this.cursorNextLine(D)),this._parser.registerCsiHandler({final:"F"},D=>this.cursorPrecedingLine(D)),this._parser.registerCsiHandler({final:"G"},D=>this.cursorCharAbsolute(D)),this._parser.registerCsiHandler({final:"H"},D=>this.cursorPosition(D)),this._parser.registerCsiHandler({final:"I"},D=>this.cursorForwardTab(D)),this._parser.registerCsiHandler({final:"J"},D=>this.eraseInDisplay(D,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},D=>this.eraseInDisplay(D,!0)),this._parser.registerCsiHandler({final:"K"},D=>this.eraseInLine(D,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},D=>this.eraseInLine(D,!0)),this._parser.registerCsiHandler({final:"L"},D=>this.insertLines(D)),this._parser.registerCsiHandler({final:"M"},D=>this.deleteLines(D)),this._parser.registerCsiHandler({final:"P"},D=>this.deleteChars(D)),this._parser.registerCsiHandler({final:"S"},D=>this.scrollUp(D)),this._parser.registerCsiHandler({final:"T"},D=>this.scrollDown(D)),this._parser.registerCsiHandler({final:"X"},D=>this.eraseChars(D)),this._parser.registerCsiHandler({final:"Z"},D=>this.cursorBackwardTab(D)),this._parser.registerCsiHandler({final:"`"},D=>this.charPosAbsolute(D)),this._parser.registerCsiHandler({final:"a"},D=>this.hPositionRelative(D)),this._parser.registerCsiHandler({final:"b"},D=>this.repeatPrecedingCharacter(D)),this._parser.registerCsiHandler({final:"c"},D=>this.sendDeviceAttributesPrimary(D)),this._parser.registerCsiHandler({prefix:">",final:"c"},D=>this.sendDeviceAttributesSecondary(D)),this._parser.registerCsiHandler({final:"d"},D=>this.linePosAbsolute(D)),this._parser.registerCsiHandler({final:"e"},D=>this.vPositionRelative(D)),this._parser.registerCsiHandler({final:"f"},D=>this.hVPosition(D)),this._parser.registerCsiHandler({final:"g"},D=>this.tabClear(D)),this._parser.registerCsiHandler({final:"h"},D=>this.setMode(D)),this._parser.registerCsiHandler({prefix:"?",final:"h"},D=>this.setModePrivate(D)),this._parser.registerCsiHandler({final:"l"},D=>this.resetMode(D)),this._parser.registerCsiHandler({prefix:"?",final:"l"},D=>this.resetModePrivate(D)),this._parser.registerCsiHandler({final:"m"},D=>this.charAttributes(D)),this._parser.registerCsiHandler({final:"n"},D=>this.deviceStatus(D)),this._parser.registerCsiHandler({prefix:"?",final:"n"},D=>this.deviceStatusPrivate(D)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},D=>this.softReset(D)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},D=>this.setCursorStyle(D)),this._parser.registerCsiHandler({final:"r"},D=>this.setScrollRegion(D)),this._parser.registerCsiHandler({final:"s"},D=>this.saveCursor(D)),this._parser.registerCsiHandler({final:"t"},D=>this.windowOptions(D)),this._parser.registerCsiHandler({final:"u"},D=>this.restoreCursor(D)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},D=>this.insertColumns(D)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},D=>this.deleteColumns(D)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},D=>this.selectProtected(D)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},D=>this.requestMode(D,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},D=>this.requestMode(D,!1)),this._parser.setExecuteHandler(f.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(f.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(f.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(f.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(f.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(f.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(f.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(f.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(f.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(f.C1.IND,()=>this.index()),this._parser.setExecuteHandler(f.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(f.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new k.OscHandler(D=>(this.setTitle(D),this.setIconName(D),!0))),this._parser.registerOscHandler(1,new k.OscHandler(D=>this.setIconName(D))),this._parser.registerOscHandler(2,new k.OscHandler(D=>this.setTitle(D))),this._parser.registerOscHandler(4,new k.OscHandler(D=>this.setOrReportIndexedColor(D))),this._parser.registerOscHandler(8,new k.OscHandler(D=>this.setHyperlink(D))),this._parser.registerOscHandler(10,new k.OscHandler(D=>this.setOrReportFgColor(D))),this._parser.registerOscHandler(11,new k.OscHandler(D=>this.setOrReportBgColor(D))),this._parser.registerOscHandler(12,new k.OscHandler(D=>this.setOrReportCursorColor(D))),this._parser.registerOscHandler(104,new k.OscHandler(D=>this.restoreIndexedColor(D))),this._parser.registerOscHandler(110,new k.OscHandler(D=>this.restoreFgColor(D))),this._parser.registerOscHandler(111,new k.OscHandler(D=>this.restoreBgColor(D))),this._parser.registerOscHandler(112,new k.OscHandler(D=>this.restoreCursorColor(D))),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(const D in g.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:D},()=>this.selectCharset("("+D)),this._parser.registerEscHandler({intermediates:")",final:D},()=>this.selectCharset(")"+D)),this._parser.registerEscHandler({intermediates:"*",final:D},()=>this.selectCharset("*"+D)),this._parser.registerEscHandler({intermediates:"+",final:D},()=>this.selectCharset("+"+D)),this._parser.registerEscHandler({intermediates:"-",final:D},()=>this.selectCharset("-"+D)),this._parser.registerEscHandler({intermediates:".",final:D},()=>this.selectCharset("."+D)),this._parser.registerEscHandler({intermediates:"/",final:D},()=>this.selectCharset("/"+D));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(D=>(this._logService.error("Parsing error: ",D),D)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new x.DcsHandler((D,V)=>this.requestStatusString(D,V)))}_preserveStack(R,A,M,O){this._parseStack.paused=!0,this._parseStack.cursorStartX=R,this._parseStack.cursorStartY=A,this._parseStack.decodedLength=M,this._parseStack.position=O}_logSlowResolvingAsync(R){this._logService.logLevel<=j.LogLevelEnum.WARN&&Promise.race([R,new Promise((A,M)=>setTimeout(()=>M("#SLOW_TIMEOUT"),5e3))]).catch(A=>{if(A!=="#SLOW_TIMEOUT")throw A;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(R,A){let M,O=this._activeBuffer.x,W=this._activeBuffer.y,F=0;const z=this._parseStack.paused;if(z){if(M=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,A))return this._logSlowResolvingAsync(M),M;O=this._parseStack.cursorStartX,W=this._parseStack.cursorStartY,this._parseStack.paused=!1,R.length>L&&(F=this._parseStack.position+L)}if(this._logService.logLevel<=j.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof R=="string"?` "${R}"`:` "${Array.prototype.map.call(R,D=>String.fromCharCode(D)).join("")}"`),typeof R=="string"?R.split("").map(D=>D.charCodeAt(0)):R),this._parseBuffer.lengthL)for(let D=F;D0&&H.getWidth(this._activeBuffer.x-1)===2&&H.setCellFromCodepoint(this._activeBuffer.x-1,0,1,V);let J=this._parser.precedingJoinState;for(let Q=A;QX){if(I){const Ce=H;let ae=this._activeBuffer.x-he;for(this._activeBuffer.x=he,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),H=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),he>0&&H instanceof p.BufferLine&&H.copyCellsFrom(Ce,ae,0,he,!1);ae=0;)H.setCellFromCodepoint(this._activeBuffer.x++,0,0,V)}else if(D&&(H.insertCells(this._activeBuffer.x,W-he,this._activeBuffer.getNullCell(V)),H.getWidth(X-1)===2&&H.setCellFromCodepoint(X-1,a.NULL_CELL_CODE,a.NULL_CELL_WIDTH,V)),H.setCellFromCodepoint(this._activeBuffer.x++,O,W,V),W>0)for(;--W;)H.setCellFromCodepoint(this._activeBuffer.x++,0,0,V)}this._parser.precedingJoinState=J,this._activeBuffer.x0&&H.getWidth(this._activeBuffer.x)===0&&!H.hasContent(this._activeBuffer.x)&&H.setCellFromCodepoint(this._activeBuffer.x,0,1,V),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(R,A){return R.final!=="t"||R.prefix||R.intermediates?this._parser.registerCsiHandler(R,A):this._parser.registerCsiHandler(R,M=>!T(M.params[0],this._optionsService.rawOptions.windowOptions)||A(M))}registerDcsHandler(R,A){return this._parser.registerDcsHandler(R,new x.DcsHandler(A))}registerEscHandler(R,A){return this._parser.registerEscHandler(R,A)}registerOscHandler(R,A){return this._parser.registerOscHandler(R,new k.OscHandler(A))}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(){var R;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&&((R=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&R.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const A=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);A.hasWidth(this._activeBuffer.x)&&!A.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const R=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-R),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(R=this._bufferService.cols-1){this._activeBuffer.x=Math.min(R,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(R,A){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=R,this._activeBuffer.y=this._activeBuffer.scrollTop+A):(this._activeBuffer.x=R,this._activeBuffer.y=A),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(R,A){this._restrictCursor(),this._setCursor(this._activeBuffer.x+R,this._activeBuffer.y+A)}cursorUp(R){const A=this._activeBuffer.y-this._activeBuffer.scrollTop;return A>=0?this._moveCursor(0,-Math.min(A,R.params[0]||1)):this._moveCursor(0,-(R.params[0]||1)),!0}cursorDown(R){const A=this._activeBuffer.scrollBottom-this._activeBuffer.y;return A>=0?this._moveCursor(0,Math.min(A,R.params[0]||1)):this._moveCursor(0,R.params[0]||1),!0}cursorForward(R){return this._moveCursor(R.params[0]||1,0),!0}cursorBackward(R){return this._moveCursor(-(R.params[0]||1),0),!0}cursorNextLine(R){return this.cursorDown(R),this._activeBuffer.x=0,!0}cursorPrecedingLine(R){return this.cursorUp(R),this._activeBuffer.x=0,!0}cursorCharAbsolute(R){return this._setCursor((R.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(R){return this._setCursor(R.length>=2?(R.params[1]||1)-1:0,(R.params[0]||1)-1),!0}charPosAbsolute(R){return this._setCursor((R.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(R){return this._moveCursor(R.params[0]||1,0),!0}linePosAbsolute(R){return this._setCursor(this._activeBuffer.x,(R.params[0]||1)-1),!0}vPositionRelative(R){return this._moveCursor(0,R.params[0]||1),!0}hVPosition(R){return this.cursorPosition(R),!0}tabClear(R){const A=R.params[0];return A===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:A===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(R){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let A=R.params[0]||1;for(;A--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(R){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let A=R.params[0]||1;for(;A--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(R){const A=R.params[0];return A===1&&(this._curAttrData.bg|=536870912),A!==2&&A!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(R,A,M,O=!1,W=!1){const F=this._activeBuffer.lines.get(this._activeBuffer.ybase+R);F.replaceCells(A,M,this._activeBuffer.getNullCell(this._eraseAttrData()),W),O&&(F.isWrapped=!1)}_resetBufferLine(R,A=!1){const M=this._activeBuffer.lines.get(this._activeBuffer.ybase+R);M&&(M.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),A),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+R),M.isWrapped=!1)}eraseInDisplay(R,A=!1){let M;switch(this._restrictCursor(this._bufferService.cols),R.params[0]){case 0:for(M=this._activeBuffer.y,this._dirtyRowTracker.markDirty(M),this._eraseInBufferLine(M++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,A);M=this._bufferService.cols&&(this._activeBuffer.lines.get(M+1).isWrapped=!1);M--;)this._resetBufferLine(M,A);this._dirtyRowTracker.markDirty(0);break;case 2:for(M=this._bufferService.rows,this._dirtyRowTracker.markDirty(M-1);M--;)this._resetBufferLine(M,A);this._dirtyRowTracker.markDirty(0);break;case 3:const O=this._activeBuffer.lines.length-this._bufferService.rows;O>0&&(this._activeBuffer.lines.trimStart(O),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-O,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-O,0),this._onScroll.fire(0))}return!0}eraseInLine(R,A=!1){switch(this._restrictCursor(this._bufferService.cols),R.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,A);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,A);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,A)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(R){this._restrictCursor();let A=R.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 I=X;for(let D=1;D0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(f.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(f.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(R){return R.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(f.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(f.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(R.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(f.C0.ESC+"[>83;40003;0c")),!0}_is(R){return(this._optionsService.rawOptions.termName+"").indexOf(R)===0}setMode(R){for(let A=0;Aie?1:2,J=R.params[0];return Q=J,re=A?J===2?4:J===4?H(F.modes.insertMode):J===12?3:J===20?H(V.convertEol):0:J===1?H(M.applicationCursorKeys):J===3?V.windowOptions.setWinLines?X===80?2:X===132?1:0:0:J===6?H(M.origin):J===7?H(M.wraparound):J===8?3:J===9?H(O==="X10"):J===12?H(V.cursorBlink):J===25?H(!F.isCursorHidden):J===45?H(M.reverseWraparound):J===66?H(M.applicationKeypad):J===67?4:J===1e3?H(O==="VT200"):J===1002?H(O==="DRAG"):J===1003?H(O==="ANY"):J===1004?H(M.sendFocus):J===1005?4:J===1006?H(W==="SGR"):J===1015?4:J===1016?H(W==="SGR_PIXELS"):J===1048?1:J===47||J===1047||J===1049?H(I===D):J===2004?H(M.bracketedPasteMode):0,F.triggerDataEvent(`${f.C0.ESC}[${A?"":"?"}${Q};${re}$y`),!0;var Q,re}_updateAttrColor(R,A,M,O,W){return A===2?(R|=50331648,R&=-16777216,R|=_.AttributeData.fromColorRGB([M,O,W])):A===5&&(R&=-50331904,R|=33554432|255&M),R}_extractColor(R,A,M){const O=[0,0,-1,0,0,0];let W=0,F=0;do{if(O[F+W]=R.params[A+F],R.hasSubParams(A+F)){const z=R.getSubParams(A+F);let X=0;do O[1]===5&&(W=1),O[F+X+1+W]=z[X];while(++X=2||O[1]===2&&F+W>=5)break;O[1]&&(W=1)}while(++F+A5)&&(R=1),A.extended.underlineStyle=R,A.fg|=268435456,R===0&&(A.fg&=-268435457),A.updateExtended()}_processSGR0(R){R.fg=p.DEFAULT_ATTR_DATA.fg,R.bg=p.DEFAULT_ATTR_DATA.bg,R.extended=R.extended.clone(),R.extended.underlineStyle=0,R.extended.underlineColor&=-67108864,R.updateExtended()}charAttributes(R){if(R.length===1&&R.params[0]===0)return this._processSGR0(this._curAttrData),!0;const A=R.length;let M;const O=this._curAttrData;for(let W=0;W=30&&M<=37?(O.fg&=-50331904,O.fg|=16777216|M-30):M>=40&&M<=47?(O.bg&=-50331904,O.bg|=16777216|M-40):M>=90&&M<=97?(O.fg&=-50331904,O.fg|=16777224|M-90):M>=100&&M<=107?(O.bg&=-50331904,O.bg|=16777224|M-100):M===0?this._processSGR0(O):M===1?O.fg|=134217728:M===3?O.bg|=67108864:M===4?(O.fg|=268435456,this._processUnderline(R.hasSubParams(W)?R.getSubParams(W)[0]:1,O)):M===5?O.fg|=536870912:M===7?O.fg|=67108864:M===8?O.fg|=1073741824:M===9?O.fg|=2147483648:M===2?O.bg|=134217728:M===21?this._processUnderline(2,O):M===22?(O.fg&=-134217729,O.bg&=-134217729):M===23?O.bg&=-67108865:M===24?(O.fg&=-268435457,this._processUnderline(0,O)):M===25?O.fg&=-536870913:M===27?O.fg&=-67108865:M===28?O.fg&=-1073741825:M===29?O.fg&=2147483647:M===39?(O.fg&=-67108864,O.fg|=16777215&p.DEFAULT_ATTR_DATA.fg):M===49?(O.bg&=-67108864,O.bg|=16777215&p.DEFAULT_ATTR_DATA.bg):M===38||M===48||M===58?W+=this._extractColor(R,W,O):M===53?O.bg|=1073741824:M===55?O.bg&=-1073741825:M===59?(O.extended=O.extended.clone(),O.extended.underlineColor=-1,O.updateExtended()):M===100?(O.fg&=-67108864,O.fg|=16777215&p.DEFAULT_ATTR_DATA.fg,O.bg&=-67108864,O.bg|=16777215&p.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",M);return!0}deviceStatus(R){switch(R.params[0]){case 5:this._coreService.triggerDataEvent(`${f.C0.ESC}[0n`);break;case 6:const A=this._activeBuffer.y+1,M=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${f.C0.ESC}[${A};${M}R`)}return!0}deviceStatusPrivate(R){if(R.params[0]===6){const A=this._activeBuffer.y+1,M=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${f.C0.ESC}[?${A};${M}R`)}return!0}softReset(R){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=p.DEFAULT_ATTR_DATA.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(R){const A=R.params[0]||1;switch(A){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const M=A%2==1;return this._optionsService.options.cursorBlink=M,!0}setScrollRegion(R){const A=R.params[0]||1;let M;return(R.length<2||(M=R.params[1])>this._bufferService.rows||M===0)&&(M=this._bufferService.rows),M>A&&(this._activeBuffer.scrollTop=A-1,this._activeBuffer.scrollBottom=M-1,this._setCursor(0,0)),!0}windowOptions(R){if(!T(R.params[0],this._optionsService.rawOptions.windowOptions))return!0;const A=R.length>1?R.params[1]:0;switch(R.params[0]){case 14:A!==2&&this._onRequestWindowsOptionsReport.fire(P.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(P.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${f.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:A!==0&&A!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),A!==0&&A!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:A!==0&&A!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),A!==0&&A!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(R){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(R){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(R){return this._windowTitle=R,this._onTitleChange.fire(R),!0}setIconName(R){return this._iconName=R,!0}setOrReportIndexedColor(R){const A=[],M=R.split(";");for(;M.length>1;){const O=M.shift(),W=M.shift();if(/^\d+$/.exec(O)){const F=parseInt(O);if(q(F))if(W==="?")A.push({type:0,index:F});else{const z=(0,N.parseColor)(W);z&&A.push({type:1,index:F,color:z})}}}return A.length&&this._onColor.fire(A),!0}setHyperlink(R){const A=R.split(";");return!(A.length<2)&&(A[1]?this._createHyperlink(A[0],A[1]):!A[0]&&this._finishHyperlink())}_createHyperlink(R,A){this._getCurrentLinkId()&&this._finishHyperlink();const M=R.split(":");let O;const W=M.findIndex(F=>F.startsWith("id="));return W!==-1&&(O=M[W].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:O,uri:A}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(R,A){const M=R.split(";");for(let O=0;O=this._specialColors.length);++O,++A)if(M[O]==="?")this._onColor.fire([{type:0,index:this._specialColors[A]}]);else{const W=(0,N.parseColor)(M[O]);W&&this._onColor.fire([{type:1,index:this._specialColors[A],color:W}])}return!0}setOrReportFgColor(R){return this._setOrReportSpecialColor(R,0)}setOrReportBgColor(R){return this._setOrReportSpecialColor(R,1)}setOrReportCursorColor(R){return this._setOrReportSpecialColor(R,2)}restoreIndexedColor(R){if(!R)return this._onColor.fire([{type:2}]),!0;const A=[],M=R.split(";");for(let O=0;O=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){const R=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,R,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=p.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=p.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(R){return this._charsetService.setgLevel(R),!0}screenAlignmentPattern(){const R=new l.CellData;R.content=4194373,R.fg=this._curAttrData.fg,R.bg=this._curAttrData.bg,this._setCursor(0,0);for(let A=0;A(this._coreService.triggerDataEvent(`${f.C0.ESC}${W}${f.C0.ESC}\\`),!0))(R==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:R==='"p'?'P1$r61;1"p':R==="r"?`P1$r${M.scrollTop+1};${M.scrollBottom+1}r`:R==="m"?"P1$r0m":R===" q"?`P1$r${{block:2,underline:4,bar:6}[O.cursorStyle]-(O.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(R,A){this._dirtyRowTracker.markRangeDirty(R,A)}}o.InputHandler=U;let K=class{constructor($){this._bufferService=$,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty($){$this.end&&(this.end=$)}markRangeDirty($,R){$>R&&(B=$,$=R,R=B),$this.end&&(this.end=R)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function q($){return 0<=$&&$<256}K=d([m(0,j.IBufferService)],K)},844:(y,o)=>{function u(d){for(const m of d)m.dispose();d.length=0}Object.defineProperty(o,"__esModule",{value:!0}),o.getDisposeArrayDisposable=o.disposeArray=o.toDisposable=o.MutableDisposable=o.Disposable=void 0,o.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const d of this._disposables)d.dispose();this._disposables.length=0}register(d){return this._disposables.push(d),d}unregister(d){const m=this._disposables.indexOf(d);m!==-1&&this._disposables.splice(m,1)}},o.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(d){var m;this._isDisposed||d===this._value||((m=this._value)==null||m.dispose(),this._value=d)}clear(){this.value=void 0}dispose(){var d;this._isDisposed=!0,(d=this._value)==null||d.dispose(),this._value=void 0}},o.toDisposable=function(d){return{dispose:d}},o.disposeArray=u,o.getDisposeArrayDisposable=function(d){return{dispose:()=>u(d)}}},1505:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.FourKeyMap=o.TwoKeyMap=void 0;class u{constructor(){this._data={}}set(m,f,g){this._data[m]||(this._data[m]={}),this._data[m][f]=g}get(m,f){return this._data[m]?this._data[m][f]:void 0}clear(){this._data={}}}o.TwoKeyMap=u,o.FourKeyMap=class{constructor(){this._data=new u}set(d,m,f,g,w){this._data.get(d,m)||this._data.set(d,m,new u),this._data.get(d,m).set(f,g,w)}get(d,m,f,g){var w;return(w=this._data.get(d,m))==null?void 0:w.get(f,g)}clear(){this._data.clear()}}},6114:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.isChromeOS=o.isLinux=o.isWindows=o.isIphone=o.isIpad=o.isMac=o.getSafariVersion=o.isSafari=o.isLegacyEdge=o.isFirefox=o.isNode=void 0,o.isNode=typeof process<"u"&&"title"in process;const u=o.isNode?"node":navigator.userAgent,d=o.isNode?"node":navigator.platform;o.isFirefox=u.includes("Firefox"),o.isLegacyEdge=u.includes("Edge"),o.isSafari=/^((?!chrome|android).)*safari/i.test(u),o.getSafariVersion=function(){if(!o.isSafari)return 0;const m=u.match(/Version\/(\d+)/);return m===null||m.length<2?0:parseInt(m[1])},o.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(d),o.isIpad=d==="iPad",o.isIphone=d==="iPhone",o.isWindows=["Windows","Win16","Win32","WinCE"].includes(d),o.isLinux=d.indexOf("Linux")>=0,o.isChromeOS=/\bCrOS\b/.test(u)},6106:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SortedList=void 0;let u=0;o.SortedList=class{constructor(d){this._getKey=d,this._array=[]}clear(){this._array.length=0}insert(d){this._array.length!==0?(u=this._search(this._getKey(d)),this._array.splice(u,0,d)):this._array.push(d)}delete(d){if(this._array.length===0)return!1;const m=this._getKey(d);if(m===void 0||(u=this._search(m),u===-1)||this._getKey(this._array[u])!==m)return!1;do if(this._array[u]===d)return this._array.splice(u,1),!0;while(++u=this._array.length)&&this._getKey(this._array[u])===d))do yield this._array[u];while(++u=this._array.length)&&this._getKey(this._array[u])===d))do m(this._array[u]);while(++u=m;){let g=m+f>>1;const w=this._getKey(this._array[g]);if(w>d)f=g-1;else{if(!(w0&&this._getKey(this._array[g-1])===d;)g--;return g}m=g+1}}return m}}},7226:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DebouncedIdleTask=o.IdleTaskQueue=o.PriorityTaskQueue=void 0;const d=u(6114);class m{constructor(){this._tasks=[],this._i=0}enqueue(w){this._tasks.push(w),this._start()}flush(){for(;this._ic)return p-S<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(p-S))}ms`),void this._start();p=c}this.clear()}}class f extends m{_requestCallback(w){return setTimeout(()=>w(this._createDeadline(16)))}_cancelCallback(w){clearTimeout(w)}_createDeadline(w){const S=Date.now()+w;return{timeRemaining:()=>Math.max(0,S-Date.now())}}}o.PriorityTaskQueue=f,o.IdleTaskQueue=!d.isNode&&"requestIdleCallback"in window?class extends m{_requestCallback(g){return requestIdleCallback(g)}_cancelCallback(g){cancelIdleCallback(g)}}:f,o.DebouncedIdleTask=class{constructor(){this._queue=new o.IdleTaskQueue}set(g){this._queue.clear(),this._queue.enqueue(g)}flush(){this._queue.flush()}}},9282:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.updateWindowsModeWrappedState=void 0;const d=u(643);o.updateWindowsModeWrappedState=function(m){const f=m.buffer.lines.get(m.buffer.ybase+m.buffer.y-1),g=f==null?void 0:f.get(m.cols-1),w=m.buffer.lines.get(m.buffer.ybase+m.buffer.y);w&&g&&(w.isWrapped=g[d.CHAR_DATA_CODE_INDEX]!==d.NULL_CELL_CODE&&g[d.CHAR_DATA_CODE_INDEX]!==d.WHITESPACE_CELL_CODE)}},3734:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ExtendedAttrs=o.AttributeData=void 0;class u{constructor(){this.fg=0,this.bg=0,this.extended=new d}static toColorRGB(f){return[f>>>16&255,f>>>8&255,255&f]}static fromColorRGB(f){return(255&f[0])<<16|(255&f[1])<<8|255&f[2]}clone(){const f=new u;return f.fg=this.fg,f.bg=this.bg,f.extended=this.extended.clone(),f}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}o.AttributeData=u;class d{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(f){this._ext=f}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(f){this._ext&=-469762049,this._ext|=f<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(f){this._ext&=-67108864,this._ext|=67108863&f}get urlId(){return this._urlId}set urlId(f){this._urlId=f}get underlineVariantOffset(){const f=(3758096384&this._ext)>>29;return f<0?4294967288^f:f}set underlineVariantOffset(f){this._ext&=536870911,this._ext|=f<<29&3758096384}constructor(f=0,g=0){this._ext=0,this._urlId=0,this._ext=f,this._urlId=g}clone(){return new d(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}o.ExtendedAttrs=d},9092:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Buffer=o.MAX_BUFFER_SIZE=void 0;const d=u(6349),m=u(7226),f=u(3734),g=u(8437),w=u(4634),S=u(511),v=u(643),p=u(4863),c=u(7116);o.MAX_BUFFER_SIZE=4294967295,o.Buffer=class{constructor(a,l,_){this._hasScrollback=a,this._optionsService=l,this._bufferService=_,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=g.DEFAULT_ATTR_DATA.clone(),this.savedCharset=c.DEFAULT_CHARSET,this.markers=[],this._nullCell=S.CellData.fromCharData([0,v.NULL_CELL_CHAR,v.NULL_CELL_WIDTH,v.NULL_CELL_CODE]),this._whitespaceCell=S.CellData.fromCharData([0,v.WHITESPACE_CELL_CHAR,v.WHITESPACE_CELL_WIDTH,v.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new m.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new d.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(a){return a?(this._nullCell.fg=a.fg,this._nullCell.bg=a.bg,this._nullCell.extended=a.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new f.ExtendedAttrs),this._nullCell}getWhitespaceCell(a){return a?(this._whitespaceCell.fg=a.fg,this._whitespaceCell.bg=a.bg,this._whitespaceCell.extended=a.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new f.ExtendedAttrs),this._whitespaceCell}getBlankLine(a,l){return new g.BufferLine(this._bufferService.cols,this.getNullCell(a),l)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const a=this.ybase+this.y-this.ydisp;return a>=0&&ao.MAX_BUFFER_SIZE?o.MAX_BUFFER_SIZE:l}fillViewportRows(a){if(this.lines.length===0){a===void 0&&(a=g.DEFAULT_ATTR_DATA);let l=this._rows;for(;l--;)this.lines.push(this.getBlankLine(a))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new d.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(a,l){const _=this.getNullCell(g.DEFAULT_ATTR_DATA);let j=0;const b=this._getCorrectBufferLength(l);if(b>this.lines.maxLength&&(this.lines.maxLength=b),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new g.BufferLine(a,_)));else for(let x=this._rows;x>l;x--)this.lines.length>l+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(b0&&(this.lines.trimStart(x),this.ybase=Math.max(this.ybase-x,0),this.ydisp=Math.max(this.ydisp-x,0),this.savedY=Math.max(this.savedY-x,0)),this.lines.maxLength=b}this.x=Math.min(this.x,a-1),this.y=Math.min(this.y,l-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,a-1),this.scrollTop=0}if(this.scrollBottom=l-1,this._isReflowEnabled&&(this._reflow(a,l),this._cols>a))for(let k=0;k.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let a=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,a=!1);let l=0;for(;this._memoryCleanupPosition100)return!0;return a}get _isReflowEnabled(){const a=this._optionsService.rawOptions.windowsPty;return a&&a.buildNumber?this._hasScrollback&&a.backend==="conpty"&&a.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(a,l){this._cols!==a&&(a>this._cols?this._reflowLarger(a,l):this._reflowSmaller(a,l))}_reflowLarger(a,l){const _=(0,w.reflowLargerGetLinesToRemove)(this.lines,this._cols,a,this.ybase+this.y,this.getNullCell(g.DEFAULT_ATTR_DATA));if(_.length>0){const j=(0,w.reflowLargerCreateNewLayout)(this.lines,_);(0,w.reflowLargerApplyNewLayout)(this.lines,j.layout),this._reflowLargerAdjustViewport(a,l,j.countRemoved)}}_reflowLargerAdjustViewport(a,l,_){const j=this.getNullCell(g.DEFAULT_ATTR_DATA);let b=_;for(;b-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;k--){let x=this.lines.get(k);if(!x||!x.isWrapped&&x.getTrimmedLength()<=a)continue;const N=[x];for(;x.isWrapped&&k>0;)x=this.lines.get(--k),N.unshift(x);const E=this.ybase+this.y;if(E>=k&&E0&&(j.push({start:k+N.length+b,newLines:U}),b+=U.length),N.push(...U);let K=T.length-1,q=T[K];q===0&&(K--,q=T[K]);let $=N.length-P-1,R=L;for(;$>=0;){const M=Math.min(R,q);if(N[K]===void 0)break;if(N[K].copyCellsFrom(N[$],R-M,q-M,M,!0),q-=M,q===0&&(K--,q=T[K]),R-=M,R===0){$--;const O=Math.max($,0);R=(0,w.getWrappedLineTrimmedLength)(N,O,this._cols)}}for(let M=0;M0;)this.ybase===0?this.y0){const k=[],x=[];for(let K=0;K=0;K--)if(T&&T.start>E+P){for(let q=T.newLines.length-1;q>=0;q--)this.lines.set(K--,T.newLines[q]);K++,k.push({index:E+1,amount:T.newLines.length}),P+=T.newLines.length,T=j[++L]}else this.lines.set(K,x[E--]);let B=0;for(let K=k.length-1;K>=0;K--)k[K].index+=B,this.lines.onInsertEmitter.fire(k[K]),B+=k[K].amount;const U=Math.max(0,N+b-this.lines.maxLength);U>0&&this.lines.onTrimEmitter.fire(U)}}translateBufferLineToString(a,l,_=0,j){const b=this.lines.get(a);return b?b.translateToString(l,_,j):""}getWrappedRangeForLine(a){let l=a,_=a;for(;l>0&&this.lines.get(l).isWrapped;)l--;for(;_+10;);return a>=this._cols?this._cols-1:a<0?0:a}nextStop(a){for(a==null&&(a=this.x);!this.tabs[++a]&&a=this._cols?this._cols-1:a<0?0:a}clearMarkers(a){this._isClearing=!0;for(let l=0;l{l.line-=_,l.line<0&&l.dispose()})),l.register(this.lines.onInsert(_=>{l.line>=_.index&&(l.line+=_.amount)})),l.register(this.lines.onDelete(_=>{l.line>=_.index&&l.line<_.index+_.amount&&l.dispose(),l.line>_.index&&(l.line-=_.amount)})),l.register(l.onDispose(()=>this._removeMarker(l))),l}_removeMarker(a){this._isClearing||this.markers.splice(this.markers.indexOf(a),1)}}},8437:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLine=o.DEFAULT_ATTR_DATA=void 0;const d=u(3734),m=u(511),f=u(643),g=u(482);o.DEFAULT_ATTR_DATA=Object.freeze(new d.AttributeData);let w=0;class S{constructor(p,c,a=!1){this.isWrapped=a,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*p);const l=c||m.CellData.fromCharData([0,f.NULL_CELL_CHAR,f.NULL_CELL_WIDTH,f.NULL_CELL_CODE]);for(let _=0;_>22,2097152&c?this._combined[p].charCodeAt(this._combined[p].length-1):a]}set(p,c){this._data[3*p+1]=c[f.CHAR_DATA_ATTR_INDEX],c[f.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[p]=c[1],this._data[3*p+0]=2097152|p|c[f.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*p+0]=c[f.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|c[f.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(p){return this._data[3*p+0]>>22}hasWidth(p){return 12582912&this._data[3*p+0]}getFg(p){return this._data[3*p+1]}getBg(p){return this._data[3*p+2]}hasContent(p){return 4194303&this._data[3*p+0]}getCodePoint(p){const c=this._data[3*p+0];return 2097152&c?this._combined[p].charCodeAt(this._combined[p].length-1):2097151&c}isCombined(p){return 2097152&this._data[3*p+0]}getString(p){const c=this._data[3*p+0];return 2097152&c?this._combined[p]:2097151&c?(0,g.stringFromCodePoint)(2097151&c):""}isProtected(p){return 536870912&this._data[3*p+2]}loadCell(p,c){return w=3*p,c.content=this._data[w+0],c.fg=this._data[w+1],c.bg=this._data[w+2],2097152&c.content&&(c.combinedData=this._combined[p]),268435456&c.bg&&(c.extended=this._extendedAttrs[p]),c}setCell(p,c){2097152&c.content&&(this._combined[p]=c.combinedData),268435456&c.bg&&(this._extendedAttrs[p]=c.extended),this._data[3*p+0]=c.content,this._data[3*p+1]=c.fg,this._data[3*p+2]=c.bg}setCellFromCodepoint(p,c,a,l){268435456&l.bg&&(this._extendedAttrs[p]=l.extended),this._data[3*p+0]=c|a<<22,this._data[3*p+1]=l.fg,this._data[3*p+2]=l.bg}addCodepointToCell(p,c,a){let l=this._data[3*p+0];2097152&l?this._combined[p]+=(0,g.stringFromCodePoint)(c):2097151&l?(this._combined[p]=(0,g.stringFromCodePoint)(2097151&l)+(0,g.stringFromCodePoint)(c),l&=-2097152,l|=2097152):l=c|4194304,a&&(l&=-12582913,l|=a<<22),this._data[3*p+0]=l}insertCells(p,c,a){if((p%=this.length)&&this.getWidth(p-1)===2&&this.setCellFromCodepoint(p-1,0,1,a),c=0;--_)this.setCell(p+c+_,this.loadCell(p+_,l));for(let _=0;_this.length){if(this._data.buffer.byteLength>=4*a)this._data=new Uint32Array(this._data.buffer,0,a);else{const l=new Uint32Array(a);l.set(this._data),this._data=l}for(let l=this.length;l=p&&delete this._combined[b]}const _=Object.keys(this._extendedAttrs);for(let j=0;j<_.length;j++){const b=parseInt(_[j],10);b>=p&&delete this._extendedAttrs[b]}}return this.length=p,4*a*2=0;--p)if(4194303&this._data[3*p+0])return p+(this._data[3*p+0]>>22);return 0}getNoBgTrimmedLength(){for(let p=this.length-1;p>=0;--p)if(4194303&this._data[3*p+0]||50331648&this._data[3*p+2])return p+(this._data[3*p+0]>>22);return 0}copyCellsFrom(p,c,a,l,_){const j=p._data;if(_)for(let k=l-1;k>=0;k--){for(let x=0;x<3;x++)this._data[3*(a+k)+x]=j[3*(c+k)+x];268435456&j[3*(c+k)+2]&&(this._extendedAttrs[a+k]=p._extendedAttrs[c+k])}else for(let k=0;k=c&&(this._combined[x-c+a]=p._combined[x])}}translateToString(p,c,a,l){c=c??0,a=a??this.length,p&&(a=Math.min(a,this.getTrimmedLength())),l&&(l.length=0);let _="";for(;c>22||1}return l&&l.push(c),_}}o.BufferLine=S},4841:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.getRangeLength=void 0,o.getRangeLength=function(u,d){if(u.start.y>u.end.y)throw new Error(`Buffer range end (${u.end.x}, ${u.end.y}) cannot be before start (${u.start.x}, ${u.start.y})`);return d*(u.end.y-u.start.y)+(u.end.x-u.start.x+1)}},4634:(y,o)=>{function u(d,m,f){if(m===d.length-1)return d[m].getTrimmedLength();const g=!d[m].hasContent(f-1)&&d[m].getWidth(f-1)===1,w=d[m+1].getWidth(0)===2;return g&&w?f-1:f}Object.defineProperty(o,"__esModule",{value:!0}),o.getWrappedLineTrimmedLength=o.reflowSmallerGetNewLineLengths=o.reflowLargerApplyNewLayout=o.reflowLargerCreateNewLayout=o.reflowLargerGetLinesToRemove=void 0,o.reflowLargerGetLinesToRemove=function(d,m,f,g,w){const S=[];for(let v=0;v=v&&g0&&(x>l||a[x].getTrimmedLength()===0);x--)k++;k>0&&(S.push(v+a.length-k),S.push(k)),v+=a.length-1}return S},o.reflowLargerCreateNewLayout=function(d,m){const f=[];let g=0,w=m[g],S=0;for(let v=0;vu(d,a,m)).reduce((c,a)=>c+a);let S=0,v=0,p=0;for(;pc&&(S-=c,v++);const a=d[v].getWidth(S-1)===2;a&&S--;const l=a?f-1:f;g.push(l),p+=l}return g},o.getWrappedLineTrimmedLength=u},5295:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferSet=void 0;const d=u(8460),m=u(844),f=u(9092);class g extends m.Disposable{constructor(S,v){super(),this._optionsService=S,this._bufferService=v,this._onBufferActivate=this.register(new d.EventEmitter),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 f.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new f.Buffer(!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(S){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(S),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(S,v){this._normal.resize(S,v),this._alt.resize(S,v),this.setupTabStops(S)}setupTabStops(S){this._normal.setupTabStops(S),this._alt.setupTabStops(S)}}o.BufferSet=g},511:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CellData=void 0;const d=u(482),m=u(643),f=u(3734);class g extends f.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new f.ExtendedAttrs,this.combinedData=""}static fromCharData(S){const v=new g;return v.setFromCharData(S),v}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,d.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(S){this.fg=S[m.CHAR_DATA_ATTR_INDEX],this.bg=0;let v=!1;if(S[m.CHAR_DATA_CHAR_INDEX].length>2)v=!0;else if(S[m.CHAR_DATA_CHAR_INDEX].length===2){const p=S[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=p&&p<=56319){const c=S[m.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=c&&c<=57343?this.content=1024*(p-55296)+c-56320+65536|S[m.CHAR_DATA_WIDTH_INDEX]<<22:v=!0}else v=!0}else this.content=S[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|S[m.CHAR_DATA_WIDTH_INDEX]<<22;v&&(this.combinedData=S[m.CHAR_DATA_CHAR_INDEX],this.content=2097152|S[m.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.CellData=g},643:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WHITESPACE_CELL_CODE=o.WHITESPACE_CELL_WIDTH=o.WHITESPACE_CELL_CHAR=o.NULL_CELL_CODE=o.NULL_CELL_WIDTH=o.NULL_CELL_CHAR=o.CHAR_DATA_CODE_INDEX=o.CHAR_DATA_WIDTH_INDEX=o.CHAR_DATA_CHAR_INDEX=o.CHAR_DATA_ATTR_INDEX=o.DEFAULT_EXT=o.DEFAULT_ATTR=o.DEFAULT_COLOR=void 0,o.DEFAULT_COLOR=0,o.DEFAULT_ATTR=256|o.DEFAULT_COLOR<<9,o.DEFAULT_EXT=0,o.CHAR_DATA_ATTR_INDEX=0,o.CHAR_DATA_CHAR_INDEX=1,o.CHAR_DATA_WIDTH_INDEX=2,o.CHAR_DATA_CODE_INDEX=3,o.NULL_CELL_CHAR="",o.NULL_CELL_WIDTH=1,o.NULL_CELL_CODE=0,o.WHITESPACE_CELL_CHAR=" ",o.WHITESPACE_CELL_WIDTH=1,o.WHITESPACE_CELL_CODE=32},4863:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Marker=void 0;const d=u(8460),m=u(844);class f{get id(){return this._id}constructor(w){this.line=w,this.isDisposed=!1,this._disposables=[],this._id=f._nextId++,this._onDispose=this.register(new d.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,m.disposeArray)(this._disposables),this._disposables.length=0)}register(w){return this._disposables.push(w),w}}o.Marker=f,f._nextId=1},7116:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DEFAULT_CHARSET=o.CHARSETS=void 0,o.CHARSETS={},o.DEFAULT_CHARSET=o.CHARSETS.B,o.CHARSETS[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:"≥","{":"π","|":"≠","}":"£","~":"·"},o.CHARSETS.A={"#":"£"},o.CHARSETS.B=void 0,o.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},o.CHARSETS.C=o.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},o.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},o.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},o.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},o.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},o.CHARSETS.E=o.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},o.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},o.CHARSETS.H=o.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},o.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(y,o)=>{var u,d,m;Object.defineProperty(o,"__esModule",{value:!0}),o.C1_ESCAPED=o.C1=o.C0=void 0,function(f){f.NUL="\0",f.SOH="",f.STX="",f.ETX="",f.EOT="",f.ENQ="",f.ACK="",f.BEL="\x07",f.BS="\b",f.HT=" ",f.LF=` +`,f.VT="\v",f.FF="\f",f.CR="\r",f.SO="",f.SI="",f.DLE="",f.DC1="",f.DC2="",f.DC3="",f.DC4="",f.NAK="",f.SYN="",f.ETB="",f.CAN="",f.EM="",f.SUB="",f.ESC="\x1B",f.FS="",f.GS="",f.RS="",f.US="",f.SP=" ",f.DEL=""}(u||(o.C0=u={})),function(f){f.PAD="€",f.HOP="",f.BPH="‚",f.NBH="ƒ",f.IND="„",f.NEL="…",f.SSA="†",f.ESA="‡",f.HTS="ˆ",f.HTJ="‰",f.VTS="Š",f.PLD="‹",f.PLU="Œ",f.RI="",f.SS2="Ž",f.SS3="",f.DCS="",f.PU1="‘",f.PU2="’",f.STS="“",f.CCH="”",f.MW="•",f.SPA="–",f.EPA="—",f.SOS="˜",f.SGCI="™",f.SCI="š",f.CSI="›",f.ST="œ",f.OSC="",f.PM="ž",f.APC="Ÿ"}(d||(o.C1=d={})),function(f){f.ST=`${u.ESC}\\`}(m||(o.C1_ESCAPED=m={}))},7399:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.evaluateKeyboardEvent=void 0;const d=u(2584),m={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:["'",'"']};o.evaluateKeyboardEvent=function(f,g,w,S){const v={type:0,cancel:!1,key:void 0},p=(f.shiftKey?1:0)|(f.altKey?2:0)|(f.ctrlKey?4:0)|(f.metaKey?8:0);switch(f.keyCode){case 0:f.key==="UIKeyInputUpArrow"?v.key=g?d.C0.ESC+"OA":d.C0.ESC+"[A":f.key==="UIKeyInputLeftArrow"?v.key=g?d.C0.ESC+"OD":d.C0.ESC+"[D":f.key==="UIKeyInputRightArrow"?v.key=g?d.C0.ESC+"OC":d.C0.ESC+"[C":f.key==="UIKeyInputDownArrow"&&(v.key=g?d.C0.ESC+"OB":d.C0.ESC+"[B");break;case 8:v.key=f.ctrlKey?"\b":d.C0.DEL,f.altKey&&(v.key=d.C0.ESC+v.key);break;case 9:if(f.shiftKey){v.key=d.C0.ESC+"[Z";break}v.key=d.C0.HT,v.cancel=!0;break;case 13:v.key=f.altKey?d.C0.ESC+d.C0.CR:d.C0.CR,v.cancel=!0;break;case 27:v.key=d.C0.ESC,f.altKey&&(v.key=d.C0.ESC+d.C0.ESC),v.cancel=!0;break;case 37:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"D",v.key===d.C0.ESC+"[1;3D"&&(v.key=d.C0.ESC+(w?"b":"[1;5D"))):v.key=g?d.C0.ESC+"OD":d.C0.ESC+"[D";break;case 39:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"C",v.key===d.C0.ESC+"[1;3C"&&(v.key=d.C0.ESC+(w?"f":"[1;5C"))):v.key=g?d.C0.ESC+"OC":d.C0.ESC+"[C";break;case 38:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"A",w||v.key!==d.C0.ESC+"[1;3A"||(v.key=d.C0.ESC+"[1;5A")):v.key=g?d.C0.ESC+"OA":d.C0.ESC+"[A";break;case 40:if(f.metaKey)break;p?(v.key=d.C0.ESC+"[1;"+(p+1)+"B",w||v.key!==d.C0.ESC+"[1;3B"||(v.key=d.C0.ESC+"[1;5B")):v.key=g?d.C0.ESC+"OB":d.C0.ESC+"[B";break;case 45:f.shiftKey||f.ctrlKey||(v.key=d.C0.ESC+"[2~");break;case 46:v.key=p?d.C0.ESC+"[3;"+(p+1)+"~":d.C0.ESC+"[3~";break;case 36:v.key=p?d.C0.ESC+"[1;"+(p+1)+"H":g?d.C0.ESC+"OH":d.C0.ESC+"[H";break;case 35:v.key=p?d.C0.ESC+"[1;"+(p+1)+"F":g?d.C0.ESC+"OF":d.C0.ESC+"[F";break;case 33:f.shiftKey?v.type=2:f.ctrlKey?v.key=d.C0.ESC+"[5;"+(p+1)+"~":v.key=d.C0.ESC+"[5~";break;case 34:f.shiftKey?v.type=3:f.ctrlKey?v.key=d.C0.ESC+"[6;"+(p+1)+"~":v.key=d.C0.ESC+"[6~";break;case 112:v.key=p?d.C0.ESC+"[1;"+(p+1)+"P":d.C0.ESC+"OP";break;case 113:v.key=p?d.C0.ESC+"[1;"+(p+1)+"Q":d.C0.ESC+"OQ";break;case 114:v.key=p?d.C0.ESC+"[1;"+(p+1)+"R":d.C0.ESC+"OR";break;case 115:v.key=p?d.C0.ESC+"[1;"+(p+1)+"S":d.C0.ESC+"OS";break;case 116:v.key=p?d.C0.ESC+"[15;"+(p+1)+"~":d.C0.ESC+"[15~";break;case 117:v.key=p?d.C0.ESC+"[17;"+(p+1)+"~":d.C0.ESC+"[17~";break;case 118:v.key=p?d.C0.ESC+"[18;"+(p+1)+"~":d.C0.ESC+"[18~";break;case 119:v.key=p?d.C0.ESC+"[19;"+(p+1)+"~":d.C0.ESC+"[19~";break;case 120:v.key=p?d.C0.ESC+"[20;"+(p+1)+"~":d.C0.ESC+"[20~";break;case 121:v.key=p?d.C0.ESC+"[21;"+(p+1)+"~":d.C0.ESC+"[21~";break;case 122:v.key=p?d.C0.ESC+"[23;"+(p+1)+"~":d.C0.ESC+"[23~";break;case 123:v.key=p?d.C0.ESC+"[24;"+(p+1)+"~":d.C0.ESC+"[24~";break;default:if(!f.ctrlKey||f.shiftKey||f.altKey||f.metaKey)if(w&&!S||!f.altKey||f.metaKey)!w||f.altKey||f.ctrlKey||f.shiftKey||!f.metaKey?f.key&&!f.ctrlKey&&!f.altKey&&!f.metaKey&&f.keyCode>=48&&f.key.length===1?v.key=f.key:f.key&&f.ctrlKey&&(f.key==="_"&&(v.key=d.C0.US),f.key==="@"&&(v.key=d.C0.NUL)):f.keyCode===65&&(v.type=1);else{const c=m[f.keyCode],a=c==null?void 0:c[f.shiftKey?1:0];if(a)v.key=d.C0.ESC+a;else if(f.keyCode>=65&&f.keyCode<=90){const l=f.ctrlKey?f.keyCode-64:f.keyCode+32;let _=String.fromCharCode(l);f.shiftKey&&(_=_.toUpperCase()),v.key=d.C0.ESC+_}else if(f.keyCode===32)v.key=d.C0.ESC+(f.ctrlKey?d.C0.NUL:" ");else if(f.key==="Dead"&&f.code.startsWith("Key")){let l=f.code.slice(3,4);f.shiftKey||(l=l.toLowerCase()),v.key=d.C0.ESC+l,v.cancel=!0}}else f.keyCode>=65&&f.keyCode<=90?v.key=String.fromCharCode(f.keyCode-64):f.keyCode===32?v.key=d.C0.NUL:f.keyCode>=51&&f.keyCode<=55?v.key=String.fromCharCode(f.keyCode-51+27):f.keyCode===56?v.key=d.C0.DEL:f.keyCode===219?v.key=d.C0.ESC:f.keyCode===220?v.key=d.C0.FS:f.keyCode===221&&(v.key=d.C0.GS)}return v}},482:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Utf8ToUtf32=o.StringToUtf32=o.utf32ToString=o.stringFromCodePoint=void 0,o.stringFromCodePoint=function(u){return u>65535?(u-=65536,String.fromCharCode(55296+(u>>10))+String.fromCharCode(u%1024+56320)):String.fromCharCode(u)},o.utf32ToString=function(u,d=0,m=u.length){let f="";for(let g=d;g65535?(w-=65536,f+=String.fromCharCode(55296+(w>>10))+String.fromCharCode(w%1024+56320)):f+=String.fromCharCode(w)}return f},o.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(u,d){const m=u.length;if(!m)return 0;let f=0,g=0;if(this._interim){const w=u.charCodeAt(g++);56320<=w&&w<=57343?d[f++]=1024*(this._interim-55296)+w-56320+65536:(d[f++]=this._interim,d[f++]=w),this._interim=0}for(let w=g;w=m)return this._interim=S,f;const v=u.charCodeAt(w);56320<=v&&v<=57343?d[f++]=1024*(S-55296)+v-56320+65536:(d[f++]=S,d[f++]=v)}else S!==65279&&(d[f++]=S)}return f}},o.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(u,d){const m=u.length;if(!m)return 0;let f,g,w,S,v=0,p=0,c=0;if(this.interim[0]){let _=!1,j=this.interim[0];j&=(224&j)==192?31:(240&j)==224?15:7;let b,k=0;for(;(b=63&this.interim[++k])&&k<4;)j<<=6,j|=b;const x=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,N=x-k;for(;c=m)return 0;if(b=u[c++],(192&b)!=128){c--,_=!0;break}this.interim[k++]=b,j<<=6,j|=63&b}_||(x===2?j<128?c--:d[v++]=j:x===3?j<2048||j>=55296&&j<=57343||j===65279||(d[v++]=j):j<65536||j>1114111||(d[v++]=j)),this.interim.fill(0)}const a=m-4;let l=c;for(;l=m)return this.interim[0]=f,v;if(g=u[l++],(192&g)!=128){l--;continue}if(p=(31&f)<<6|63&g,p<128){l--;continue}d[v++]=p}else if((240&f)==224){if(l>=m)return this.interim[0]=f,v;if(g=u[l++],(192&g)!=128){l--;continue}if(l>=m)return this.interim[0]=f,this.interim[1]=g,v;if(w=u[l++],(192&w)!=128){l--;continue}if(p=(15&f)<<12|(63&g)<<6|63&w,p<2048||p>=55296&&p<=57343||p===65279)continue;d[v++]=p}else if((248&f)==240){if(l>=m)return this.interim[0]=f,v;if(g=u[l++],(192&g)!=128){l--;continue}if(l>=m)return this.interim[0]=f,this.interim[1]=g,v;if(w=u[l++],(192&w)!=128){l--;continue}if(l>=m)return this.interim[0]=f,this.interim[1]=g,this.interim[2]=w,v;if(S=u[l++],(192&S)!=128){l--;continue}if(p=(7&f)<<18|(63&g)<<12|(63&w)<<6|63&S,p<65536||p>1114111)continue;d[v++]=p}}return v}}},225:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeV6=void 0;const d=u(1480),m=[[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]],f=[[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]];let g;o.UnicodeV6=class{constructor(){if(this.version="6",!g){g=new Uint8Array(65536),g.fill(1),g[0]=0,g.fill(0,1,32),g.fill(0,127,160),g.fill(2,4352,4448),g[9001]=2,g[9002]=2,g.fill(2,11904,42192),g[12351]=1,g.fill(2,44032,55204),g.fill(2,63744,64256),g.fill(2,65040,65050),g.fill(2,65072,65136),g.fill(2,65280,65377),g.fill(2,65504,65511);for(let w=0;wv[a][1])return!1;for(;a>=c;)if(p=c+a>>1,S>v[p][1])c=p+1;else{if(!(S=131072&&w<=196605||w>=196608&&w<=262141?2:1}charProperties(w,S){let v=this.wcwidth(w),p=v===0&&S!==0;if(p){const c=d.UnicodeService.extractWidth(S);c===0?p=!1:c>v&&(v=c)}return d.UnicodeService.createPropertyValue(0,v,p)}}},5981:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WriteBuffer=void 0;const d=u(8460),m=u(844);class f extends m.Disposable{constructor(w){super(),this._action=w,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new d.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(w,S){if(S!==void 0&&this._syncCalls>S)return void(this._syncCalls=0);if(this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let v;for(this._isSyncWriting=!0;v=this._writeBuffer.shift();){this._action(v);const p=this._callbacks.shift();p&&p()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(w,S){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(S),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(S)}_innerWrite(w=0,S=!0){const v=w||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const p=this._writeBuffer[this._bufferOffset],c=this._action(p,S);if(c){const l=_=>Date.now()-v>=12?setTimeout(()=>this._innerWrite(0,_)):this._innerWrite(v,_);return void c.catch(_=>(queueMicrotask(()=>{throw _}),Promise.resolve(!1))).then(l)}const a=this._callbacks[this._bufferOffset];if(a&&a(),this._bufferOffset++,this._pendingData-=p.length,Date.now()-v>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(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()}}o.WriteBuffer=f},5941:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.toRgbString=o.parseColor=void 0;const u=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,d=/^[\da-f]+$/;function m(f,g){const w=f.toString(16),S=w.length<2?"0"+w:w;switch(g){case 4:return w[0];case 8:return S;case 12:return(S+S).slice(0,3);default:return S+S}}o.parseColor=function(f){if(!f)return;let g=f.toLowerCase();if(g.indexOf("rgb:")===0){g=g.slice(4);const w=u.exec(g);if(w){const S=w[1]?15:w[4]?255:w[7]?4095:65535;return[Math.round(parseInt(w[1]||w[4]||w[7]||w[10],16)/S*255),Math.round(parseInt(w[2]||w[5]||w[8]||w[11],16)/S*255),Math.round(parseInt(w[3]||w[6]||w[9]||w[12],16)/S*255)]}}else if(g.indexOf("#")===0&&(g=g.slice(1),d.exec(g)&&[3,6,9,12].includes(g.length))){const w=g.length/3,S=[0,0,0];for(let v=0;v<3;++v){const p=parseInt(g.slice(w*v,w*v+w),16);S[v]=w===1?p<<4:w===2?p:w===3?p>>4:p>>8}return S}},o.toRgbString=function(f,g=16){const[w,S,v]=f;return`rgb:${m(w,g)}/${m(S,g)}/${m(v,g)}`}},5770:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.PAYLOAD_LIMIT=void 0,o.PAYLOAD_LIMIT=1e7},6351:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DcsHandler=o.DcsParser=void 0;const d=u(482),m=u(8742),f=u(5770),g=[];o.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=g,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=g}registerHandler(S,v){this._handlers[S]===void 0&&(this._handlers[S]=[]);const p=this._handlers[S];return p.push(v),{dispose:()=>{const c=p.indexOf(v);c!==-1&&p.splice(c,1)}}}clearHandler(S){this._handlers[S]&&delete this._handlers[S]}setHandlerFallback(S){this._handlerFb=S}reset(){if(this._active.length)for(let S=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;S>=0;--S)this._active[S].unhook(!1);this._stack.paused=!1,this._active=g,this._ident=0}hook(S,v){if(this.reset(),this._ident=S,this._active=this._handlers[S]||g,this._active.length)for(let p=this._active.length-1;p>=0;p--)this._active[p].hook(v);else this._handlerFb(this._ident,"HOOK",v)}put(S,v,p){if(this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].put(S,v,p);else this._handlerFb(this._ident,"PUT",(0,d.utf32ToString)(S,v,p))}unhook(S,v=!0){if(this._active.length){let p=!1,c=this._active.length-1,a=!1;if(this._stack.paused&&(c=this._stack.loopPosition-1,p=v,a=this._stack.fallThrough,this._stack.paused=!1),!a&&p===!1){for(;c>=0&&(p=this._active[c].unhook(S),p!==!0);c--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=c,this._stack.fallThrough=!1,p;c--}for(;c>=0;c--)if(p=this._active[c].unhook(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=c,this._stack.fallThrough=!0,p}else this._handlerFb(this._ident,"UNHOOK",S);this._active=g,this._ident=0}};const w=new m.Params;w.addParam(0),o.DcsHandler=class{constructor(S){this._handler=S,this._data="",this._params=w,this._hitLimit=!1}hook(S){this._params=S.length>1||S.params[0]?S.clone():w,this._data="",this._hitLimit=!1}put(S,v,p){this._hitLimit||(this._data+=(0,d.utf32ToString)(S,v,p),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(S){let v=!1;if(this._hitLimit)v=!1;else if(S&&(v=this._handler(this._data,this._params),v instanceof Promise))return v.then(p=>(this._params=w,this._data="",this._hitLimit=!1,p));return this._params=w,this._data="",this._hitLimit=!1,v}}},2015:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.EscapeSequenceParser=o.VT500_TRANSITION_TABLE=o.TransitionTable=void 0;const d=u(844),m=u(8742),f=u(6242),g=u(6351);class w{constructor(c){this.table=new Uint8Array(c)}setDefault(c,a){this.table.fill(c<<4|a)}add(c,a,l,_){this.table[a<<8|c]=l<<4|_}addMany(c,a,l,_){for(let j=0;jx),a=(k,x)=>c.slice(k,x),l=a(32,127),_=a(0,24);_.push(25),_.push.apply(_,a(28,32));const j=a(0,14);let b;for(b in p.setDefault(1,0),p.addMany(l,0,2,0),j)p.addMany([24,26,153,154],b,3,0),p.addMany(a(128,144),b,3,0),p.addMany(a(144,152),b,3,0),p.add(156,b,0,0),p.add(27,b,11,1),p.add(157,b,4,8),p.addMany([152,158,159],b,0,7),p.add(155,b,11,3),p.add(144,b,11,9);return p.addMany(_,0,3,0),p.addMany(_,1,3,1),p.add(127,1,0,1),p.addMany(_,8,0,8),p.addMany(_,3,3,3),p.add(127,3,0,3),p.addMany(_,4,3,4),p.add(127,4,0,4),p.addMany(_,6,3,6),p.addMany(_,5,3,5),p.add(127,5,0,5),p.addMany(_,2,3,2),p.add(127,2,0,2),p.add(93,1,4,8),p.addMany(l,8,5,8),p.add(127,8,5,8),p.addMany([156,27,24,26,7],8,6,0),p.addMany(a(28,32),8,0,8),p.addMany([88,94,95],1,0,7),p.addMany(l,7,0,7),p.addMany(_,7,0,7),p.add(156,7,0,0),p.add(127,7,0,7),p.add(91,1,11,3),p.addMany(a(64,127),3,7,0),p.addMany(a(48,60),3,8,4),p.addMany([60,61,62,63],3,9,4),p.addMany(a(48,60),4,8,4),p.addMany(a(64,127),4,7,0),p.addMany([60,61,62,63],4,0,6),p.addMany(a(32,64),6,0,6),p.add(127,6,0,6),p.addMany(a(64,127),6,0,0),p.addMany(a(32,48),3,9,5),p.addMany(a(32,48),5,9,5),p.addMany(a(48,64),5,0,6),p.addMany(a(64,127),5,7,0),p.addMany(a(32,48),4,9,5),p.addMany(a(32,48),1,9,2),p.addMany(a(32,48),2,9,2),p.addMany(a(48,127),2,10,0),p.addMany(a(48,80),1,10,0),p.addMany(a(81,88),1,10,0),p.addMany([89,90,92],1,10,0),p.addMany(a(96,127),1,10,0),p.add(80,1,11,9),p.addMany(_,9,0,9),p.add(127,9,0,9),p.addMany(a(28,32),9,0,9),p.addMany(a(32,48),9,9,12),p.addMany(a(48,60),9,8,10),p.addMany([60,61,62,63],9,9,10),p.addMany(_,11,0,11),p.addMany(a(32,128),11,0,11),p.addMany(a(28,32),11,0,11),p.addMany(_,10,0,10),p.add(127,10,0,10),p.addMany(a(28,32),10,0,10),p.addMany(a(48,60),10,8,10),p.addMany([60,61,62,63],10,0,11),p.addMany(a(32,48),10,9,12),p.addMany(_,12,0,12),p.add(127,12,0,12),p.addMany(a(28,32),12,0,12),p.addMany(a(32,48),12,9,12),p.addMany(a(48,64),12,0,11),p.addMany(a(64,127),12,12,13),p.addMany(a(64,127),10,12,13),p.addMany(a(64,127),9,12,13),p.addMany(_,13,13,13),p.addMany(l,13,13,13),p.add(127,13,0,13),p.addMany([27,156,24,26],13,14,0),p.add(S,0,2,0),p.add(S,8,5,8),p.add(S,6,0,6),p.add(S,11,0,11),p.add(S,13,13,13),p}();class v extends d.Disposable{constructor(c=o.VT500_TRANSITION_TABLE){super(),this._transitions=c,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new m.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(a,l,_)=>{},this._executeHandlerFb=a=>{},this._csiHandlerFb=(a,l)=>{},this._escHandlerFb=a=>{},this._errorHandlerFb=a=>a,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,d.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new f.OscParser),this._dcsParser=this.register(new g.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(c,a=[64,126]){let l=0;if(c.prefix){if(c.prefix.length>1)throw new Error("only one byte as prefix supported");if(l=c.prefix.charCodeAt(0),l&&60>l||l>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(c.intermediates){if(c.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let j=0;jb||b>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");l<<=8,l|=b}}if(c.final.length!==1)throw new Error("final must be a single byte");const _=c.final.charCodeAt(0);if(a[0]>_||_>a[1])throw new Error(`final must be in range ${a[0]} .. ${a[1]}`);return l<<=8,l|=_,l}identToString(c){const a=[];for(;c;)a.push(String.fromCharCode(255&c)),c>>=8;return a.reverse().join("")}setPrintHandler(c){this._printHandler=c}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(c,a){const l=this._identifier(c,[48,126]);this._escHandlers[l]===void 0&&(this._escHandlers[l]=[]);const _=this._escHandlers[l];return _.push(a),{dispose:()=>{const j=_.indexOf(a);j!==-1&&_.splice(j,1)}}}clearEscHandler(c){this._escHandlers[this._identifier(c,[48,126])]&&delete this._escHandlers[this._identifier(c,[48,126])]}setEscHandlerFallback(c){this._escHandlerFb=c}setExecuteHandler(c,a){this._executeHandlers[c.charCodeAt(0)]=a}clearExecuteHandler(c){this._executeHandlers[c.charCodeAt(0)]&&delete this._executeHandlers[c.charCodeAt(0)]}setExecuteHandlerFallback(c){this._executeHandlerFb=c}registerCsiHandler(c,a){const l=this._identifier(c);this._csiHandlers[l]===void 0&&(this._csiHandlers[l]=[]);const _=this._csiHandlers[l];return _.push(a),{dispose:()=>{const j=_.indexOf(a);j!==-1&&_.splice(j,1)}}}clearCsiHandler(c){this._csiHandlers[this._identifier(c)]&&delete this._csiHandlers[this._identifier(c)]}setCsiHandlerFallback(c){this._csiHandlerFb=c}registerDcsHandler(c,a){return this._dcsParser.registerHandler(this._identifier(c),a)}clearDcsHandler(c){this._dcsParser.clearHandler(this._identifier(c))}setDcsHandlerFallback(c){this._dcsParser.setHandlerFallback(c)}registerOscHandler(c,a){return this._oscParser.registerHandler(c,a)}clearOscHandler(c){this._oscParser.clearHandler(c)}setOscHandlerFallback(c){this._oscParser.setHandlerFallback(c)}setErrorHandler(c){this._errorHandler=c}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(c,a,l,_,j){this._parseStack.state=c,this._parseStack.handlers=a,this._parseStack.handlerPos=l,this._parseStack.transition=_,this._parseStack.chunkPos=j}parse(c,a,l){let _,j=0,b=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(l===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const x=this._parseStack.handlers;let N=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(l===!1&&N>-1){for(;N>=0&&(_=x[N](this._params),_!==!0);N--)if(_ instanceof Promise)return this._parseStack.handlerPos=N,_}this._parseStack.handlers=[];break;case 4:if(l===!1&&N>-1){for(;N>=0&&(_=x[N](),_!==!0);N--)if(_ instanceof Promise)return this._parseStack.handlerPos=N,_}this._parseStack.handlers=[];break;case 6:if(j=c[this._parseStack.chunkPos],_=this._dcsParser.unhook(j!==24&&j!==26,l),_)return _;j===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(j=c[this._parseStack.chunkPos],_=this._oscParser.end(j!==24&&j!==26,l),_)return _;j===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let x=k;x>4){case 2:for(let P=x+1;;++P){if(P>=a||(j=c[P])<32||j>126&&j=a||(j=c[P])<32||j>126&&j=a||(j=c[P])<32||j>126&&j=a||(j=c[P])<32||j>126&&j=0&&(_=N[E](this._params),_!==!0);E--)if(_ instanceof Promise)return this._preserveStack(3,N,E,b,x),_;E<0&&this._csiHandlerFb(this._collect<<8|j,this._params),this.precedingJoinState=0;break;case 8:do switch(j){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(j-48)}while(++x47&&j<60);x--;break;case 9:this._collect<<=8,this._collect|=j;break;case 10:const L=this._escHandlers[this._collect<<8|j];let T=L?L.length-1:-1;for(;T>=0&&(_=L[T](),_!==!0);T--)if(_ instanceof Promise)return this._preserveStack(4,L,T,b,x),_;T<0&&this._escHandlerFb(this._collect<<8|j),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|j,this._params);break;case 13:for(let P=x+1;;++P)if(P>=a||(j=c[P])===24||j===26||j===27||j>127&&j=a||(j=c[P])<32||j>127&&j{Object.defineProperty(o,"__esModule",{value:!0}),o.OscHandler=o.OscParser=void 0;const d=u(5770),m=u(482),f=[];o.OscParser=class{constructor(){this._state=0,this._active=f,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(g,w){this._handlers[g]===void 0&&(this._handlers[g]=[]);const S=this._handlers[g];return S.push(w),{dispose:()=>{const v=S.indexOf(w);v!==-1&&S.splice(v,1)}}}clearHandler(g){this._handlers[g]&&delete this._handlers[g]}setHandlerFallback(g){this._handlerFb=g}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=f}reset(){if(this._state===2)for(let g=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;g>=0;--g)this._active[g].end(!1);this._stack.paused=!1,this._active=f,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||f,this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].start();else this._handlerFb(this._id,"START")}_put(g,w,S){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(g,w,S);else this._handlerFb(this._id,"PUT",(0,m.utf32ToString)(g,w,S))}start(){this.reset(),this._state=1}put(g,w,S){if(this._state!==3){if(this._state===1)for(;w0&&this._put(g,w,S)}}end(g,w=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let S=!1,v=this._active.length-1,p=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,S=w,p=this._stack.fallThrough,this._stack.paused=!1),!p&&S===!1){for(;v>=0&&(S=this._active[v].end(g),S!==!0);v--)if(S instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,S;v--}for(;v>=0;v--)if(S=this._active[v].end(!1),S instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,S}else this._handlerFb(this._id,"END",g);this._active=f,this._id=-1,this._state=0}}},o.OscHandler=class{constructor(g){this._handler=g,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(g,w,S){this._hitLimit||(this._data+=(0,m.utf32ToString)(g,w,S),this._data.length>d.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(g){let w=!1;if(this._hitLimit)w=!1;else if(g&&(w=this._handler(this._data),w instanceof Promise))return w.then(S=>(this._data="",this._hitLimit=!1,S));return this._data="",this._hitLimit=!1,w}}},8742:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Params=void 0;const u=2147483647;class d{static fromArray(f){const g=new d;if(!f.length)return g;for(let w=Array.isArray(f[0])?1:0;w256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(f),this.length=0,this._subParams=new Int32Array(g),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(f),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const f=new d(this.maxLength,this.maxSubParamsLength);return f.params.set(this.params),f.length=this.length,f._subParams.set(this._subParams),f._subParamsLength=this._subParamsLength,f._subParamsIdx.set(this._subParamsIdx),f._rejectDigits=this._rejectDigits,f._rejectSubDigits=this._rejectSubDigits,f._digitIsSub=this._digitIsSub,f}toArray(){const f=[];for(let g=0;g>8,S=255&this._subParamsIdx[g];S-w>0&&f.push(Array.prototype.slice.call(this._subParams,w,S))}return f}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(f){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(f<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=f>u?u:f}}addSubParam(f){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(f<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=f>u?u:f,this._subParamsIdx[this.length-1]++}}hasSubParams(f){return(255&this._subParamsIdx[f])-(this._subParamsIdx[f]>>8)>0}getSubParams(f){const g=this._subParamsIdx[f]>>8,w=255&this._subParamsIdx[f];return w-g>0?this._subParams.subarray(g,w):null}getSubParamsAll(){const f={};for(let g=0;g>8,S=255&this._subParamsIdx[g];S-w>0&&(f[g]=this._subParams.slice(w,S))}return f}addDigit(f){let g;if(this._rejectDigits||!(g=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const w=this._digitIsSub?this._subParams:this.params,S=w[g-1];w[g-1]=~S?Math.min(10*S+f,u):f}}o.Params=d},5741:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.AddonManager=void 0,o.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let u=this._addons.length-1;u>=0;u--)this._addons[u].instance.dispose()}loadAddon(u,d){const m={instance:d,dispose:d.dispose,isDisposed:!1};this._addons.push(m),d.dispose=()=>this._wrappedAddonDispose(m),d.activate(u)}_wrappedAddonDispose(u){if(u.isDisposed)return;let d=-1;for(let m=0;m{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferApiView=void 0;const d=u(3785),m=u(511);o.BufferApiView=class{constructor(f,g){this._buffer=f,this.type=g}init(f){return this._buffer=f,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(f){const g=this._buffer.lines.get(f);if(g)return new d.BufferLineApiView(g)}getNullCell(){return new m.CellData}}},3785:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLineApiView=void 0;const d=u(511);o.BufferLineApiView=class{constructor(m){this._line=m}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(m,f){if(!(m<0||m>=this._line.length))return f?(this._line.loadCell(m,f),f):this._line.loadCell(m,new d.CellData)}translateToString(m,f,g){return this._line.translateToString(m,f,g)}}},8285:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferNamespaceApi=void 0;const d=u(8771),m=u(8460),f=u(844);class g extends f.Disposable{constructor(S){super(),this._core=S,this._onBufferChange=this.register(new m.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new d.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new d.BufferApiView(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)}}o.BufferNamespaceApi=g},7975:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ParserApi=void 0,o.ParserApi=class{constructor(u){this._core=u}registerCsiHandler(u,d){return this._core.registerCsiHandler(u,m=>d(m.toArray()))}addCsiHandler(u,d){return this.registerCsiHandler(u,d)}registerDcsHandler(u,d){return this._core.registerDcsHandler(u,(m,f)=>d(m,f.toArray()))}addDcsHandler(u,d){return this.registerDcsHandler(u,d)}registerEscHandler(u,d){return this._core.registerEscHandler(u,d)}addEscHandler(u,d){return this.registerEscHandler(u,d)}registerOscHandler(u,d){return this._core.registerOscHandler(u,d)}addOscHandler(u,d){return this.registerOscHandler(u,d)}}},7090:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeApi=void 0,o.UnicodeApi=class{constructor(u){this._core=u}register(u){this._core.unicodeService.register(u)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(u){this._core.unicodeService.activeVersion=u}}},744:function(y,o,u){var d=this&&this.__decorate||function(p,c,a,l){var _,j=arguments.length,b=j<3?c:l===null?l=Object.getOwnPropertyDescriptor(c,a):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(p,c,a,l);else for(var k=p.length-1;k>=0;k--)(_=p[k])&&(b=(j<3?_(b):j>3?_(c,a,b):_(c,a))||b);return j>3&&b&&Object.defineProperty(c,a,b),b},m=this&&this.__param||function(p,c){return function(a,l){c(a,l,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferService=o.MINIMUM_ROWS=o.MINIMUM_COLS=void 0;const f=u(8460),g=u(844),w=u(5295),S=u(2585);o.MINIMUM_COLS=2,o.MINIMUM_ROWS=1;let v=o.BufferService=class extends g.Disposable{get buffer(){return this.buffers.active}constructor(p){super(),this.isUserScrolling=!1,this._onResize=this.register(new f.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new f.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(p.rawOptions.cols||0,o.MINIMUM_COLS),this.rows=Math.max(p.rawOptions.rows||0,o.MINIMUM_ROWS),this.buffers=this.register(new w.BufferSet(p,this))}resize(p,c){this.cols=p,this.rows=c,this.buffers.resize(p,c),this._onResize.fire({cols:p,rows:c})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(p,c=!1){const a=this.buffer;let l;l=this._cachedBlankLine,l&&l.length===this.cols&&l.getFg(0)===p.fg&&l.getBg(0)===p.bg||(l=a.getBlankLine(p,c),this._cachedBlankLine=l),l.isWrapped=c;const _=a.ybase+a.scrollTop,j=a.ybase+a.scrollBottom;if(a.scrollTop===0){const b=a.lines.isFull;j===a.lines.length-1?b?a.lines.recycle().copyFrom(l):a.lines.push(l.clone()):a.lines.splice(j+1,0,l.clone()),b?this.isUserScrolling&&(a.ydisp=Math.max(a.ydisp-1,0)):(a.ybase++,this.isUserScrolling||a.ydisp++)}else{const b=j-_+1;a.lines.shiftElements(_+1,b-1,-1),a.lines.set(j,l.clone())}this.isUserScrolling||(a.ydisp=a.ybase),this._onScroll.fire(a.ydisp)}scrollLines(p,c,a){const l=this.buffer;if(p<0){if(l.ydisp===0)return;this.isUserScrolling=!0}else p+l.ydisp>=l.ybase&&(this.isUserScrolling=!1);const _=l.ydisp;l.ydisp=Math.max(Math.min(l.ydisp+p,l.ybase),0),_!==l.ydisp&&(c||this._onScroll.fire(l.ydisp))}};o.BufferService=v=d([m(0,S.IOptionsService)],v)},7994:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CharsetService=void 0,o.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(u){this.glevel=u,this.charset=this._charsets[u]}setgCharset(u,d){this._charsets[u]=d,this.glevel===u&&(this.charset=d)}}},1753:function(y,o,u){var d=this&&this.__decorate||function(l,_,j,b){var k,x=arguments.length,N=x<3?_:b===null?b=Object.getOwnPropertyDescriptor(_,j):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(l,_,j,b);else for(var E=l.length-1;E>=0;E--)(k=l[E])&&(N=(x<3?k(N):x>3?k(_,j,N):k(_,j))||N);return x>3&&N&&Object.defineProperty(_,j,N),N},m=this&&this.__param||function(l,_){return function(j,b){_(j,b,l)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreMouseService=void 0;const f=u(2585),g=u(8460),w=u(844),S={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:l=>l.button!==4&&l.action===1&&(l.ctrl=!1,l.alt=!1,l.shift=!1,!0)},VT200:{events:19,restrict:l=>l.action!==32},DRAG:{events:23,restrict:l=>l.action!==32||l.button!==3},ANY:{events:31,restrict:l=>!0}};function v(l,_){let j=(l.ctrl?16:0)|(l.shift?4:0)|(l.alt?8:0);return l.button===4?(j|=64,j|=l.action):(j|=3&l.button,4&l.button&&(j|=64),8&l.button&&(j|=128),l.action===32?j|=32:l.action!==0||_||(j|=3)),j}const p=String.fromCharCode,c={DEFAULT:l=>{const _=[v(l,!1)+32,l.col+32,l.row+32];return _[0]>255||_[1]>255||_[2]>255?"":`\x1B[M${p(_[0])}${p(_[1])}${p(_[2])}`},SGR:l=>{const _=l.action===0&&l.button!==4?"m":"M";return`\x1B[<${v(l,!0)};${l.col};${l.row}${_}`},SGR_PIXELS:l=>{const _=l.action===0&&l.button!==4?"m":"M";return`\x1B[<${v(l,!0)};${l.x};${l.y}${_}`}};let a=o.CoreMouseService=class extends w.Disposable{constructor(l,_){super(),this._bufferService=l,this._coreService=_,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new g.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const j of Object.keys(S))this.addProtocol(j,S[j]);for(const j of Object.keys(c))this.addEncoding(j,c[j]);this.reset()}addProtocol(l,_){this._protocols[l]=_}addEncoding(l,_){this._encodings[l]=_}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(l){if(!this._protocols[l])throw new Error(`unknown protocol "${l}"`);this._activeProtocol=l,this._onProtocolChange.fire(this._protocols[l].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(l){if(!this._encodings[l])throw new Error(`unknown encoding "${l}"`);this._activeEncoding=l}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(l){if(l.col<0||l.col>=this._bufferService.cols||l.row<0||l.row>=this._bufferService.rows||l.button===4&&l.action===32||l.button===3&&l.action!==32||l.button!==4&&(l.action===2||l.action===3)||(l.col++,l.row++,l.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,l,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(l))return!1;const _=this._encodings[this._activeEncoding](l);return _&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(_):this._coreService.triggerDataEvent(_,!0)),this._lastEvent=l,!0}explainEvents(l){return{down:!!(1&l),up:!!(2&l),drag:!!(4&l),move:!!(8&l),wheel:!!(16&l)}}_equalEvents(l,_,j){if(j){if(l.x!==_.x||l.y!==_.y)return!1}else if(l.col!==_.col||l.row!==_.row)return!1;return l.button===_.button&&l.action===_.action&&l.ctrl===_.ctrl&&l.alt===_.alt&&l.shift===_.shift}};o.CoreMouseService=a=d([m(0,f.IBufferService),m(1,f.ICoreService)],a)},6975:function(y,o,u){var d=this&&this.__decorate||function(a,l,_,j){var b,k=arguments.length,x=k<3?l:j===null?j=Object.getOwnPropertyDescriptor(l,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(a,l,_,j);else for(var N=a.length-1;N>=0;N--)(b=a[N])&&(x=(k<3?b(x):k>3?b(l,_,x):b(l,_))||x);return k>3&&x&&Object.defineProperty(l,_,x),x},m=this&&this.__param||function(a,l){return function(_,j){l(_,j,a)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreService=void 0;const f=u(1439),g=u(8460),w=u(844),S=u(2585),v=Object.freeze({insertMode:!1}),p=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let c=o.CoreService=class extends w.Disposable{constructor(a,l,_){super(),this._bufferService=a,this._logService=l,this._optionsService=_,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new g.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new g.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new g.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new g.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,f.clone)(v),this.decPrivateModes=(0,f.clone)(p)}reset(){this.modes=(0,f.clone)(v),this.decPrivateModes=(0,f.clone)(p)}triggerDataEvent(a,l=!1){if(this._optionsService.rawOptions.disableStdin)return;const _=this._bufferService.buffer;l&&this._optionsService.rawOptions.scrollOnUserInput&&_.ybase!==_.ydisp&&this._onRequestScrollToBottom.fire(),l&&this._onUserInput.fire(),this._logService.debug(`sending data "${a}"`,()=>a.split("").map(j=>j.charCodeAt(0))),this._onData.fire(a)}triggerBinaryEvent(a){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${a}"`,()=>a.split("").map(l=>l.charCodeAt(0))),this._onBinary.fire(a))}};o.CoreService=c=d([m(0,S.IBufferService),m(1,S.ILogService),m(2,S.IOptionsService)],c)},9074:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DecorationService=void 0;const d=u(8055),m=u(8460),f=u(844),g=u(6106);let w=0,S=0;class v extends f.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new g.SortedList(a=>a==null?void 0:a.marker.line),this._onDecorationRegistered=this.register(new m.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new m.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,f.toDisposable)(()=>this.reset()))}registerDecoration(a){if(a.marker.isDisposed)return;const l=new p(a);if(l){const _=l.marker.onDispose(()=>l.dispose());l.onDispose(()=>{l&&(this._decorations.delete(l)&&this._onDecorationRemoved.fire(l),_.dispose())}),this._decorations.insert(l),this._onDecorationRegistered.fire(l)}return l}reset(){for(const a of this._decorations.values())a.dispose();this._decorations.clear()}*getDecorationsAtCell(a,l,_){let j=0,b=0;for(const k of this._decorations.getKeyIterator(l))j=k.options.x??0,b=j+(k.options.width??1),a>=j&&a{w=b.options.x??0,S=w+(b.options.width??1),a>=w&&a{Object.defineProperty(o,"__esModule",{value:!0}),o.InstantiationService=o.ServiceCollection=void 0;const d=u(2585),m=u(8343);class f{constructor(...w){this._entries=new Map;for(const[S,v]of w)this.set(S,v)}set(w,S){const v=this._entries.get(w);return this._entries.set(w,S),v}forEach(w){for(const[S,v]of this._entries.entries())w(S,v)}has(w){return this._entries.has(w)}get(w){return this._entries.get(w)}}o.ServiceCollection=f,o.InstantiationService=class{constructor(){this._services=new f,this._services.set(d.IInstantiationService,this)}setService(g,w){this._services.set(g,w)}getService(g){return this._services.get(g)}createInstance(g,...w){const S=(0,m.getServiceDependencies)(g).sort((c,a)=>c.index-a.index),v=[];for(const c of S){const a=this._services.get(c.id);if(!a)throw new Error(`[createInstance] ${g.name} depends on UNKNOWN service ${c.id}.`);v.push(a)}const p=S.length>0?S[0].index:w.length;if(w.length!==p)throw new Error(`[createInstance] First service dependency of ${g.name} at position ${p+1} conflicts with ${w.length} static arguments`);return new g(...w,...v)}}},7866:function(y,o,u){var d=this&&this.__decorate||function(p,c,a,l){var _,j=arguments.length,b=j<3?c:l===null?l=Object.getOwnPropertyDescriptor(c,a):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(p,c,a,l);else for(var k=p.length-1;k>=0;k--)(_=p[k])&&(b=(j<3?_(b):j>3?_(c,a,b):_(c,a))||b);return j>3&&b&&Object.defineProperty(c,a,b),b},m=this&&this.__param||function(p,c){return function(a,l){c(a,l,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.traceCall=o.setTraceLogger=o.LogService=void 0;const f=u(844),g=u(2585),w={trace:g.LogLevelEnum.TRACE,debug:g.LogLevelEnum.DEBUG,info:g.LogLevelEnum.INFO,warn:g.LogLevelEnum.WARN,error:g.LogLevelEnum.ERROR,off:g.LogLevelEnum.OFF};let S,v=o.LogService=class extends f.Disposable{get logLevel(){return this._logLevel}constructor(p){super(),this._optionsService=p,this._logLevel=g.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),S=this}_updateLogLevel(){this._logLevel=w[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(p){for(let c=0;cJSON.stringify(b)).join(", ")})`);const j=l.apply(this,_);return S.trace(`GlyphRenderer#${l.name} return`,j),j}}},7302:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.OptionsService=o.DEFAULT_OPTIONS=void 0;const d=u(8460),m=u(844),f=u(6114);o.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:f.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const g=["normal","bold","100","200","300","400","500","600","700","800","900"];class w extends m.Disposable{constructor(v){super(),this._onOptionChange=this.register(new d.EventEmitter),this.onOptionChange=this._onOptionChange.event;const p={...o.DEFAULT_OPTIONS};for(const c in v)if(c in p)try{const a=v[c];p[c]=this._sanitizeAndValidateOption(c,a)}catch(a){console.error(a)}this.rawOptions=p,this.options={...p},this._setupOptions(),this.register((0,m.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(v,p){return this.onOptionChange(c=>{c===v&&p(this.rawOptions[v])})}onMultipleOptionChange(v,p){return this.onOptionChange(c=>{v.indexOf(c)!==-1&&p()})}_setupOptions(){const v=c=>{if(!(c in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${c}"`);return this.rawOptions[c]},p=(c,a)=>{if(!(c in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${c}"`);a=this._sanitizeAndValidateOption(c,a),this.rawOptions[c]!==a&&(this.rawOptions[c]=a,this._onOptionChange.fire(c))};for(const c in this.rawOptions){const a={get:v.bind(this,c),set:p.bind(this,c)};Object.defineProperty(this.options,c,a)}}_sanitizeAndValidateOption(v,p){switch(v){case"cursorStyle":if(p||(p=o.DEFAULT_OPTIONS[v]),!function(c){return c==="block"||c==="underline"||c==="bar"}(p))throw new Error(`"${p}" is not a valid value for ${v}`);break;case"wordSeparator":p||(p=o.DEFAULT_OPTIONS[v]);break;case"fontWeight":case"fontWeightBold":if(typeof p=="number"&&1<=p&&p<=1e3)break;p=g.includes(p)?p:o.DEFAULT_OPTIONS[v];break;case"cursorWidth":p=Math.floor(p);case"lineHeight":case"tabStopWidth":if(p<1)throw new Error(`${v} cannot be less than 1, value: ${p}`);break;case"minimumContrastRatio":p=Math.max(1,Math.min(21,Math.round(10*p)/10));break;case"scrollback":if((p=Math.min(p,4294967295))<0)throw new Error(`${v} cannot be less than 0, value: ${p}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(p<=0)throw new Error(`${v} cannot be less than or equal to 0, value: ${p}`);break;case"rows":case"cols":if(!p&&p!==0)throw new Error(`${v} must be numeric, value: ${p}`);break;case"windowsPty":p=p??{}}return p}}o.OptionsService=w},2660:function(y,o,u){var d=this&&this.__decorate||function(w,S,v,p){var c,a=arguments.length,l=a<3?S:p===null?p=Object.getOwnPropertyDescriptor(S,v):p;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(w,S,v,p);else for(var _=w.length-1;_>=0;_--)(c=w[_])&&(l=(a<3?c(l):a>3?c(S,v,l):c(S,v))||l);return a>3&&l&&Object.defineProperty(S,v,l),l},m=this&&this.__param||function(w,S){return function(v,p){S(v,p,w)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkService=void 0;const f=u(2585);let g=o.OscLinkService=class{constructor(w){this._bufferService=w,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(w){const S=this._bufferService.buffer;if(w.id===void 0){const _=S.addMarker(S.ybase+S.y),j={data:w,id:this._nextId++,lines:[_]};return _.onDispose(()=>this._removeMarkerFromLink(j,_)),this._dataByLinkId.set(j.id,j),j.id}const v=w,p=this._getEntryIdKey(v),c=this._entriesWithId.get(p);if(c)return this.addLineToLink(c.id,S.ybase+S.y),c.id;const a=S.addMarker(S.ybase+S.y),l={id:this._nextId++,key:this._getEntryIdKey(v),data:v,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(l,a)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(w,S){const v=this._dataByLinkId.get(w);if(v&&v.lines.every(p=>p.line!==S)){const p=this._bufferService.buffer.addMarker(S);v.lines.push(p),p.onDispose(()=>this._removeMarkerFromLink(v,p))}}getLinkData(w){var S;return(S=this._dataByLinkId.get(w))==null?void 0:S.data}_getEntryIdKey(w){return`${w.id};;${w.uri}`}_removeMarkerFromLink(w,S){const v=w.lines.indexOf(S);v!==-1&&(w.lines.splice(v,1),w.lines.length===0&&(w.data.id!==void 0&&this._entriesWithId.delete(w.key),this._dataByLinkId.delete(w.id)))}};o.OscLinkService=g=d([m(0,f.IBufferService)],g)},8343:(y,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createDecorator=o.getServiceDependencies=o.serviceRegistry=void 0;const u="di$target",d="di$dependencies";o.serviceRegistry=new Map,o.getServiceDependencies=function(m){return m[d]||[]},o.createDecorator=function(m){if(o.serviceRegistry.has(m))return o.serviceRegistry.get(m);const f=function(g,w,S){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(v,p,c){p[u]===p?p[d].push({id:v,index:c}):(p[d]=[{id:v,index:c}],p[u]=p)})(f,g,S)};return f.toString=()=>m,o.serviceRegistry.set(m,f),f}},2585:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.IDecorationService=o.IUnicodeService=o.IOscLinkService=o.IOptionsService=o.ILogService=o.LogLevelEnum=o.IInstantiationService=o.ICharsetService=o.ICoreService=o.ICoreMouseService=o.IBufferService=void 0;const d=u(8343);var m;o.IBufferService=(0,d.createDecorator)("BufferService"),o.ICoreMouseService=(0,d.createDecorator)("CoreMouseService"),o.ICoreService=(0,d.createDecorator)("CoreService"),o.ICharsetService=(0,d.createDecorator)("CharsetService"),o.IInstantiationService=(0,d.createDecorator)("InstantiationService"),function(f){f[f.TRACE=0]="TRACE",f[f.DEBUG=1]="DEBUG",f[f.INFO=2]="INFO",f[f.WARN=3]="WARN",f[f.ERROR=4]="ERROR",f[f.OFF=5]="OFF"}(m||(o.LogLevelEnum=m={})),o.ILogService=(0,d.createDecorator)("LogService"),o.IOptionsService=(0,d.createDecorator)("OptionsService"),o.IOscLinkService=(0,d.createDecorator)("OscLinkService"),o.IUnicodeService=(0,d.createDecorator)("UnicodeService"),o.IDecorationService=(0,d.createDecorator)("DecorationService")},1480:(y,o,u)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeService=void 0;const d=u(8460),m=u(225);class f{static extractShouldJoin(w){return(1&w)!=0}static extractWidth(w){return w>>1&3}static extractCharKind(w){return w>>3}static createPropertyValue(w,S,v=!1){return(16777215&w)<<3|(3&S)<<1|(v?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new d.EventEmitter,this.onChange=this._onChange.event;const w=new m.UnicodeV6;this.register(w),this._active=w.version,this._activeProvider=w}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(w){if(!this._providers[w])throw new Error(`unknown Unicode version "${w}"`);this._active=w,this._activeProvider=this._providers[w],this._onChange.fire(w)}register(w){this._providers[w.version]=w}wcwidth(w){return this._activeProvider.wcwidth(w)}getStringCellWidth(w){let S=0,v=0;const p=w.length;for(let c=0;c=p)return S+this.wcwidth(a);const j=w.charCodeAt(c);56320<=j&&j<=57343?a=1024*(a-55296)+j-56320+65536:S+=this.wcwidth(j)}const l=this.charProperties(a,v);let _=f.extractWidth(l);f.extractShouldJoin(l)&&(_-=f.extractWidth(v)),S+=_,v=l}return S}charProperties(w,S){return this._activeProvider.charProperties(w,S)}}o.UnicodeService=f}},n={};function i(y){var o=n[y];if(o!==void 0)return o.exports;var u=n[y]={exports:{}};return r[y].call(u.exports,u,u.exports,i),u.exports}var h={};return(()=>{var y=h;Object.defineProperty(y,"__esModule",{value:!0}),y.Terminal=void 0;const o=i(9042),u=i(3236),d=i(844),m=i(5741),f=i(8285),g=i(7975),w=i(7090),S=["cols","rows"];class v extends d.Disposable{constructor(c){super(),this._core=this.register(new u.Terminal(c)),this._addonManager=this.register(new m.AddonManager),this._publicOptions={...this._core.options};const a=_=>this._core.options[_],l=(_,j)=>{this._checkReadonlyOptions(_),this._core.options[_]=j};for(const _ in this._core.options){const j={get:a.bind(this,_),set:l.bind(this,_)};Object.defineProperty(this._publicOptions,_,j)}}_checkReadonlyOptions(c){if(S.includes(c))throw new Error(`Option "${c}" 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 g.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new w.UnicodeApi(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 f.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const c=this._core.coreService.decPrivateModes;let a="none";switch(this._core.coreMouseService.activeProtocol){case"X10":a="x10";break;case"VT200":a="vt200";break;case"DRAG":a="drag";break;case"ANY":a="any"}return{applicationCursorKeysMode:c.applicationCursorKeys,applicationKeypadMode:c.applicationKeypad,bracketedPasteMode:c.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:a,originMode:c.origin,reverseWraparoundMode:c.reverseWraparound,sendFocusMode:c.sendFocus,wraparoundMode:c.wraparound}}get options(){return this._publicOptions}set options(c){for(const a in c)this._publicOptions[a]=c[a]}blur(){this._core.blur()}focus(){this._core.focus()}input(c,a=!0){this._core.input(c,a)}resize(c,a){this._verifyIntegers(c,a),this._core.resize(c,a)}open(c){this._core.open(c)}attachCustomKeyEventHandler(c){this._core.attachCustomKeyEventHandler(c)}attachCustomWheelEventHandler(c){this._core.attachCustomWheelEventHandler(c)}registerLinkProvider(c){return this._core.registerLinkProvider(c)}registerCharacterJoiner(c){return this._checkProposedApi(),this._core.registerCharacterJoiner(c)}deregisterCharacterJoiner(c){this._checkProposedApi(),this._core.deregisterCharacterJoiner(c)}registerMarker(c=0){return this._verifyIntegers(c),this._core.registerMarker(c)}registerDecoration(c){return this._checkProposedApi(),this._verifyPositiveIntegers(c.x??0,c.width??0,c.height??0),this._core.registerDecoration(c)}hasSelection(){return this._core.hasSelection()}select(c,a,l){this._verifyIntegers(c,a,l),this._core.select(c,a,l)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(c,a){this._verifyIntegers(c,a),this._core.selectLines(c,a)}dispose(){super.dispose()}scrollLines(c){this._verifyIntegers(c),this._core.scrollLines(c)}scrollPages(c){this._verifyIntegers(c),this._core.scrollPages(c)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(c){this._verifyIntegers(c),this._core.scrollToLine(c)}clear(){this._core.clear()}write(c,a){this._core.write(c,a)}writeln(c,a){this._core.write(c),this._core.write(`\r `,a)}paste(c){this._core.paste(c)}refresh(c,a){this._verifyIntegers(c,a),this._core.refresh(c,a)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(c){this._addonManager.loadAddon(this,c)}static get strings(){return o}_verifyIntegers(...c){for(const a of c)if(a===1/0||isNaN(a)||a%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...c){for(const a of c)if(a&&(a===1/0||isNaN(a)||a%1!=0||a<0))throw new Error("This API only accepts positive integers")}}y.Terminal=v})(),h})())})(Cd);var jd=Cd.exports,Nd={exports:{}};(function(e,t){(function(r,n){e.exports=n()})(self,()=>(()=>{var r={};return(()=>{var n=r;Object.defineProperty(n,"__esModule",{value:!0}),n.FitAddon=void 0,n.FitAddon=class{activate(i){this._terminal=i}dispose(){}fit(){const i=this.proposeDimensions();if(!i||!this._terminal||isNaN(i.cols)||isNaN(i.rows))return;const h=this._terminal._core;this._terminal.rows===i.rows&&this._terminal.cols===i.cols||(h._renderService.clear(),this._terminal.resize(i.cols,i.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const i=this._terminal._core,h=i._renderService.dimensions;if(h.css.cell.width===0||h.css.cell.height===0)return;const y=this._terminal.options.scrollback===0?0:i.viewport.scrollBarWidth,o=window.getComputedStyle(this._terminal.element.parentElement),u=parseInt(o.getPropertyValue("height")),d=Math.max(0,parseInt(o.getPropertyValue("width"))),m=window.getComputedStyle(this._terminal.element),f=u-(parseInt(m.getPropertyValue("padding-top"))+parseInt(m.getPropertyValue("padding-bottom"))),g=d-(parseInt(m.getPropertyValue("padding-right"))+parseInt(m.getPropertyValue("padding-left")))-y;return{cols:Math.max(2,Math.floor(g/h.css.cell.width)),rows:Math.max(1,Math.floor(f/h.css.cell.height))}}}})(),r})())})(Nd);var Ed=Nd.exports;function nn({projectId:e,onDone:t}){const r=C.useRef(null),[n,i]=C.useState(!1),h=C.useRef(!1),y=C.useRef(null),o=C.useRef(null),u=C.useRef(!1),d=m=>{var f,g;if(!h.current){h.current=!0;try{(f=y.current)==null||f.close()}catch{}try{(g=o.current)==null||g.dispose()}catch{}t(m)}};return C.useEffect(()=>{const m=new jd.Terminal({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:13,theme:{background:"#0B0E14"},scrollback:1e3});o.current=m;const f=new Ed.FitAddon;m.loadAddon(f),r.current&&(m.open(r.current),f.fit());const g=new WebSocket(hs(`/p/${encodeURIComponent(e)}/sshkeys/ws`));y.current=g,g.binaryType="arraybuffer";const w=new TextDecoder;g.onopen=()=>{g.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})),m.focus()},g.onmessage=v=>{m.write(typeof v.data=="string"?v.data:w.decode(new Uint8Array(v.data)))},g.onclose=()=>d(u.current),m.onData(v=>{g.readyState===WebSocket.OPEN&&g.send(new TextEncoder().encode(v))});const S=window.setInterval(async()=>{try{const v=await ee(`/p/${encodeURIComponent(e)}/sshkeys/status`);v&&v.loaded&&!u.current&&(u.current=!0,i(!0),m.write(`\r \x1B[32m✓ keys loaded — click Continue to proceed\x1B[0m\r `))}catch{}},1500);return()=>{window.clearInterval(S)}},[e]),s.jsx("div",{className:"sshload-overlay",onClick:m=>m.target===m.currentTarget&&d(u.current),children:s.jsxs("div",{className:"sshload-box",children:[s.jsxs("h3",{children:["Load SSH keys ",s.jsx("span",{className:"sshload-hostbadge",children:"host shell"})]}),s.jsxs("p",{className:"muted",children:["This is a real shell ",s.jsx("strong",{children:"on your host machine"})," (not sandboxed). It runs ",s.jsx("code",{children:"ssh-add"})," for this project's scoped agent — type each key's passphrase at the prompt. The passphrase goes straight to"," ",s.jsx("code",{children:"ssh-add"})," in the terminal; it's never stored or sent as data."]}),s.jsx("div",{className:"sshload-term",ref:r}),s.jsx("div",{className:"sshload-actions",children:n?s.jsx("button",{className:"cfg-btn sshload-continue",onClick:()=>d(!0),children:"Continue ▶"}):s.jsx("button",{className:"cfg-btn cfg-btn-ghost sshload-done",onClick:()=>d(u.current),children:"Cancel"})})]})})}function Rd(e){if(!e)return null;const t=String(e).match(/github\.com[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/?$/);return t?`${t[1]}/${t[2]}`:null}function on(e,t){if(!e)return"";const r=new Date(e).getTime();if(isNaN(r))return"";const n=Math.max(0,(t-r)/1e3),i=[["y",31536e3],["mo",2592e3],["d",86400],["h",3600],["m",60]];for(const[h,y]of i){const o=Math.floor(n/y);if(o>=1)return`${o}${h} ago`}return"just now"}function Ld(e){const t=Date.now();return e.map(r=>{const n=on(r.pushedAt,t),i=[r.isPrivate?"private":"",n].filter(Boolean);return{value:r.nameWithOwner,label:r.nameWithOwner,hint:i.join(" · ")}})}function ca(e,t,r){if(!e)return null;const n={branch:t||void 0},i=r.find(h=>h.nameWithOwner===e||h.url===e);return i?(n.url=i.url,n):(!e.includes("://")&&e.charAt(0)==="/"?n.localPath=e:n.url=e,n)}function hr({title:e,onClose:t,children:r}){return s.jsx("div",{className:"modal-backdrop",onClick:n=>n.target===n.currentTarget&&t(),children:s.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"modal-head",children:[s.jsx("span",{children:e}),s.jsx("button",{type:"button",title:"Close",onClick:t,children:"✕"})]}),s.jsx("div",{className:"modal-body",children:r})]})})}function ua({items:e,placeholder:t,className:r,value:n,onChange:i,onPick:h,autoFocus:y}){const[o,u]=C.useState(!1),[d,m]=C.useState(-1),f=C.useRef(null);C.useEffect(()=>{var v;y&&((v=f.current)==null||v.focus())},[y]);const g=n.trim().toLowerCase(),w=e.filter(v=>!g||v.value.toLowerCase().includes(g)||(v.label||"").toLowerCase().includes(g)).slice(0,30),S=v=>{i(v.value),u(!1),m(-1),h==null||h(v.value)};return s.jsxs("div",{className:"ta",children:[s.jsx("input",{ref:f,type:"text",className:r||"ta-input",placeholder:t,autoComplete:"off",value:n,onChange:v=>{i(v.target.value),m(-1),u(!0)},onFocus:()=>u(!0),onBlur:()=>setTimeout(()=>u(!1),120),onKeyDown:v=>{v.key==="ArrowDown"?(v.preventDefault(),m(p=>Math.min(p+1,w.length-1))):v.key==="ArrowUp"?(v.preventDefault(),m(p=>Math.max(p-1,0))):v.key==="Enter"&&d>=0&&w[d]?(v.preventDefault(),S(w[d])):v.key==="Escape"&&u(!1)}}),o&&w.length>0&&s.jsx("div",{className:"ta-menu",children:w.map((v,p)=>s.jsxs("div",{className:`ta-opt${p===d?" active":""}`,onMouseDown:c=>{c.preventDefault(),S(v)},children:[s.jsx("span",{className:"ta-val",children:v.label||v.value}),v.hint&&s.jsx("span",{className:"ta-hint",children:v.hint})]},v.value))})]})}function Ec(e,t){return e.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(r,n)=>t[n]??"")}function Dd({promptKey:e,repoId:t,value:r,onChange:n,onDirty:i,vars:h}){const[y,o]=C.useState("default"),[u,d]=C.useState(!1),[m,f]=C.useState([]),[g,w]=C.useState(!1),[S,v]=C.useState(""),[p,c]=C.useState(!1),[a,l]=C.useState(""),_=C.useRef(null);C.useEffect(()=>()=>{var k;return(k=_.current)==null?void 0:k.close()},[]),C.useEffect(()=>{const k=t?`?repo=${encodeURIComponent(t)}`:"";ee(`/api/prompts${k}`).then(x=>{const N=(x.prompts||[]).find(E=>E.key===e);N&&(o(N.source),r||n(h?Ec(N.effective,h):N.effective)),d(!0)}).catch(()=>d(!0)),ee(`/api/prompts/library${k}`).then(x=>f(x.prompts||[])).catch(()=>{})},[e,t]);function j(k){const x=m.find(N=>String(N.id)===k);x&&(n(h?Ec(x.template,h):x.template),i==null||i(!0))}const b=()=>{var N;if(!S.trim())return;(N=_.current)==null||N.close(),c(!0),l("");const k=t?`?repoId=${encodeURIComponent(t)}`:"",x=new WebSocket(hs(`/api/prompts/draft${k}`));_.current=x,x.onopen=()=>x.send(JSON.stringify({description:S})),x.onmessage=E=>{let L;try{L=JSON.parse(E.data)}catch{return}L.type==="text"?l(T=>T+L.text):L.type==="tool_use"?l(T=>T+`› ${L.tool} `):L.type==="error"?l(T=>T+` ⚠ ${L.text||""}`):L.type==="draft"&&L.result&&(n(L.result),i==null||i(!0))},x.onclose=()=>{c(!1),_.current=null},x.onerror=()=>l(E=>E+` -⚠ draft connection failed`)};return u?s.jsxs("div",{className:"launch-prompt",children:[s.jsxs("div",{className:"launch-prompt-head",children:[s.jsx("span",{children:"Project-start prompt"}),s.jsxs("div",{className:"launch-prompt-head-right",children:[m.length>0&&s.jsxs("select",{className:"launch-prompt-pick",value:"",onChange:k=>{k.target.value&&j(k.target.value),k.target.value=""},title:"Fill from one of your saved prompts",children:[s.jsx("option",{value:"",children:"Use a saved prompt…"}),m.map(k=>s.jsx("option",{value:k.id,children:k.name},k.id))]}),s.jsxs("span",{className:"launch-prompt-src",title:`Inherited from the ${y} prompt`,children:["from: ",y]})]})]}),s.jsx("p",{className:"auto-hint",style:{margin:"0 0 0.35rem"},children:"Sent to Claude when the project starts. Edited here it applies to this launch only — change the saved one under Automations → Prompts."}),s.jsx("textarea",{className:"prompt-textarea",rows:5,value:r,onChange:k=>{n(k.target.value),i==null||i(!0)},placeholder:"You're working in {{repo}} on branch {{branch}}…"}),s.jsx("div",{className:"auto-row",style:{marginTop:"0.3rem"},children:s.jsx("button",{type:"button",className:"auto-btn",onClick:()=>w(k=>!k),children:"✨ Build with AI"})}),g&&s.jsxs("div",{className:"bash-ai",children:[s.jsx("div",{className:"bash-ai-head",children:s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude, not the sandbox; read-only",children:"host · not sandboxed · read-only"})}),s.jsx("textarea",{className:"prompt-textarea",rows:2,value:S,onChange:k=>v(k.target.value),placeholder:"Describe what the prompt should do…"}),s.jsx("button",{type:"button",className:"auto-btn",disabled:p||!S.trim(),onClick:b,children:p?"Drafting…":"Draft with AI"}),a&&s.jsx("pre",{className:"split-menu-ai-log",children:a})]})]}):null}let qt=null,xr=null;function Bm(){return qt?Promise.resolve(qt):xr||(xr=ee("/gh/repos").then(e=>(qt=e&&e.available?e.repos||[]:[],qt)).catch(()=>(qt=[],qt)).finally(()=>{xr=null}),xr)}function al(){const[e,t]=C.useState(qt||[]),[r,n]=C.useState(qt!=null);return C.useEffect(()=>{let i=!0;return Bm().then(h=>{i&&(t(h),n(!0))}),()=>{i=!1}},[]),{repos:e,loaded:r}}function Ti({msg:e}){return e?s.jsx("span",{className:`form-status${e.err?" error":""}`,children:e.text}):s.jsx("span",{className:"form-status"})}function Ad({ghRepos:e,removable:t,onRemove:r,value:n,onChange:i}){const[h,y]=C.useState([]),o=u=>{const d=e.find(f=>f.nameWithOwner===u||f.url===u),m=d?d.nameWithOwner:/^[\w.-]+\/[\w.-]+$/.test(u)?u:null;if(!m){y([]);return}ee(`/gh/branches?repo=${encodeURIComponent(m)}`).then(f=>y(f&&f.available?f.branches||[]:[])).catch(()=>y([]))};return s.jsxs("div",{className:"repo-input-row",children:[s.jsx(ua,{className:"repo-input",placeholder:"pick a repo, or paste a URL / local path",items:Ld(e),value:n.text,onChange:u=>{i({...n,text:u}),o(u)},onPick:o}),s.jsx(ua,{className:"branch-input",placeholder:"branch",items:h.map(u=>({value:u,label:u})),value:n.branch,onChange:u=>i({...n,branch:u})}),s.jsx("button",{type:"button",className:"btn row-rm",title:"Remove",style:{visibility:t?"visible":"hidden"},onClick:r,children:"−"})]})}function ll({presetRepoId:e,presetBranch:t,presetName:r,onClose:n}){var O,B,F;const{repos:i,loaded:h}=al(),[y,o]=C.useState("clone"),[u,d]=C.useState([{text:"",branch:""}]),[m,f]=C.useState(r||""),[g,w]=C.useState(""),[S,v]=C.useState(!1),[p,c]=C.useState(null),[a,l]=C.useState(null),[_,j]=C.useState(!0),[b,k]=C.useState(""),[x,N]=C.useState(!1),E=e||((F=ca(((O=u[0])==null?void 0:O.text.trim())||"",((B=u[0])==null?void 0:B.branch.trim())||"",i))==null?void 0:F.repoId)||"";async function L(z,K){try{const $=await je(`/p/${z}/start`),R=await $.json().catch(()=>({}));if($.status===409&&(R!=null&&R.ssh_keys_pending)){c({text:"load SSH keys to start this project…",err:!1}),l({id:z,prompt:K});return}}catch{}K&&je(`/p/${z}/populate-prompt`,{prompt:K,submit:_}).catch(()=>{}),window.location.href=`/p/${z}/`}async function T(z){z.preventDefault(),c({text:"creating…",err:!1});let K;if(y==="new")K={mode:"new",name:m.trim(),path:g.trim()};else if(y==="existing")K={mode:"existing",path:g.trim()};else{const $=[];e&&$.push({repoId:e,branch:t||void 0});for(const R of u){const D=ca(R.text.trim(),R.branch.trim(),i);D&&$.push(D)}if(!$.length){c({text:"add at least one repo",err:!0});return}K={mode:"clone",name:m.trim(),repos:$}}K.enforceAllowlist=S;try{const $=await oe("/projects/create",K);c({text:"created — starting…",err:!1});const R=x&&b.trim()?b:$.start_prompt||"";await L($.id,R)}catch($){c({text:$.message,err:!0})}}return s.jsxs(hr,{title:"New project",onClose:n,children:[s.jsx("div",{className:"mode-tabs",children:["clone","new","existing"].map(z=>s.jsx("button",{type:"button",className:y===z?"active":"",onClick:()=>o(z),children:z==="clone"?"From repo(s)":z==="new"?"Blank dir":"Existing dir"},z))}),s.jsxs("form",{className:"sc-form",onSubmit:T,children:[y==="clone"&&s.jsxs(s.Fragment,{children:[!h&&s.jsx("div",{className:"ta-loading",children:"loading your repos…"}),s.jsx("div",{className:"repo-rows",children:u.map((z,K)=>s.jsx(Ad,{ghRepos:i,removable:K>0,onRemove:()=>d($=>$.filter((R,D)=>D!==K)),value:z,onChange:$=>d(R=>R.map((D,M)=>M===K?$:D))},K))}),s.jsx("button",{type:"button",className:"btn add-row",onClick:()=>d(z=>[...z,{text:"",branch:""}]),children:"+ add another repo"}),s.jsxs("label",{children:["Project name (optional)",s.jsx("input",{type:"text",placeholder:"defaults from the repo",autoComplete:"off",value:m,onChange:z=>f(z.target.value)})]})]}),y==="new"&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Name ",s.jsx("input",{type:"text",placeholder:"my-project",autoComplete:"off",value:m,onChange:z=>f(z.target.value)})]}),s.jsxs("label",{children:["Location (optional)",s.jsx("input",{type:"text",placeholder:"~/code (default: managed workspaces dir)",autoComplete:"off",value:g,onChange:z=>w(z.target.value)})]}),s.jsxs("div",{className:"muted cfg-note",children:["Parent directory for the new project. Use ",s.jsx("code",{children:"~"}),", an absolute path, or a path relative to your home dir. Leave blank to keep it in corral's managed workspaces."]})]}),y==="existing"&&s.jsxs("label",{children:["Absolute path ",s.jsx("input",{type:"text",placeholder:"/Users/you/code/project",autoComplete:"off",value:g,onChange:z=>w(z.target.value)})]}),y!=="existing"&&s.jsxs("label",{className:"row spawn-fw",style:{marginTop:"0.4rem"},children:[s.jsx("input",{type:"checkbox",checked:_,onChange:z=>j(z.target.checked)}),s.jsx("span",{children:"Auto-send the project-start prompt to Claude when it opens."})]}),s.jsxs("details",{className:"spawn-advanced",children:[s.jsx("summary",{children:"Advanced"}),y!=="existing"&&s.jsx(Dd,{promptKey:"project.start",repoId:E,value:b,onChange:k,onDirty:()=>N(!0)}),s.jsxs("label",{className:"row spawn-fw",children:[s.jsx("input",{type:"checkbox",checked:S,onChange:z=>v(z.target.checked)}),s.jsx("span",{children:"More restrictive — strict allowlist (block unknown domains, no direct TCP). Default is permissive: proxy + mitm on, unknown domains allowed & logged."})]})]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",children:y==="existing"?"Register & start":"Create & start"}),s.jsx(Ti,{msg:p})]})]}),a&&s.jsx(nn,{projectId:a.id,onDone:z=>{const{id:K,prompt:$}=a;l(null),z&&(je(`/p/${K}/start`).catch(()=>{}),$&&je(`/p/${K}/populate-prompt`,{prompt:$,submit:_}).catch(()=>{})),window.location.href=`/p/${K}/`}})]})}function $m({onClose:e,onAdded:t}){const{repos:r,loaded:n}=al(),[i,h]=C.useState(""),[y,o]=C.useState(""),[u,d]=C.useState(!1),[m,f]=C.useState(null);async function g(w){w.preventDefault();const S=i.trim();if(!S){f({text:"pick a repo, or paste a URL / local path",err:!0});return}f({text:"cloning cache mirror…",err:!1});const v=!S.includes("://")&&S.charAt(0)==="/",p=!v&&!S.includes("://")&&S.indexOf("/")>0,c={name:y.trim(),isPrivate:u};v?c.localPath=S:c.url=p?`https://github.com/${S}`:S;try{await oe("/repos",c),t(),e()}catch(a){f({text:a.message,err:!0})}}return s.jsx(hr,{title:"Add repository",onClose:e,children:s.jsxs("form",{className:"sc-form",onSubmit:g,children:[s.jsx("label",{children:"Repository"}),s.jsx(ua,{className:"repo-input",placeholder:"search your GitHub repos, or paste a URL / local path",items:Ld(r),value:i,autoFocus:!0,onChange:h,onPick:w=>{const S=r.find(v=>v.nameWithOwner===w);S&&d(!!S.isPrivate)}}),!n&&s.jsx("div",{className:"ta-loading",children:"loading your GitHub repos…"}),n&&r.length===0&&s.jsx("div",{className:"muted",children:"no GitHub repos found (paste a URL or local path instead)"}),s.jsxs("label",{children:["Name (optional) ",s.jsx("input",{type:"text",placeholder:"defaults from the repo",autoComplete:"off",value:y,onChange:w=>o(w.target.value)})]}),s.jsxs("label",{className:"row",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:w=>d(w.target.checked)})," Private (clone with your host git/gh auth)"]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",children:"Add"}),s.jsx(Ti,{msg:m})]})]})})}function Hm({repoId:e,ownerName:t,onClose:r,onCreated:n}){const[i,h]=C.useState(""),[y,o]=C.useState(""),[u,d]=C.useState(""),[m,f]=C.useState(!1),[g,w]=C.useState(""),[S,v]=C.useState(""),[p,c]=C.useState(null),a=C.useRef(null),l=C.useRef(null);C.useEffect(()=>{l.current&&(l.current.scrollTop=l.current.scrollHeight)},[S]),C.useEffect(()=>()=>{var b;return(b=a.current)==null?void 0:b.close()},[]);function _(){var x;const b=i.trim();if(!b){w("describe what you want first");return}(x=a.current)==null||x.close(),f(!0),w(""),v("");const k=new WebSocket(hs(`/gh/issues/draft?repoId=${encodeURIComponent(e)}`));a.current=k,k.onopen=()=>k.send(JSON.stringify({description:b})),k.onmessage=N=>{let E;try{E=JSON.parse(N.data)}catch{return}E.type==="text"?v(L=>L+E.text):E.type==="tool_use"?v(L=>L+`› ${E.tool} -`):E.type==="error"?w(`AI error: ${E.text||""}`):E.type==="draft"&&(E.text&&o(E.text),E.result&&d(E.result),w("✓ drafted — review + edit, then Create"))},k.onclose=()=>{f(!1),a.current=null},k.onerror=()=>w("draft connection failed")}async function j(b){var k;if(b.preventDefault(),!y.trim()){c({text:"title is required (write one or use Draft with AI)",err:!0});return}c({text:"creating…",err:!1});try{await oe("/gh/issues/create",{repo:t,title:y.trim(),body:u}),(k=a.current)==null||k.close(),n(),r()}catch(x){c({text:x.message,err:!0})}}return s.jsx(hr,{title:`New issue · ${t}`,onClose:r,children:s.jsxs("form",{className:"sc-form",onSubmit:j,children:[s.jsxs("div",{className:"ai-draft",children:[s.jsxs("div",{className:"ai-draft-head",children:[s.jsx("span",{className:"ai-draft-title",children:"✨ Draft with AI"}),s.jsx("span",{className:"ai-warn",title:"Runs your host machine's claude, not the sandbox",children:"host claude · not sandboxed · read-only"})]}),s.jsx("textarea",{rows:2,placeholder:"describe what you want in plain words — the AI researches the repo and drafts the issue",value:i,onChange:b=>h(b.target.value)}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"button",className:"btn ai-draft-btn",disabled:m,onClick:_,children:m?"researching…":"Draft with AI"}),s.jsx("span",{className:"ai-draft-status muted",children:g})]}),S&&s.jsx("pre",{className:"ai-draft-log",ref:l,children:S})]}),s.jsxs("label",{children:["Title ",s.jsx("input",{type:"text",placeholder:"issue title",autoComplete:"off",value:y,onChange:b=>o(b.target.value)})]}),s.jsxs("label",{children:["Body ",s.jsx("textarea",{rows:6,placeholder:"describe the issue (optional)",value:u,onChange:b=>d(b.target.value)})]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",children:"Create issue"}),s.jsx(Ti,{msg:p})]})]})})}function Fm({repo:e,ownerName:t,issue:r,onClose:n}){const{repos:i}=al(),[h,y]=C.useState(!1),[o,u]=C.useState([]),[d,m]=C.useState(null),[f,g]=C.useState(!1),[w,S]=C.useState(null),[v,p]=C.useState(!1),[c,a]=C.useState(""),[l,_]=C.useState(!1);function j(x,N){N&&je(`/p/${x}/populate-prompt`,{prompt:N,submit:v}).catch(()=>{}),window.location.href=`/p/${x}/`}async function b(x,N){try{const E=await je(`/p/${x}/start`),L=await E.json().catch(()=>({}));if(E.status===409&&(L!=null&&L.ssh_keys_pending)){m({text:"load SSH keys to start this project…",err:!1}),S({id:x,prompt:N});return}j(x,N)}catch{j(x,N)}}async function k(x){x.preventDefault(),g(!0),m({text:"spawning…",err:!1});const N=[{repoId:e.id}];for(const L of o){const T=ca(L.text.trim(),L.branch.trim(),i);T&&N.push(T)}const E={mode:"clone",repos:N,name:`${e.name}-${r.number}`,issue:{number:r.number,title:r.title,body:r.body||"",url:r.url,repo:t},enforceAllowlist:h};try{const L=await oe("/projects/create",E);b(L.id,l&&c.trim()?c:L.issue_prompt||"")}catch(L){g(!1),m({text:L.message,err:!0})}}return s.jsxs(hr,{title:`Spawn project · #${r.number}`,onClose:n,children:[s.jsxs("form",{className:"sc-form",onSubmit:k,children:[s.jsxs("div",{className:"spawn-summary",children:[s.jsx("div",{children:"Spawn a project to work on:"}),s.jsxs("div",{className:"issue-titleline",children:[s.jsxs("span",{className:"issue-num",children:["#",r.number]}),s.jsx("span",{className:"issue-title",title:r.title,children:r.title})]}),s.jsxs("div",{className:"muted",style:{fontSize:"0.78rem"},children:["clones ",t," on a new branch, writes ISSUE.md, and pre-types a prompt into Claude."]})]}),s.jsxs("label",{className:"row spawn-fw",style:{marginBottom:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:v,onChange:x=>p(x.target.checked)}),s.jsx("span",{children:"Auto-start — submit the pre-typed prompt to Claude automatically (don't wait for you to press Enter)."})]}),s.jsxs("details",{className:"spawn-advanced",children:[s.jsx("summary",{children:"Advanced"}),s.jsx(Dd,{promptKey:"project.issue",repoId:e.id,value:c,onChange:a,onDirty:()=>_(!0),vars:{repo:t,number:String(r.number),title:r.title}}),s.jsxs("label",{className:"row spawn-fw",style:{marginBottom:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:h,onChange:x=>y(x.target.checked)}),s.jsx("span",{children:"More restrictive — strict allowlist (block unknown domains, no direct TCP). Default is permissive: proxy + mitm on, unknown domains allowed & logged."})]}),s.jsx("div",{className:"repo-rows",children:o.map((x,N)=>s.jsx(Ad,{ghRepos:i,removable:!0,onRemove:()=>u(E=>E.filter((L,T)=>T!==N)),value:x,onChange:E=>u(L=>L.map((T,O)=>O===N?E:T))},N))}),s.jsx("button",{type:"button",className:"btn add-row",onClick:()=>u(x=>[...x,{text:"",branch:""}]),children:"+ add another repo"})]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",disabled:f,children:"Spawn project"}),s.jsx(Ti,{msg:d})]})]}),w&&s.jsx(nn,{projectId:w.id,onDone:x=>{const N=w;S(null),x?(je(`/p/${N.id}/start`).catch(()=>{}),j(N.id,N.prompt)):(g(!1),m({text:"keys not loaded — project created but not started.",err:!0}))}})]})}function Um({search:e,reloadKey:t}){const[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState(null),[u,d]=C.useState(null),[m,f]=C.useState(null),[g,w]=C.useState(null),S=C.useCallback(()=>{ee("/repos").then(l=>{n(l.repos||[]),h(null)}).catch(l=>h(l.message))},[]);C.useEffect(()=>S(),[S,t]);const v=e.trim().toLowerCase(),p=(r||[]).filter(l=>!v||(l.name||"").toLowerCase().includes(v)||(l.url||"").toLowerCase().includes(v)||(l.local_path||"").toLowerCase().includes(v));async function c(l){try{await je(`/repos/${encodeURIComponent(l.id)}/fetch`),S()}catch(_){alert(`refresh failed: ${_.message}`)}}async function a(l){if(window.confirm(`Remove '${l.name}'? Spun-off projects are kept.`))try{await fetch(`/repos/${encodeURIComponent(l.id)}`,{method:"DELETE",credentials:"same-origin"}),S()}catch(_){alert(`remove failed: ${_.message}`)}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"repos-list",children:[i&&s.jsxs("p",{className:"attention",children:["repos error: ",i]}),r&&r.length===0&&s.jsx("p",{className:"muted",children:"No repos cached yet. Add one to spin projects off it quickly."}),r&&r.length>0&&p.length===0&&s.jsxs("p",{className:"muted",children:["No repos match “",e,"”."]}),p.map(l=>{const _=Rd(l.url),j=y===l.id;return s.jsxs("div",{className:"repo-item",children:[s.jsxs("div",{className:"repo-row",children:[s.jsxs("div",{className:"repo-meta",children:[s.jsx("button",{type:"button",className:`repo-pin${l.pinned?" on":""}`,title:l.pinned?"Unpin":"Pin to top",onClick:()=>je(`/repos/${encodeURIComponent(l.id)}/pin`,{pinned:!l.pinned}).then(S),children:l.pinned?"★":"☆"}),l.color&&s.jsx("span",{className:"repo-color-dot",style:{background:l.color},title:"Repo label color"}),s.jsx(be,{className:"repo-name",to:`/repos/${encodeURIComponent(l.id)}`,style:l.color?{color:l.color}:void 0,children:l.name}),s.jsx("span",{className:"repo-src",children:l.url||l.local_path||""}),l.is_private&&s.jsx("span",{className:"repo-badge",children:"private"})]}),s.jsxs("div",{className:"repo-actions",children:[s.jsx("button",{type:"button",className:"btn primary",onClick:()=>d({repoId:l.id}),children:"Create project"}),s.jsx("button",{type:"button",className:`btn${j?" on":""}`,disabled:!_,title:"Browse this repo's GitHub issues",onClick:()=>o(j?null:l.id),children:"Issues"}),s.jsx("button",{type:"button",className:"btn",title:"Refresh cache",onClick:()=>c(l),children:"⟳"}),s.jsx("button",{type:"button",className:"btn",title:"Remove repo",onClick:()=>a(l),children:"✕"})]})]}),j&&_&&s.jsx(zm,{ownerName:_,onNewIssue:()=>f({repo:l,ownerName:_}),onSpawn:b=>w({repo:l,ownerName:_,issue:b})})]},l.id)})]}),u&&s.jsx(ll,{presetRepoId:u.repoId,onClose:()=>d(null)}),m&&s.jsx(Hm,{repoId:m.repo.id,ownerName:m.ownerName,onClose:()=>f(null),onCreated:()=>o(m.repo.id)}),g&&s.jsx(Fm,{repo:g.repo,ownerName:g.ownerName,issue:g.issue,onClose:()=>w(null)})]})}function zm({ownerName:e,onNewIssue:t,onSpawn:r}){const[n,i]=C.useState(null),[h,y]=C.useState(null),o=Date.now(),u=C.useCallback(()=>{i(null),y(null),ee(`/gh/issues?repo=${encodeURIComponent(e)}`).then(d=>{if(!d||!d.available){y((d==null?void 0:d.reason)||"gh error"),i([]);return}i(d.issues||[])}).catch(d=>y(d.message))},[e]);return C.useEffect(()=>u(),[u]),s.jsxs("div",{className:"issues-panel",children:[s.jsxs("div",{className:"issues-head",children:[s.jsx("span",{className:"muted",children:e}),s.jsx("button",{type:"button",className:"btn",onClick:t,children:"+ New issue"})]}),s.jsxs("div",{className:"issues-list",children:[n===null&&s.jsx("div",{className:"ta-loading",children:"loading issues…"}),h&&s.jsxs("div",{className:"muted",children:["couldn't load issues (",h,")"]}),n&&n.length===0&&!h&&s.jsx("div",{className:"muted",children:"no open issues"}),(n||[]).map(d=>{var g;const f=[(g=d.author)!=null&&g.login?`@${d.author.login}`:"",on(d.createdAt,o)].filter(Boolean).join(" · ");return s.jsxs("div",{className:"issue-row",children:[s.jsxs("div",{className:"issue-meta",children:[s.jsxs("div",{className:"issue-titleline",children:[s.jsxs("span",{className:"issue-num",children:["#",d.number]}),s.jsx("span",{className:"issue-title",title:d.title,children:d.title})]}),f&&s.jsx("div",{className:"issue-sub muted",children:f})]}),s.jsx("button",{type:"button",className:"btn primary issue-spawn",onClick:()=>r(d),children:"Spawn"})]},d.number)})]})]})}const Rc="corral.prInbox.lastSeen";function Wm(){const{navigate:e}=ur(),[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState("all"),[o,u]=C.useState(""),[d,m]=C.useState(null),[f,g]=C.useState(""),w=Date.now(),S=C.useMemo(()=>{const L=localStorage.getItem(Rc);return L?Date.parse(L):0},[]);if(C.useEffect(()=>()=>localStorage.setItem(Rc,new Date().toISOString()),[]),C.useEffect(()=>{ee("/prs/inbox").then(L=>{r(L.prs||[]),i(L.currentUser||"")}).catch(L=>m(L.message))},[]),d)return s.jsxs("p",{className:"tab-note err",children:["Failed to load PRs: ",d]});if(t===null)return s.jsx("p",{className:"tab-note",children:"Loading PRs…"});if(t.length===0)return s.jsx("p",{className:"tab-note",children:"No open PRs across your repos. Add a GitHub repo (Repos tab) to see its open PRs here."});const v=n?t.filter(L=>L.pr.author===n).length:0,p=h==="mine"&&n?t.filter(L=>L.pr.author===n):t,c=(()=>{const L=new Map;for(const T of p){const O=L.get(T.repoId);O?O.count++:L.set(T.repoId,{id:T.repoId,name:T.repoName,color:T.repoColor,count:1})}return[...L.values()].sort((T,O)=>O.count-T.count||T.name.localeCompare(O.name))})(),a=o&&c.some(L=>L.id===o)?o:"",l=a?p.filter(L=>L.repoId===a):p,_=f.trim().toLowerCase(),j=_?l.filter(L=>String(L.pr.number).includes(_)||L.pr.title.toLowerCase().includes(_)||L.repoName.toLowerCase().includes(_)||L.pr.author.toLowerCase().includes(_)):l,b=[...j].sort((L,T)=>(T.pr.updatedAt||"").localeCompare(L.pr.updatedAt||"")),k=L=>S>0&&Date.parse(L.pr.updatedAt||"")>S,x=b.filter(k),N=b.filter(L=>!k(L)),E=L=>s.jsxs("li",{className:"pr-row",children:[s.jsxs("button",{type:"button",className:"pr-head",onClick:()=>e(`/repos/${encodeURIComponent(L.repoId)}/prs/${L.pr.number}`),children:[s.jsx("span",{className:"repo-color-chip",style:{borderColor:L.repoColor||"var(--con-line)",color:L.repoColor||"var(--con-muted)"},children:L.repoName}),s.jsxs("span",{className:"pr-num",children:["#",L.pr.number]})," ",L.pr.title,s.jsx(Km,{decision:L.pr.reviewDecision,draft:L.pr.isDraft})]}),s.jsxs("div",{className:"pr-byline",children:[L.pr.author&&s.jsxs("span",{children:["@",L.pr.author]}),s.jsxs("span",{children:[" · updated ",on(L.pr.updatedAt,w)]}),s.jsxs("span",{className:"pr-diffstat",children:[" ",s.jsxs("span",{className:"add",children:["+",L.pr.additions]})," ",s.jsxs("span",{className:"del",children:["−",L.pr.deletions]})]})]})]},`${L.repoId}-${L.pr.number}`);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"pr-scope-tabs",children:[s.jsxs("button",{type:"button",className:`pr-scope-tab${h==="all"?" active":""}`,onClick:()=>y("all"),children:["All ",s.jsx("span",{className:"pr-scope-count",children:t.length})]}),n&&s.jsxs("button",{type:"button",className:`pr-scope-tab${h==="mine"?" active":""}`,onClick:()=>y("mine"),title:`PRs authored by @${n}`,children:["Mine ",s.jsx("span",{className:"pr-scope-count",children:v})]})]}),s.jsxs("div",{className:"pr-toolbar",children:[s.jsx("input",{className:"pr-search",type:"search",placeholder:"🔎 filter PRs by repo, #, title, author…",value:f,onChange:L=>g(L.target.value)}),s.jsxs("span",{className:"pr-toolbar-count",children:[j.length," of ",l.length]})]}),c.length>1&&s.jsxs("div",{className:"pr-repo-badges",children:[s.jsxs("button",{type:"button",className:`pr-repo-badge${a===""?" active":""}`,onClick:()=>u(""),children:["All repos ",s.jsx("span",{className:"pr-repo-badge-count",children:p.length})]}),c.map(L=>s.jsxs("button",{type:"button",className:`pr-repo-badge${a===L.id?" active":""}`,style:a===L.id&&L.color?{borderColor:L.color,color:L.color}:void 0,onClick:()=>u(a===L.id?"":L.id),children:[s.jsx("i",{className:"pr-repo-badge-dot",style:{background:L.color||"var(--con-muted)"}}),L.name," ",s.jsx("span",{className:"pr-repo-badge-count",children:L.count})]},L.id))]}),j.length===0&&s.jsx("p",{className:"tab-note",children:h==="mine"&&l.length===0?`No open PRs authored by @${n}.`:"No PRs match your filter."}),x.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"inbox-divider new",children:"▸ New (updated since last visit)"}),s.jsx("ul",{className:"pr-list",children:x.map(E)})]}),N.length>0&&s.jsxs(s.Fragment,{children:[x.length>0&&s.jsx("div",{className:"inbox-divider",children:"▸ Earlier"}),s.jsx("ul",{className:"pr-list",children:N.map(E)})]})]})}function Km({decision:e,draft:t}){return t?s.jsx("span",{className:"review-badge draft",children:"draft"}):e==="APPROVED"?s.jsx("span",{className:"review-badge approved",children:"✓"}):e==="CHANGES_REQUESTED"?s.jsx("span",{className:"review-badge changes",children:"✗"}):e==="REVIEW_REQUIRED"?s.jsx("span",{className:"review-badge required",children:"○"}):null}function ds(e){C.useEffect(()=>(document.body.classList.add(e),()=>document.body.classList.remove(e)),[e])}const Lc={waiting:0,working:1,off:2};function Vm(e){return e==="working"?"working":e==="waiting"?"waiting on you":"idle"}function qm(e){let t=0,r=0,n=0;for(const h of e)h.activity==="working"?t++:h.activity==="waiting"?r++:n++;const i=[];return r&&i.push(`${r} waiting on you`),t&&i.push(`${t} working`),n&&i.push(`${n} idle`),`${e.length} project${e.length===1?"":"s"}${i.length?" — "+i.join(", "):""}`}function uo({up:e}){return s.jsx("i",{className:`pdot ${e?"on":"off"}`})}function Gm(){ds("console");const{projects:e,bootId:t,connected:r,loaded:n}=xd(3e3),{isMuted:i,mutedAll:h,toggleMute:y,toggleMuteAll:o,forgetMute:u}=Lm(t),{notify:d}=Mm(),m=wd(),[f,g]=C.useState("connecting…"),[w,S]=C.useState(!1),[v,p]=C.useState({}),[c,a]=C.useState(null),[l,_]=C.useState("projects"),[j,b]=C.useState(""),[k,x]=C.useState(0),[N,E]=C.useState(!1),[L,T]=C.useState(!1),O=C.useRef({}),B=C.useRef(!1);C.useEffect(()=>{if(!n)return;if(!r){g("lost connection"),S(!0);return}const R=m.notificationsAllowed();let D=!1;for(const M of e){const P=O.current[M.id],U=M.activity||"off";B.current&&P==="working"&&U==="waiting"&&(R&&!i(M.id)&&(D=!0),R&&d(M.id,M.name)),O.current[M.id]=U}D&&Om(),B.current=!0,g(qm(e)),S(e.some(M=>M.activity==="waiting"))},[e,r,n,i,d,m.quiet]);const F=[...e].sort((R,D)=>{const M=Lc[R.activity]??3,P=Lc[D.activity]??3;if(M!==P)return M-P;const U=R.last_active||0,Y=D.last_active||0;return U!==Y?Y-U:R.name.localeCompare(D.name)});async function z(R){const D=R.container_up;p(M=>({...M,[R.id]:!0}));try{const M=await je(`/p/${encodeURIComponent(R.id)}/${D?"stop":"start"}`),P=await M.json().catch(()=>({}));if(!D&&M.status===409&&(P!=null&&P.ssh_keys_pending)){g(`"${R.name}" needs SSH keys — load them to start.`),S(!0),p(U=>({...U,[R.id]:!1})),a({id:R.id,name:R.name});return}if(M.status>=400)throw new Error((P==null?void 0:P.message)||`HTTP ${M.status}`);g(`${D?"stopping ":"starting "}${R.name}…`),S(!1)}catch(M){g(`${D?"stop":"start"} failed: ${M.message}`),S(!0)}finally{p(M=>({...M,[R.id]:!1}))}}async function K(R,D){try{const M=await je(`/p/${encodeURIComponent(R)}/start`),P=await M.json().catch(()=>({}));if(M.status>=400)throw new Error((P==null?void 0:P.message)||`HTTP ${M.status}`);g(`starting ${D}…`),S(!1)}catch(M){g(`start failed: ${M.message}`),S(!0)}}async function $(R){if(window.confirm(`Remove "${R.name}" from the dashboard? +⚠ draft connection failed`)};return u?s.jsxs("div",{className:"launch-prompt",children:[s.jsxs("div",{className:"launch-prompt-head",children:[s.jsx("span",{children:"Project-start prompt"}),s.jsxs("div",{className:"launch-prompt-head-right",children:[m.length>0&&s.jsxs("select",{className:"launch-prompt-pick",value:"",onChange:k=>{k.target.value&&j(k.target.value),k.target.value=""},title:"Fill from one of your saved prompts",children:[s.jsx("option",{value:"",children:"Use a saved prompt…"}),m.map(k=>s.jsx("option",{value:k.id,children:k.name},k.id))]}),s.jsxs("span",{className:"launch-prompt-src",title:`Inherited from the ${y} prompt`,children:["from: ",y]})]})]}),s.jsx("p",{className:"auto-hint",style:{margin:"0 0 0.35rem"},children:"Sent to Claude when the project starts. Edited here it applies to this launch only — change the saved one under Automations → Prompts."}),s.jsx("textarea",{className:"prompt-textarea",rows:5,value:r,onChange:k=>{n(k.target.value),i==null||i(!0)},placeholder:"You're working in {{repo}} on branch {{branch}}…"}),s.jsx("div",{className:"auto-row",style:{marginTop:"0.3rem"},children:s.jsx("button",{type:"button",className:"auto-btn",onClick:()=>w(k=>!k),children:"✨ Build with AI"})}),g&&s.jsxs("div",{className:"bash-ai",children:[s.jsx("div",{className:"bash-ai-head",children:s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude, not the sandbox; read-only",children:"host · not sandboxed · read-only"})}),s.jsx("textarea",{className:"prompt-textarea",rows:2,value:S,onChange:k=>v(k.target.value),placeholder:"Describe what the prompt should do…"}),s.jsx("button",{type:"button",className:"auto-btn",disabled:p||!S.trim(),onClick:b,children:p?"Drafting…":"Draft with AI"}),a&&s.jsx("pre",{className:"split-menu-ai-log",children:a})]})]}):null}let qt=null,xr=null;function Bm(){return qt?Promise.resolve(qt):xr||(xr=ee("/gh/repos").then(e=>(qt=e&&e.available?e.repos||[]:[],qt)).catch(()=>(qt=[],qt)).finally(()=>{xr=null}),xr)}function al(){const[e,t]=C.useState(qt||[]),[r,n]=C.useState(qt!=null);return C.useEffect(()=>{let i=!0;return Bm().then(h=>{i&&(t(h),n(!0))}),()=>{i=!1}},[]),{repos:e,loaded:r}}function Ti({msg:e}){return e?s.jsx("span",{className:`form-status${e.err?" error":""}`,children:e.text}):s.jsx("span",{className:"form-status"})}function Ad({ghRepos:e,removable:t,onRemove:r,value:n,onChange:i}){const[h,y]=C.useState([]),o=u=>{const d=e.find(f=>f.nameWithOwner===u||f.url===u),m=d?d.nameWithOwner:/^[\w.-]+\/[\w.-]+$/.test(u)?u:null;if(!m){y([]);return}ee(`/gh/branches?repo=${encodeURIComponent(m)}`).then(f=>y(f&&f.available?f.branches||[]:[])).catch(()=>y([]))};return s.jsxs("div",{className:"repo-input-row",children:[s.jsx(ua,{className:"repo-input",placeholder:"pick a repo, or paste a URL / local path",items:Ld(e),value:n.text,onChange:u=>{i({...n,text:u}),o(u)},onPick:o}),s.jsx(ua,{className:"branch-input",placeholder:"branch",items:h.map(u=>({value:u,label:u})),value:n.branch,onChange:u=>i({...n,branch:u})}),s.jsx("button",{type:"button",className:"btn row-rm",title:"Remove",style:{visibility:t?"visible":"hidden"},onClick:r,children:"−"})]})}function ll({presetRepoId:e,presetBranch:t,presetName:r,onClose:n}){var P,B,U;const{repos:i,loaded:h}=al(),[y,o]=C.useState("clone"),[u,d]=C.useState([{text:"",branch:""}]),[m,f]=C.useState(r||""),[g,w]=C.useState(""),[S,v]=C.useState(!1),[p,c]=C.useState(null),[a,l]=C.useState(null),[_,j]=C.useState(!0),[b,k]=C.useState(""),[x,N]=C.useState(!1),E=e||((U=ca(((P=u[0])==null?void 0:P.text.trim())||"",((B=u[0])==null?void 0:B.branch.trim())||"",i))==null?void 0:U.repoId)||"";async function L(K,q){try{const $=await je(`/p/${K}/start`),R=await $.json().catch(()=>({}));if($.status===409&&(R!=null&&R.ssh_keys_pending)){c({text:"load SSH keys to start this project…",err:!1}),l({id:K,prompt:q});return}}catch{}q&&je(`/p/${K}/populate-prompt`,{prompt:q,submit:_}).catch(()=>{}),window.location.href=`/p/${K}/`}async function T(K){K.preventDefault(),c({text:"creating…",err:!1});let q;if(y==="new")q={mode:"new",name:m.trim(),path:g.trim()};else if(y==="existing")q={mode:"existing",path:g.trim()};else{const $=[];e&&$.push({repoId:e,branch:t||void 0});for(const R of u){const A=ca(R.text.trim(),R.branch.trim(),i);A&&$.push(A)}if(!$.length){c({text:"add at least one repo",err:!0});return}q={mode:"clone",name:m.trim(),repos:$}}q.enforceAllowlist=S;try{const $=await oe("/projects/create",q);c({text:"created — starting…",err:!1});const R=x&&b.trim()?b:$.start_prompt||"";await L($.id,R)}catch($){c({text:$.message,err:!0})}}return s.jsxs(hr,{title:"New project",onClose:n,children:[s.jsx("div",{className:"mode-tabs",children:["clone","new","existing"].map(K=>s.jsx("button",{type:"button",className:y===K?"active":"",onClick:()=>o(K),children:K==="clone"?"From repo(s)":K==="new"?"Blank dir":"Existing dir"},K))}),s.jsxs("form",{className:"sc-form",onSubmit:T,children:[y==="clone"&&s.jsxs(s.Fragment,{children:[!h&&s.jsx("div",{className:"ta-loading",children:"loading your repos…"}),s.jsx("div",{className:"repo-rows",children:u.map((K,q)=>s.jsx(Ad,{ghRepos:i,removable:q>0,onRemove:()=>d($=>$.filter((R,A)=>A!==q)),value:K,onChange:$=>d(R=>R.map((A,M)=>M===q?$:A))},q))}),s.jsx("button",{type:"button",className:"btn add-row",onClick:()=>d(K=>[...K,{text:"",branch:""}]),children:"+ add another repo"}),s.jsxs("label",{children:["Project name (optional)",s.jsx("input",{type:"text",placeholder:"defaults from the repo",autoComplete:"off",value:m,onChange:K=>f(K.target.value)})]})]}),y==="new"&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Name ",s.jsx("input",{type:"text",placeholder:"my-project",autoComplete:"off",value:m,onChange:K=>f(K.target.value)})]}),s.jsxs("label",{children:["Location (optional)",s.jsx("input",{type:"text",placeholder:"~/code (default: managed workspaces dir)",autoComplete:"off",value:g,onChange:K=>w(K.target.value)})]}),s.jsxs("div",{className:"muted cfg-note",children:["Parent directory for the new project. Use ",s.jsx("code",{children:"~"}),", an absolute path, or a path relative to your home dir. Leave blank to keep it in corral's managed workspaces."]})]}),y==="existing"&&s.jsxs("label",{children:["Absolute path ",s.jsx("input",{type:"text",placeholder:"/Users/you/code/project",autoComplete:"off",value:g,onChange:K=>w(K.target.value)})]}),y!=="existing"&&s.jsxs("label",{className:"row spawn-fw",style:{marginTop:"0.4rem"},children:[s.jsx("input",{type:"checkbox",checked:_,onChange:K=>j(K.target.checked)}),s.jsx("span",{children:"Auto-send the project-start prompt to Claude when it opens."})]}),s.jsxs("details",{className:"spawn-advanced",children:[s.jsx("summary",{children:"Advanced"}),y!=="existing"&&s.jsx(Dd,{promptKey:"project.start",repoId:E,value:b,onChange:k,onDirty:()=>N(!0)}),s.jsxs("label",{className:"row spawn-fw",children:[s.jsx("input",{type:"checkbox",checked:S,onChange:K=>v(K.target.checked)}),s.jsx("span",{children:"More restrictive — strict allowlist (block unknown domains, no direct TCP). Default is permissive: proxy + mitm on, unknown domains allowed & logged."})]})]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",children:y==="existing"?"Register & start":"Create & start"}),s.jsx(Ti,{msg:p})]})]}),a&&s.jsx(nn,{projectId:a.id,onDone:K=>{const{id:q,prompt:$}=a;l(null),K&&(je(`/p/${q}/start`).catch(()=>{}),$&&je(`/p/${q}/populate-prompt`,{prompt:$,submit:_}).catch(()=>{})),window.location.href=`/p/${q}/`}})]})}function $m({onClose:e,onAdded:t}){const{repos:r,loaded:n}=al(),[i,h]=C.useState(""),[y,o]=C.useState(""),[u,d]=C.useState(!1),[m,f]=C.useState(null);async function g(w){w.preventDefault();const S=i.trim();if(!S){f({text:"pick a repo, or paste a URL / local path",err:!0});return}f({text:"cloning cache mirror…",err:!1});const v=!S.includes("://")&&S.charAt(0)==="/",p=!v&&!S.includes("://")&&S.indexOf("/")>0,c={name:y.trim(),isPrivate:u};v?c.localPath=S:c.url=p?`https://github.com/${S}`:S;try{await oe("/repos",c),t(),e()}catch(a){f({text:a.message,err:!0})}}return s.jsx(hr,{title:"Add repository",onClose:e,children:s.jsxs("form",{className:"sc-form",onSubmit:g,children:[s.jsx("label",{children:"Repository"}),s.jsx(ua,{className:"repo-input",placeholder:"search your GitHub repos, or paste a URL / local path",items:Ld(r),value:i,autoFocus:!0,onChange:h,onPick:w=>{const S=r.find(v=>v.nameWithOwner===w);S&&d(!!S.isPrivate)}}),!n&&s.jsx("div",{className:"ta-loading",children:"loading your GitHub repos…"}),n&&r.length===0&&s.jsx("div",{className:"muted",children:"no GitHub repos found (paste a URL or local path instead)"}),s.jsxs("label",{children:["Name (optional) ",s.jsx("input",{type:"text",placeholder:"defaults from the repo",autoComplete:"off",value:y,onChange:w=>o(w.target.value)})]}),s.jsxs("label",{className:"row",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:w=>d(w.target.checked)})," Private (clone with your host git/gh auth)"]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",children:"Add"}),s.jsx(Ti,{msg:m})]})]})})}function Hm({repoId:e,ownerName:t,onClose:r,onCreated:n}){const[i,h]=C.useState(""),[y,o]=C.useState(""),[u,d]=C.useState(""),[m,f]=C.useState(!1),[g,w]=C.useState(""),[S,v]=C.useState(""),[p,c]=C.useState(null),a=C.useRef(null),l=C.useRef(null);C.useEffect(()=>{l.current&&(l.current.scrollTop=l.current.scrollHeight)},[S]),C.useEffect(()=>()=>{var b;return(b=a.current)==null?void 0:b.close()},[]);function _(){var x;const b=i.trim();if(!b){w("describe what you want first");return}(x=a.current)==null||x.close(),f(!0),w(""),v("");const k=new WebSocket(hs(`/gh/issues/draft?repoId=${encodeURIComponent(e)}`));a.current=k,k.onopen=()=>k.send(JSON.stringify({description:b})),k.onmessage=N=>{let E;try{E=JSON.parse(N.data)}catch{return}E.type==="text"?v(L=>L+E.text):E.type==="tool_use"?v(L=>L+`› ${E.tool} +`):E.type==="error"?w(`AI error: ${E.text||""}`):E.type==="draft"&&(E.text&&o(E.text),E.result&&d(E.result),w("✓ drafted — review + edit, then Create"))},k.onclose=()=>{f(!1),a.current=null},k.onerror=()=>w("draft connection failed")}async function j(b){var k;if(b.preventDefault(),!y.trim()){c({text:"title is required (write one or use Draft with AI)",err:!0});return}c({text:"creating…",err:!1});try{await oe("/gh/issues/create",{repo:t,title:y.trim(),body:u}),(k=a.current)==null||k.close(),n(),r()}catch(x){c({text:x.message,err:!0})}}return s.jsx(hr,{title:`New issue · ${t}`,onClose:r,children:s.jsxs("form",{className:"sc-form",onSubmit:j,children:[s.jsxs("div",{className:"ai-draft",children:[s.jsxs("div",{className:"ai-draft-head",children:[s.jsx("span",{className:"ai-draft-title",children:"✨ Draft with AI"}),s.jsx("span",{className:"ai-warn",title:"Runs your host machine's claude, not the sandbox",children:"host claude · not sandboxed · read-only"})]}),s.jsx("textarea",{rows:2,placeholder:"describe what you want in plain words — the AI researches the repo and drafts the issue",value:i,onChange:b=>h(b.target.value)}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"button",className:"btn ai-draft-btn",disabled:m,onClick:_,children:m?"researching…":"Draft with AI"}),s.jsx("span",{className:"ai-draft-status muted",children:g})]}),S&&s.jsx("pre",{className:"ai-draft-log",ref:l,children:S})]}),s.jsxs("label",{children:["Title ",s.jsx("input",{type:"text",placeholder:"issue title",autoComplete:"off",value:y,onChange:b=>o(b.target.value)})]}),s.jsxs("label",{children:["Body ",s.jsx("textarea",{rows:6,placeholder:"describe the issue (optional)",value:u,onChange:b=>d(b.target.value)})]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",children:"Create issue"}),s.jsx(Ti,{msg:p})]})]})})}function Fm({repo:e,ownerName:t,issue:r,onClose:n}){const{repos:i}=al(),[h,y]=C.useState(!1),[o,u]=C.useState([]),[d,m]=C.useState(null),[f,g]=C.useState(!1),[w,S]=C.useState(null),[v,p]=C.useState(!1),[c,a]=C.useState(""),[l,_]=C.useState(!1);function j(x,N){N&&je(`/p/${x}/populate-prompt`,{prompt:N,submit:v}).catch(()=>{}),window.location.href=`/p/${x}/`}async function b(x,N){try{const E=await je(`/p/${x}/start`),L=await E.json().catch(()=>({}));if(E.status===409&&(L!=null&&L.ssh_keys_pending)){m({text:"load SSH keys to start this project…",err:!1}),S({id:x,prompt:N});return}j(x,N)}catch{j(x,N)}}async function k(x){x.preventDefault(),g(!0),m({text:"spawning…",err:!1});const N=[{repoId:e.id}];for(const L of o){const T=ca(L.text.trim(),L.branch.trim(),i);T&&N.push(T)}const E={mode:"clone",repos:N,name:`${e.name}-${r.number}`,issue:{number:r.number,title:r.title,body:r.body||"",url:r.url,repo:t},enforceAllowlist:h};try{const L=await oe("/projects/create",E);b(L.id,l&&c.trim()?c:L.issue_prompt||"")}catch(L){g(!1),m({text:L.message,err:!0})}}return s.jsxs(hr,{title:`Spawn project · #${r.number}`,onClose:n,children:[s.jsxs("form",{className:"sc-form",onSubmit:k,children:[s.jsxs("div",{className:"spawn-summary",children:[s.jsx("div",{children:"Spawn a project to work on:"}),s.jsxs("div",{className:"issue-titleline",children:[s.jsxs("span",{className:"issue-num",children:["#",r.number]}),s.jsx("span",{className:"issue-title",title:r.title,children:r.title})]}),s.jsxs("div",{className:"muted",style:{fontSize:"0.78rem"},children:["clones ",t," on a new branch, writes ISSUE.md, and pre-types a prompt into Claude."]})]}),s.jsxs("label",{className:"row spawn-fw",style:{marginBottom:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:v,onChange:x=>p(x.target.checked)}),s.jsx("span",{children:"Auto-start — submit the pre-typed prompt to Claude automatically (don't wait for you to press Enter)."})]}),s.jsxs("details",{className:"spawn-advanced",children:[s.jsx("summary",{children:"Advanced"}),s.jsx(Dd,{promptKey:"project.issue",repoId:e.id,value:c,onChange:a,onDirty:()=>_(!0),vars:{repo:t,number:String(r.number),title:r.title}}),s.jsxs("label",{className:"row spawn-fw",style:{marginBottom:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:h,onChange:x=>y(x.target.checked)}),s.jsx("span",{children:"More restrictive — strict allowlist (block unknown domains, no direct TCP). Default is permissive: proxy + mitm on, unknown domains allowed & logged."})]}),s.jsx("div",{className:"repo-rows",children:o.map((x,N)=>s.jsx(Ad,{ghRepos:i,removable:!0,onRemove:()=>u(E=>E.filter((L,T)=>T!==N)),value:x,onChange:E=>u(L=>L.map((T,P)=>P===N?E:T))},N))}),s.jsx("button",{type:"button",className:"btn add-row",onClick:()=>u(x=>[...x,{text:"",branch:""}]),children:"+ add another repo"})]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{type:"submit",className:"btn primary",disabled:f,children:"Spawn project"}),s.jsx(Ti,{msg:d})]})]}),w&&s.jsx(nn,{projectId:w.id,onDone:x=>{const N=w;S(null),x?(je(`/p/${N.id}/start`).catch(()=>{}),j(N.id,N.prompt)):(g(!1),m({text:"keys not loaded — project created but not started.",err:!0}))}})]})}function Um({search:e,reloadKey:t}){const[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState(null),[u,d]=C.useState(null),[m,f]=C.useState(null),[g,w]=C.useState(null),S=C.useCallback(()=>{ee("/repos").then(l=>{n(l.repos||[]),h(null)}).catch(l=>h(l.message))},[]);C.useEffect(()=>S(),[S,t]);const v=e.trim().toLowerCase(),p=(r||[]).filter(l=>!v||(l.name||"").toLowerCase().includes(v)||(l.url||"").toLowerCase().includes(v)||(l.local_path||"").toLowerCase().includes(v));async function c(l){try{await je(`/repos/${encodeURIComponent(l.id)}/fetch`),S()}catch(_){alert(`refresh failed: ${_.message}`)}}async function a(l){if(window.confirm(`Remove '${l.name}'? Spun-off projects are kept.`))try{await fetch(`/repos/${encodeURIComponent(l.id)}`,{method:"DELETE",credentials:"same-origin"}),S()}catch(_){alert(`remove failed: ${_.message}`)}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"repos-list",children:[i&&s.jsxs("p",{className:"attention",children:["repos error: ",i]}),r&&r.length===0&&s.jsx("p",{className:"muted",children:"No repos cached yet. Add one to spin projects off it quickly."}),r&&r.length>0&&p.length===0&&s.jsxs("p",{className:"muted",children:["No repos match “",e,"”."]}),p.map(l=>{const _=Rd(l.url),j=y===l.id;return s.jsxs("div",{className:"repo-item",children:[s.jsxs("div",{className:"repo-row",children:[s.jsxs("div",{className:"repo-meta",children:[s.jsx("button",{type:"button",className:`repo-pin${l.pinned?" on":""}`,title:l.pinned?"Unpin":"Pin to top",onClick:()=>je(`/repos/${encodeURIComponent(l.id)}/pin`,{pinned:!l.pinned}).then(S),children:l.pinned?"★":"☆"}),l.color&&s.jsx("span",{className:"repo-color-dot",style:{background:l.color},title:"Repo label color"}),s.jsx(be,{className:"repo-name",to:`/repos/${encodeURIComponent(l.id)}`,style:l.color?{color:l.color}:void 0,children:l.name}),s.jsx("span",{className:"repo-src",children:l.url||l.local_path||""}),l.is_private&&s.jsx("span",{className:"repo-badge",children:"private"})]}),s.jsxs("div",{className:"repo-actions",children:[s.jsx("button",{type:"button",className:"btn primary",onClick:()=>d({repoId:l.id}),children:"Create project"}),s.jsx("button",{type:"button",className:`btn${j?" on":""}`,disabled:!_,title:"Browse this repo's GitHub issues",onClick:()=>o(j?null:l.id),children:"Issues"}),s.jsx("button",{type:"button",className:"btn",title:"Refresh cache",onClick:()=>c(l),children:"⟳"}),s.jsx("button",{type:"button",className:"btn",title:"Remove repo",onClick:()=>a(l),children:"✕"})]})]}),j&&_&&s.jsx(zm,{ownerName:_,onNewIssue:()=>f({repo:l,ownerName:_}),onSpawn:b=>w({repo:l,ownerName:_,issue:b})})]},l.id)})]}),u&&s.jsx(ll,{presetRepoId:u.repoId,onClose:()=>d(null)}),m&&s.jsx(Hm,{repoId:m.repo.id,ownerName:m.ownerName,onClose:()=>f(null),onCreated:()=>o(m.repo.id)}),g&&s.jsx(Fm,{repo:g.repo,ownerName:g.ownerName,issue:g.issue,onClose:()=>w(null)})]})}function zm({ownerName:e,onNewIssue:t,onSpawn:r}){const[n,i]=C.useState(null),[h,y]=C.useState(null),o=Date.now(),u=C.useCallback(()=>{i(null),y(null),ee(`/gh/issues?repo=${encodeURIComponent(e)}`).then(d=>{if(!d||!d.available){y((d==null?void 0:d.reason)||"gh error"),i([]);return}i(d.issues||[])}).catch(d=>y(d.message))},[e]);return C.useEffect(()=>u(),[u]),s.jsxs("div",{className:"issues-panel",children:[s.jsxs("div",{className:"issues-head",children:[s.jsx("span",{className:"muted",children:e}),s.jsx("button",{type:"button",className:"btn",onClick:t,children:"+ New issue"})]}),s.jsxs("div",{className:"issues-list",children:[n===null&&s.jsx("div",{className:"ta-loading",children:"loading issues…"}),h&&s.jsxs("div",{className:"muted",children:["couldn't load issues (",h,")"]}),n&&n.length===0&&!h&&s.jsx("div",{className:"muted",children:"no open issues"}),(n||[]).map(d=>{var g;const f=[(g=d.author)!=null&&g.login?`@${d.author.login}`:"",on(d.createdAt,o)].filter(Boolean).join(" · ");return s.jsxs("div",{className:"issue-row",children:[s.jsxs("div",{className:"issue-meta",children:[s.jsxs("div",{className:"issue-titleline",children:[s.jsxs("span",{className:"issue-num",children:["#",d.number]}),s.jsx("span",{className:"issue-title",title:d.title,children:d.title})]}),f&&s.jsx("div",{className:"issue-sub muted",children:f})]}),s.jsx("button",{type:"button",className:"btn primary issue-spawn",onClick:()=>r(d),children:"Spawn"})]},d.number)})]})]})}const Rc="corral.prInbox.lastSeen";function Wm(){const{navigate:e}=ur(),[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState("all"),[o,u]=C.useState(""),[d,m]=C.useState(null),[f,g]=C.useState(""),w=Date.now(),S=C.useMemo(()=>{const L=localStorage.getItem(Rc);return L?Date.parse(L):0},[]);if(C.useEffect(()=>()=>localStorage.setItem(Rc,new Date().toISOString()),[]),C.useEffect(()=>{ee("/prs/inbox").then(L=>{r(L.prs||[]),i(L.currentUser||"")}).catch(L=>m(L.message))},[]),d)return s.jsxs("p",{className:"tab-note err",children:["Failed to load PRs: ",d]});if(t===null)return s.jsx("p",{className:"tab-note",children:"Loading PRs…"});if(t.length===0)return s.jsx("p",{className:"tab-note",children:"No open PRs across your repos. Add a GitHub repo (Repos tab) to see its open PRs here."});const v=n?t.filter(L=>L.pr.author===n).length:0,p=h==="mine"&&n?t.filter(L=>L.pr.author===n):t,c=(()=>{const L=new Map;for(const T of p){const P=L.get(T.repoId);P?P.count++:L.set(T.repoId,{id:T.repoId,name:T.repoName,color:T.repoColor,count:1})}return[...L.values()].sort((T,P)=>P.count-T.count||T.name.localeCompare(P.name))})(),a=o&&c.some(L=>L.id===o)?o:"",l=a?p.filter(L=>L.repoId===a):p,_=f.trim().toLowerCase(),j=_?l.filter(L=>String(L.pr.number).includes(_)||L.pr.title.toLowerCase().includes(_)||L.repoName.toLowerCase().includes(_)||L.pr.author.toLowerCase().includes(_)):l,b=[...j].sort((L,T)=>(T.pr.updatedAt||"").localeCompare(L.pr.updatedAt||"")),k=L=>S>0&&Date.parse(L.pr.updatedAt||"")>S,x=b.filter(k),N=b.filter(L=>!k(L)),E=L=>s.jsxs("li",{className:"pr-row",children:[s.jsxs("button",{type:"button",className:"pr-head",onClick:()=>e(`/repos/${encodeURIComponent(L.repoId)}/prs/${L.pr.number}`),children:[s.jsx("span",{className:"repo-color-chip",style:{borderColor:L.repoColor||"var(--con-line)",color:L.repoColor||"var(--con-muted)"},children:L.repoName}),s.jsxs("span",{className:"pr-num",children:["#",L.pr.number]})," ",L.pr.title,s.jsx(Km,{decision:L.pr.reviewDecision,draft:L.pr.isDraft})]}),s.jsxs("div",{className:"pr-byline",children:[L.pr.author&&s.jsxs("span",{children:["@",L.pr.author]}),s.jsxs("span",{children:[" · updated ",on(L.pr.updatedAt,w)]}),s.jsxs("span",{className:"pr-diffstat",children:[" ",s.jsxs("span",{className:"add",children:["+",L.pr.additions]})," ",s.jsxs("span",{className:"del",children:["−",L.pr.deletions]})]})]})]},`${L.repoId}-${L.pr.number}`);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"pr-scope-tabs",children:[s.jsxs("button",{type:"button",className:`pr-scope-tab${h==="all"?" active":""}`,onClick:()=>y("all"),children:["All ",s.jsx("span",{className:"pr-scope-count",children:t.length})]}),n&&s.jsxs("button",{type:"button",className:`pr-scope-tab${h==="mine"?" active":""}`,onClick:()=>y("mine"),title:`PRs authored by @${n}`,children:["Mine ",s.jsx("span",{className:"pr-scope-count",children:v})]})]}),s.jsxs("div",{className:"pr-toolbar",children:[s.jsx("input",{className:"pr-search",type:"search",placeholder:"🔎 filter PRs by repo, #, title, author…",value:f,onChange:L=>g(L.target.value)}),s.jsxs("span",{className:"pr-toolbar-count",children:[j.length," of ",l.length]})]}),c.length>1&&s.jsxs("div",{className:"pr-repo-badges",children:[s.jsxs("button",{type:"button",className:`pr-repo-badge${a===""?" active":""}`,onClick:()=>u(""),children:["All repos ",s.jsx("span",{className:"pr-repo-badge-count",children:p.length})]}),c.map(L=>s.jsxs("button",{type:"button",className:`pr-repo-badge${a===L.id?" active":""}`,style:a===L.id&&L.color?{borderColor:L.color,color:L.color}:void 0,onClick:()=>u(a===L.id?"":L.id),children:[s.jsx("i",{className:"pr-repo-badge-dot",style:{background:L.color||"var(--con-muted)"}}),L.name," ",s.jsx("span",{className:"pr-repo-badge-count",children:L.count})]},L.id))]}),j.length===0&&s.jsx("p",{className:"tab-note",children:h==="mine"&&l.length===0?`No open PRs authored by @${n}.`:"No PRs match your filter."}),x.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"inbox-divider new",children:"▸ New (updated since last visit)"}),s.jsx("ul",{className:"pr-list",children:x.map(E)})]}),N.length>0&&s.jsxs(s.Fragment,{children:[x.length>0&&s.jsx("div",{className:"inbox-divider",children:"▸ Earlier"}),s.jsx("ul",{className:"pr-list",children:N.map(E)})]})]})}function Km({decision:e,draft:t}){return t?s.jsx("span",{className:"review-badge draft",children:"draft"}):e==="APPROVED"?s.jsx("span",{className:"review-badge approved",children:"✓"}):e==="CHANGES_REQUESTED"?s.jsx("span",{className:"review-badge changes",children:"✗"}):e==="REVIEW_REQUIRED"?s.jsx("span",{className:"review-badge required",children:"○"}):null}function ds(e){C.useEffect(()=>(document.body.classList.add(e),()=>document.body.classList.remove(e)),[e])}const Lc={waiting:0,working:1,off:2};function Vm(e){return e==="working"?"working":e==="waiting"?"waiting on you":"idle"}function qm(e){let t=0,r=0,n=0;for(const h of e)h.activity==="working"?t++:h.activity==="waiting"?r++:n++;const i=[];return r&&i.push(`${r} waiting on you`),t&&i.push(`${t} working`),n&&i.push(`${n} idle`),`${e.length} project${e.length===1?"":"s"}${i.length?" — "+i.join(", "):""}`}function uo({up:e}){return s.jsx("i",{className:`pdot ${e?"on":"off"}`})}function Gm(){ds("console");const{projects:e,bootId:t,connected:r,loaded:n}=xd(3e3),{isMuted:i,mutedAll:h,toggleMute:y,toggleMuteAll:o,forgetMute:u}=Lm(t),{notify:d}=Mm(),m=wd(),[f,g]=C.useState("connecting…"),[w,S]=C.useState(!1),[v,p]=C.useState({}),[c,a]=C.useState(null),[l,_]=C.useState("projects"),[j,b]=C.useState(""),[k,x]=C.useState(0),[N,E]=C.useState(!1),[L,T]=C.useState(!1),P=C.useRef({}),B=C.useRef(!1);C.useEffect(()=>{if(!n)return;if(!r){g("lost connection"),S(!0);return}const R=m.notificationsAllowed();let A=!1;for(const M of e){const O=P.current[M.id],W=M.activity||"off";B.current&&O==="working"&&W==="waiting"&&(R&&!i(M.id)&&(A=!0),R&&d(M.id,M.name)),P.current[M.id]=W}A&&Om(),B.current=!0,g(qm(e)),S(e.some(M=>M.activity==="waiting"))},[e,r,n,i,d,m.quiet]);const U=[...e].sort((R,A)=>{const M=Lc[R.activity]??3,O=Lc[A.activity]??3;if(M!==O)return M-O;const W=R.last_active||0,F=A.last_active||0;return W!==F?F-W:R.name.localeCompare(A.name)});async function K(R){const A=R.container_up;p(M=>({...M,[R.id]:!0}));try{const M=await je(`/p/${encodeURIComponent(R.id)}/${A?"stop":"start"}`),O=await M.json().catch(()=>({}));if(!A&&M.status===409&&(O!=null&&O.ssh_keys_pending)){g(`"${R.name}" needs SSH keys — load them to start.`),S(!0),p(W=>({...W,[R.id]:!1})),a({id:R.id,name:R.name});return}if(M.status>=400)throw new Error((O==null?void 0:O.message)||`HTTP ${M.status}`);g(`${A?"stopping ":"starting "}${R.name}…`),S(!1)}catch(M){g(`${A?"stop":"start"} failed: ${M.message}`),S(!0)}finally{p(M=>({...M,[R.id]:!1}))}}async function q(R,A){try{const M=await je(`/p/${encodeURIComponent(R)}/start`),O=await M.json().catch(()=>({}));if(M.status>=400)throw new Error((O==null?void 0:O.message)||`HTTP ${M.status}`);g(`starting ${A}…`),S(!1)}catch(M){g(`start failed: ${M.message}`),S(!0)}}async function $(R){if(window.confirm(`Remove "${R.name}" from the dashboard? -This only unregisters it here — its .corral/ config and logs are kept, and it reappears if you start it again.`))try{const D=await je(`/p/${encodeURIComponent(R.id)}/remove`);if(!D.ok)throw new Error(`HTTP ${D.status}`);u(R.id)}catch(D){g(`remove failed: ${D.message}`),S(!0)}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"app-shell",children:[s.jsxs("nav",{className:"sidebar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:"◇"}),s.jsx("span",{className:"brand-name",children:"corral"})]}),s.jsxs("button",{type:"button",className:`nav-item${l==="projects"?" active":""}`,onClick:()=>_("projects"),children:[s.jsx("span",{className:"nav-ico",children:"▤"})," Projects"]}),s.jsxs("button",{type:"button",className:`nav-item${l==="repos"?" active":""}`,onClick:()=>_("repos"),children:[s.jsx("span",{className:"nav-ico",children:"◧"})," Repos"]}),s.jsxs("button",{type:"button",className:`nav-item${l==="prs"?" active":""}`,onClick:()=>_("prs"),children:[s.jsx("span",{className:"nav-ico",children:"⑃"})," PRs"]}),s.jsx("div",{className:"nav-sep"}),s.jsxs(be,{to:"/automations",className:"nav-item nav-link nav-automations",children:[s.jsx("span",{className:"nav-ico",children:"⚡"})," Automations"]}),s.jsxs(be,{to:"/logs",className:"nav-item nav-link",children:[s.jsx("span",{className:"nav-ico",children:"📋"})," Logs"]}),s.jsxs(be,{to:"/integrations",className:"nav-item nav-link",children:[s.jsx("span",{className:"nav-ico",children:"🔌"})," Integrations"]}),s.jsx("div",{className:"sidebar-spacer"}),s.jsx("button",{type:"button",className:"sidebar-cta",title:"Create a new project",onClick:()=>E(!0),children:"+ New project"}),s.jsx(be,{to:"/global",className:"nav-item nav-link",children:"⚙ Global settings"})]}),s.jsxs("div",{className:"content",children:[s.jsxs("header",{className:"content-head",children:[s.jsx("h1",{id:"section-title",children:l==="repos"?"Repos":l==="prs"?"PRs":"Projects"}),s.jsxs("div",{className:"head-right",children:[s.jsxs("div",{className:"legend",children:[s.jsxs("span",{className:"legend-item",children:[s.jsx("i",{className:"dot working"}),"working"]}),s.jsxs("span",{className:"legend-item",children:[s.jsx("i",{className:"dot waiting"}),"waiting"]}),s.jsxs("span",{className:"legend-item",children:[s.jsx("i",{className:"dot off"}),"idle"]})]}),s.jsx(Pm,{dnd:m}),s.jsx("button",{type:"button",className:"btn mute-all","aria-pressed":h,title:h?"Unmute all alerts":"Mute all alerts",onClick:o,children:h?"🔇 muted":"🔔 alerts"})]})]}),l==="repos"&&s.jsxs("section",{className:"section active",children:[s.jsxs("div",{className:"section-toolbar",children:[s.jsx("input",{className:"section-search",type:"search",placeholder:"Filter repos…",autoComplete:"off",spellCheck:!1,value:j,onChange:R=>b(R.target.value)}),s.jsx("button",{type:"button",className:"btn primary",title:"Add a repository",onClick:()=>T(!0),children:"+ Add repo"})]}),s.jsx(Um,{search:j,reloadKey:k})]}),l==="prs"&&s.jsx("section",{className:"section active",children:s.jsx(Wm,{})}),s.jsx("section",{className:"section active",style:{display:l==="projects"?"":"none"},children:s.jsxs("main",{className:"panes",children:[!n&&Array.from({length:3}).map((R,D)=>s.jsxs("div",{className:"pane pane-skeleton","aria-hidden":"true",children:[s.jsxs("div",{className:"pane-top",children:[s.jsx("span",{className:"pane-name skel skel-line",style:{width:"40%"}}),s.jsx("span",{className:"skel skel-line",style:{width:"5rem"}})]}),s.jsx("div",{className:"pane-peek",children:s.jsx("span",{className:"skel skel-line",style:{width:"70%"}})}),s.jsxs("div",{className:"pane-foot",children:[s.jsx("span",{className:"skel skel-line",style:{width:"3rem"}}),s.jsx("span",{className:"skel skel-line",style:{width:"3rem"}}),s.jsx("span",{className:"skel skel-line",style:{width:"3rem"}})]})]},`sk-${D}`)),n&&F.length===0&&s.jsxs("p",{className:"empty",children:["No projects yet. Start one with ",s.jsx("code",{children:"corral init"})," then ",s.jsx("code",{children:"corral start"}),"."]}),F.map(R=>{const D=R.activity||"off",M=R.peek||(D==="off"?"container not running":"…"),P=i(R.id);return s.jsxs(be,{className:`pane pane-${D}`,to:`/p/${R.id}`,children:[s.jsxs("div",{className:"pane-top",children:[s.jsx("span",{className:"pane-name",children:R.name}),s.jsxs("span",{className:`pane-state state-${D}`,children:[s.jsx("i",{className:"beacon"}),Vm(D),s.jsx("button",{className:`power-btn ${R.container_up?"stop":"start"}`,type:"button",disabled:v[R.id],title:R.container_up?"Stop this project's container":"Start this project's container",onClick:U=>{U.preventDefault(),U.stopPropagation(),z(R)},children:v[R.id]?s.jsx("span",{className:"power-spin",children:"↻"}):R.container_up?"■":"▶"}),s.jsx("button",{className:"mute-btn",type:"button","aria-pressed":P,title:P?"Unmute alerts for this project":"Mute alerts for this project",onClick:U=>{U.preventDefault(),U.stopPropagation(),y(R.id)},children:P?"🔇":"🔔"}),D==="off"&&s.jsx("button",{className:"remove-btn",type:"button",title:"Remove this idle project from the dashboard",onClick:U=>{U.preventDefault(),U.stopPropagation(),$(R)},children:"✕"})]})]}),s.jsxs("div",{className:"pane-peek",children:[s.jsx("span",{className:"peek-caret",children:">"})," ",M]}),s.jsxs("div",{className:"pane-foot",children:[s.jsxs("span",{className:"svc",children:[s.jsx(uo,{up:R.container_up}),"box"]}),s.jsxs("span",{className:"svc",children:[s.jsx(uo,{up:R.mitm_up}),"proxy"]}),s.jsxs("span",{className:"svc",children:[s.jsx(uo,{up:R.tmux_up}),"session"]}),D==="working"&&s.jsxs("span",{className:"rate",children:[R.anthropic_hits," req/min · live"]}),D==="waiting"&&s.jsx("span",{className:"rate quiet",children:"idle at prompt"})]})]},R.id)})]})})]})]}),s.jsx("footer",{className:"console-footer",children:s.jsx("span",{className:w?"attention":"muted",children:f})}),c&&s.jsx(nn,{projectId:c.id,onDone:R=>{const{id:D,name:M}=c;a(null),R?K(D,M):(g(`"${M}" — keys not loaded; start canceled.`),S(!0))}}),N&&s.jsx(ll,{onClose:()=>E(!1)}),L&&s.jsx($m,{onClose:()=>T(!1),onAdded:()=>{_("repos"),x(R=>R+1)}})]})}function it(e,t){const[r,n]=C.useState(()=>{try{const h=localStorage.getItem(e);if(h!=null)return JSON.parse(h)}catch{}return t}),i=C.useCallback(h=>{n(y=>{const o=typeof h=="function"?h(y):h;try{localStorage.setItem(e,JSON.stringify(o))}catch{}return o})},[e]);return[r,i]}function Qs(e){const t=C.useRef(e);return t.current=e,C.useCallback(r=>{if(!r)return;const n=i=>{i.preventDefault();const h=t.current,y=h.axis==="x"?i.clientX:i.clientY,o=h.get();r.setPointerCapture(i.pointerId),document.body.style.userSelect="none",document.body.style.cursor=h.axis==="x"?"ew-resize":"ns-resize";const u=m=>{const f=t.current;let w=(f.axis==="x"?m.clientX:m.clientY)-y;f.edge==="start"&&(w=-w),f.onResize(Math.max(f.min,Math.min(f.max(),o+w)))},d=m=>{try{r.releasePointerCapture(m.pointerId)}catch{}document.body.style.userSelect="",document.body.style.cursor="",r.removeEventListener("pointermove",u),r.removeEventListener("pointerup",d)};r.addEventListener("pointermove",u),r.addEventListener("pointerup",d)};r.addEventListener("pointerdown",n)},[])}function Jm({x:e,y:t,canSplit:r,onAction:n,onClose:i}){const h=C.useRef(null);C.useEffect(()=>{const o=d=>{h.current&&!h.current.contains(d.target)&&i()},u=d=>d.key==="Escape"&&i();return document.addEventListener("mousedown",o),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",o),document.removeEventListener("keydown",u)}},[i]);const y={left:Math.min(e,window.innerWidth-190),top:Math.min(t,window.innerHeight-220)};return s.jsxs("div",{className:"term-menu",ref:h,style:y,onContextMenu:o=>o.preventDefault(),children:[r&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"term-menu-item",onClick:()=>n("split-h"),children:"Split right"}),s.jsx("button",{className:"term-menu-item",onClick:()=>n("split-v"),children:"Split down"}),s.jsx("div",{className:"term-menu-sep"})]}),s.jsxs("button",{className:"term-menu-item",onClick:()=>n("copy"),children:["Copy ",s.jsx("span",{className:"term-menu-key",children:"⌘C"})]}),s.jsxs("button",{className:"term-menu-item",onClick:()=>n("paste"),children:["Paste ",s.jsx("span",{className:"term-menu-key",children:"⌘V"})]}),s.jsx("button",{className:"term-menu-item",onClick:()=>n("clear"),children:"Clear"}),r&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"term-menu-sep"}),s.jsx("button",{className:"term-menu-item term-menu-danger",onClick:()=>n("kill-pane"),children:"Close pane"})]})]})}function Zs({projectId:e,wsPath:t,fullPath:r,kind:n}){const i=C.useRef(null),h=C.useRef(null),y=C.useRef(null),[o,u]=C.useState(null),d=r??`/p/${e}${t}`;C.useEffect(()=>{const g=new jd.Terminal({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:13,theme:{background:"#0B0E14",selectionBackground:"#2e5aa0",selectionForeground:"#ffffff"},scrollback:1e4,macOptionClickForcesSelection:!0});h.current=g,g.parser.registerOscHandler(52,E=>{var T;const L=E.slice(E.indexOf(";")+1);if(!L||L==="?")return!0;try{const O=new TextDecoder().decode(Uint8Array.from(atob(L),B=>B.charCodeAt(0)));(T=navigator.clipboard)==null||T.writeText(O).catch(()=>{})}catch{}return!0});const w=new Ed.FitAddon;g.loadAddon(w),i.current&&(g.open(i.current),i.current.clientWidth>0&&i.current.clientHeight>0&&w.fit());const S=new WebSocket(hs(d));y.current=S,S.binaryType="arraybuffer";const v=new TextDecoder,p=()=>{S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:g.cols,rows:g.rows}))};S.onopen=()=>{p(),g.focus()},S.onmessage=E=>{g.write(typeof E.data=="string"?E.data:v.decode(new Uint8Array(E.data)))},S.onclose=()=>{g.write(`\r +This only unregisters it here — its .corral/ config and logs are kept, and it reappears if you start it again.`))try{const A=await je(`/p/${encodeURIComponent(R.id)}/remove`);if(!A.ok)throw new Error(`HTTP ${A.status}`);u(R.id)}catch(A){g(`remove failed: ${A.message}`),S(!0)}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"app-shell",children:[s.jsxs("nav",{className:"sidebar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:"◇"}),s.jsx("span",{className:"brand-name",children:"corral"})]}),s.jsxs("button",{type:"button",className:`nav-item${l==="projects"?" active":""}`,onClick:()=>_("projects"),children:[s.jsx("span",{className:"nav-ico",children:"▤"})," Projects"]}),s.jsxs("button",{type:"button",className:`nav-item${l==="repos"?" active":""}`,onClick:()=>_("repos"),children:[s.jsx("span",{className:"nav-ico",children:"◧"})," Repos"]}),s.jsxs("button",{type:"button",className:`nav-item${l==="prs"?" active":""}`,onClick:()=>_("prs"),children:[s.jsx("span",{className:"nav-ico",children:"⑃"})," PRs"]}),s.jsx("div",{className:"nav-sep"}),s.jsxs(be,{to:"/automations",className:"nav-item nav-link nav-automations",children:[s.jsx("span",{className:"nav-ico",children:"⚡"})," Automations"]}),s.jsxs(be,{to:"/logs",className:"nav-item nav-link",children:[s.jsx("span",{className:"nav-ico",children:"📋"})," Logs"]}),s.jsxs(be,{to:"/integrations",className:"nav-item nav-link",children:[s.jsx("span",{className:"nav-ico",children:"🔌"})," Integrations"]}),s.jsx("div",{className:"sidebar-spacer"}),s.jsx("button",{type:"button",className:"sidebar-cta",title:"Create a new project",onClick:()=>E(!0),children:"+ New project"}),s.jsx(be,{to:"/global",className:"nav-item nav-link",children:"⚙ Global settings"})]}),s.jsxs("div",{className:"content",children:[s.jsxs("header",{className:"content-head",children:[s.jsx("h1",{id:"section-title",children:l==="repos"?"Repos":l==="prs"?"PRs":"Projects"}),s.jsxs("div",{className:"head-right",children:[s.jsxs("div",{className:"legend",children:[s.jsxs("span",{className:"legend-item",children:[s.jsx("i",{className:"dot working"}),"working"]}),s.jsxs("span",{className:"legend-item",children:[s.jsx("i",{className:"dot waiting"}),"waiting"]}),s.jsxs("span",{className:"legend-item",children:[s.jsx("i",{className:"dot off"}),"idle"]})]}),s.jsx(Pm,{dnd:m}),s.jsx("button",{type:"button",className:"btn mute-all","aria-pressed":h,title:h?"Unmute all alerts":"Mute all alerts",onClick:o,children:h?"🔇 muted":"🔔 alerts"})]})]}),l==="repos"&&s.jsxs("section",{className:"section active",children:[s.jsxs("div",{className:"section-toolbar",children:[s.jsx("input",{className:"section-search",type:"search",placeholder:"Filter repos…",autoComplete:"off",spellCheck:!1,value:j,onChange:R=>b(R.target.value)}),s.jsx("button",{type:"button",className:"btn primary",title:"Add a repository",onClick:()=>T(!0),children:"+ Add repo"})]}),s.jsx(Um,{search:j,reloadKey:k})]}),l==="prs"&&s.jsx("section",{className:"section active",children:s.jsx(Wm,{})}),s.jsx("section",{className:"section active",style:{display:l==="projects"?"":"none"},children:s.jsxs("main",{className:"panes",children:[!n&&Array.from({length:3}).map((R,A)=>s.jsxs("div",{className:"pane pane-skeleton","aria-hidden":"true",children:[s.jsxs("div",{className:"pane-top",children:[s.jsx("span",{className:"pane-name skel skel-line",style:{width:"40%"}}),s.jsx("span",{className:"skel skel-line",style:{width:"5rem"}})]}),s.jsx("div",{className:"pane-peek",children:s.jsx("span",{className:"skel skel-line",style:{width:"70%"}})}),s.jsxs("div",{className:"pane-foot",children:[s.jsx("span",{className:"skel skel-line",style:{width:"3rem"}}),s.jsx("span",{className:"skel skel-line",style:{width:"3rem"}}),s.jsx("span",{className:"skel skel-line",style:{width:"3rem"}})]})]},`sk-${A}`)),n&&U.length===0&&s.jsxs("p",{className:"empty",children:["No projects yet. Start one with ",s.jsx("code",{children:"corral init"})," then ",s.jsx("code",{children:"corral start"}),"."]}),U.map(R=>{const A=R.activity||"off",M=R.peek||(A==="off"?"container not running":"…"),O=i(R.id);return s.jsxs(be,{className:`pane pane-${A}`,to:`/p/${R.id}`,children:[s.jsxs("div",{className:"pane-top",children:[s.jsx("span",{className:"pane-name",children:R.name}),s.jsxs("span",{className:`pane-state state-${A}`,children:[s.jsx("i",{className:"beacon"}),Vm(A),s.jsx("button",{className:`power-btn ${R.container_up?"stop":"start"}`,type:"button",disabled:v[R.id],title:R.container_up?"Stop this project's container":"Start this project's container",onClick:W=>{W.preventDefault(),W.stopPropagation(),K(R)},children:v[R.id]?s.jsx("span",{className:"power-spin",children:"↻"}):R.container_up?"■":"▶"}),s.jsx("button",{className:"mute-btn",type:"button","aria-pressed":O,title:O?"Unmute alerts for this project":"Mute alerts for this project",onClick:W=>{W.preventDefault(),W.stopPropagation(),y(R.id)},children:O?"🔇":"🔔"}),A==="off"&&s.jsx("button",{className:"remove-btn",type:"button",title:"Remove this idle project from the dashboard",onClick:W=>{W.preventDefault(),W.stopPropagation(),$(R)},children:"✕"})]})]}),s.jsxs("div",{className:"pane-peek",children:[s.jsx("span",{className:"peek-caret",children:">"})," ",M]}),s.jsxs("div",{className:"pane-foot",children:[s.jsxs("span",{className:"svc",children:[s.jsx(uo,{up:R.container_up}),"box"]}),s.jsxs("span",{className:"svc",children:[s.jsx(uo,{up:R.mitm_up}),"proxy"]}),s.jsxs("span",{className:"svc",children:[s.jsx(uo,{up:R.tmux_up}),"session"]}),A==="working"&&s.jsxs("span",{className:"rate",children:[R.anthropic_hits," req/min · live"]}),A==="waiting"&&s.jsx("span",{className:"rate quiet",children:"idle at prompt"})]})]},R.id)})]})})]})]}),s.jsx("footer",{className:"console-footer",children:s.jsx("span",{className:w?"attention":"muted",children:f})}),c&&s.jsx(nn,{projectId:c.id,onDone:R=>{const{id:A,name:M}=c;a(null),R?q(A,M):(g(`"${M}" — keys not loaded; start canceled.`),S(!0))}}),N&&s.jsx(ll,{onClose:()=>E(!1)}),L&&s.jsx($m,{onClose:()=>T(!1),onAdded:()=>{_("repos"),x(R=>R+1)}})]})}function it(e,t){const[r,n]=C.useState(()=>{try{const h=localStorage.getItem(e);if(h!=null)return JSON.parse(h)}catch{}return t}),i=C.useCallback(h=>{n(y=>{const o=typeof h=="function"?h(y):h;try{localStorage.setItem(e,JSON.stringify(o))}catch{}return o})},[e]);return[r,i]}function Qs(e){const t=C.useRef(e);return t.current=e,C.useCallback(r=>{if(!r)return;const n=i=>{i.preventDefault();const h=t.current,y=h.axis==="x"?i.clientX:i.clientY,o=h.get();r.setPointerCapture(i.pointerId),document.body.style.userSelect="none",document.body.style.cursor=h.axis==="x"?"ew-resize":"ns-resize";const u=m=>{const f=t.current;let w=(f.axis==="x"?m.clientX:m.clientY)-y;f.edge==="start"&&(w=-w),f.onResize(Math.max(f.min,Math.min(f.max(),o+w)))},d=m=>{try{r.releasePointerCapture(m.pointerId)}catch{}document.body.style.userSelect="",document.body.style.cursor="",r.removeEventListener("pointermove",u),r.removeEventListener("pointerup",d)};r.addEventListener("pointermove",u),r.addEventListener("pointerup",d)};r.addEventListener("pointerdown",n)},[])}function Jm({x:e,y:t,canSplit:r,onAction:n,onClose:i}){const h=C.useRef(null);C.useEffect(()=>{const o=d=>{h.current&&!h.current.contains(d.target)&&i()},u=d=>d.key==="Escape"&&i();return document.addEventListener("mousedown",o),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",o),document.removeEventListener("keydown",u)}},[i]);const y={left:Math.min(e,window.innerWidth-190),top:Math.min(t,window.innerHeight-220)};return s.jsxs("div",{className:"term-menu",ref:h,style:y,onContextMenu:o=>o.preventDefault(),children:[r&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"term-menu-item",onClick:()=>n("split-h"),children:"Split right"}),s.jsx("button",{className:"term-menu-item",onClick:()=>n("split-v"),children:"Split down"}),s.jsx("div",{className:"term-menu-sep"})]}),s.jsxs("button",{className:"term-menu-item",onClick:()=>n("copy"),children:["Copy ",s.jsx("span",{className:"term-menu-key",children:"⌘C"})]}),s.jsxs("button",{className:"term-menu-item",onClick:()=>n("paste"),children:["Paste ",s.jsx("span",{className:"term-menu-key",children:"⌘V"})]}),s.jsx("button",{className:"term-menu-item",onClick:()=>n("clear"),children:"Clear"}),r&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"term-menu-sep"}),s.jsx("button",{className:"term-menu-item term-menu-danger",onClick:()=>n("kill-pane"),children:"Close pane"})]})]})}function Zs({projectId:e,wsPath:t,fullPath:r,kind:n}){const i=C.useRef(null),h=C.useRef(null),y=C.useRef(null),[o,u]=C.useState(null),d=r??`/p/${e}${t}`;C.useEffect(()=>{const g=new jd.Terminal({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:13,theme:{background:"#0B0E14",selectionBackground:"#2e5aa0",selectionForeground:"#ffffff"},scrollback:1e4,macOptionClickForcesSelection:!0});h.current=g,g.parser.registerOscHandler(52,E=>{var T;const L=E.slice(E.indexOf(";")+1);if(!L||L==="?")return!0;try{const P=new TextDecoder().decode(Uint8Array.from(atob(L),B=>B.charCodeAt(0)));(T=navigator.clipboard)==null||T.writeText(P).catch(()=>{})}catch{}return!0});const w=new Ed.FitAddon;g.loadAddon(w),i.current&&(g.open(i.current),i.current.clientWidth>0&&i.current.clientHeight>0&&w.fit());const S=new WebSocket(hs(d));y.current=S,S.binaryType="arraybuffer";const v=new TextDecoder,p=()=>{S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:g.cols,rows:g.rows}))};S.onopen=()=>{p(),g.focus()},S.onmessage=E=>{g.write(typeof E.data=="string"?E.data:v.decode(new Uint8Array(E.data)))},S.onclose=()=>{g.write(`\r \x1B[90m[disconnected — reopen to reconnect]\x1B[0m\r `)};const c=E=>{S.readyState===WebSocket.OPEN&&S.send(new TextEncoder().encode(E))};g.onData(E=>c(E)),g.attachCustomKeyEventHandler(E=>E.type!=="keydown"||E.key!=="Enter"?!0:(E.preventDefault(),c(E.shiftKey||E.metaKey||E.ctrlKey||E.altKey?"\x1B\r":"\r"),!1));const a=()=>{const E=i.current;if(!E||E.clientWidth===0||E.clientHeight===0)return;const L=w.proposeDimensions();L&&L.cols===g.cols&&L.rows===g.rows||(w.fit(),p())};let l;const _=()=>{window.clearTimeout(l),l=window.setTimeout(a,100)};window.addEventListener("resize",_);const j=new ResizeObserver(()=>_());i.current&&j.observe(i.current);let b=0,k=0;const x=[],N=()=>{const E=i.current;if(E&&E.clientWidth>0&&E.clientHeight>0){a(),[120,350,700].forEach(T=>x.push(window.setTimeout(a,T)));return}k++<90&&(b=requestAnimationFrame(N))};return b=requestAnimationFrame(N),document.fonts&&document.fonts.ready&&document.fonts.ready.then(()=>a()).catch(()=>{}),()=>{window.removeEventListener("resize",_),j.disconnect(),window.clearTimeout(l),x.forEach(E=>window.clearTimeout(E)),cancelAnimationFrame(b);try{S.close()}catch{}g.dispose()}},[d]);const m=async g=>{var S;u(null);const w=h.current;switch(g){case"copy":{const v=w==null?void 0:w.getSelection();v&&await navigator.clipboard.writeText(v).catch(()=>{});return}case"paste":{const v=await navigator.clipboard.readText().catch(()=>"");v&&((S=y.current)==null?void 0:S.readyState)===WebSocket.OPEN&&y.current.send(new TextEncoder().encode(v));return}case"clear":n==="claude"||n==="host"?await oe(`/p/${e}/terminal/action`,{kind:n,action:"clear"}).catch(()=>{}):w==null||w.clear();return;case"split-h":case"split-v":case"kill-pane":n==="host"&&await oe(`/p/${e}/terminal/action`,{kind:n,action:g}).catch(()=>{});return}},f=n==="host"&&!!e;return s.jsx("div",{className:"term-fill",ref:i,style:{width:"100%",height:"100%"},onContextMenu:g=>{g.preventDefault(),u({x:g.clientX,y:g.clientY})},children:o&&s.jsx(Jm,{x:o.x,y:o.y,canSplit:f,onClose:()=>u(null),onAction:m})})}function Dc(e){return e.replace(/&/g,"&").replace(//g,">")}function jr(e){let t="";const r=e.split(/```/);for(let n=0;n${Dc(i)}`}else{let i=Dc(r[n]);i=i.replace(/`([^`]+)`/g,"$1"),i=i.replace(/\*\*([^*]+)\*\*/g,"$1"),i=i.split(/\n{2,}/).map(h=>`

${h.replace(/\n/g,"
")}

`).join(""),t+=i}return t}const Ac="=== LIVE VIEW READY ===",Tc="=== END LIVE VIEW READY ===";function Ym(e){if(!e)return null;const t=e.indexOf(Ac);if(t===-1)return null;const r=t+Ac.length,n=e.indexOf(Tc,r);if(n===-1)return null;const i=e.slice(r,n),h={};for(const o of i.split(` `)){const u=o.indexOf(":");if(u===-1)continue;const d=o.slice(0,u).trim().toLowerCase(),m=o.slice(u+1).trim();d&&(h[d]=m)}const y=(e.slice(0,t)+e.slice(n+Tc.length)).trim();return{status:h.status||"",urlPath:h.url_path||h.path||void 0,port:h.port||void 0,login:h.login||void 0,note:h.note||void 0,rest:y}}const Xm=/```[ \t]*corral-question[ \t]*\n([\s\S]*?)```/i;function Qm(e){if(!e)return null;const t=e.match(Xm);if(!t)return null;const r=t[1];let n="";const i=[];for(const y of r.split(` -`)){const o=y.trim();if(!o)continue;const u=o.match(/^question\s*:\s*(.+)$/i);if(u){n=u[1].trim();continue}const d=o.match(/^[-*]\s+(.+)$/);d&&i.push(d[1].trim())}if(!n||i.length<2)return null;const h=(e.slice(0,t.index)+e.slice((t.index??0)+t[0].length)).trim();return{question:n,options:i,rest:h}}function Zm({data:e}){const t=e.status.toLowerCase()==="verified";return s.jsxs("div",{className:`lvr-card${t?" verified":""}`,children:[s.jsxs("div",{className:"lvr-head",children:[s.jsx("span",{className:"lvr-badge",children:t?"✓ Live View ready":`Live View: ${e.status||"unknown"}`}),e.port&&s.jsxs("span",{className:"lvr-port",children:["port ",e.port]})]}),e.note&&s.jsx("div",{className:"lvr-note",children:e.note}),s.jsxs("div",{className:"lvr-fields",children:[e.urlPath&&s.jsxs("div",{className:"lvr-field",children:[s.jsx("span",{className:"lvr-key",children:"page"}),s.jsx("code",{className:"lvr-val",children:e.urlPath})]}),e.login&&s.jsxs("div",{className:"lvr-field",children:[s.jsx("span",{className:"lvr-key",children:"sign in"}),s.jsx("code",{className:"lvr-val",children:e.login})]})]})]})}function eg(e){if(!e)return"";let t;try{t=JSON.parse(e)}catch{return""}for(const n of["file_path","path","pattern","command","query","url"])if(t[n]!=null)return String(t[n]);const r=e.replace(/\s+/g," ");return r.length>80?r.slice(0,79)+"…":r}function tg(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function an({wsPath:e,getCtx:t,persistKey:r,canAct:n=!1,onConvMeta:i,onBusyChange:h}){const y=r?`corral.chat.msgs.${r}`:"",o=r?`corral.chat.sid.${r}`:"",[u,d]=C.useState(()=>{if(!y)return[];try{const D=localStorage.getItem(y);return D?JSON.parse(D):[]}catch{return[]}}),[m,f]=C.useState(""),[g,w]=C.useState(!1),[S,v]=C.useState(!1),[p,c]=C.useState(null),a=C.useRef(null);a.current=p;const l=C.useRef(()=>{}),[_,j]=C.useState(0),b=C.useRef(null),k=C.useRef(null),x=C.useRef(i);x.current=i;const N=C.useRef(h);N.current=h,C.useEffect(()=>{var D;(D=N.current)==null||D.call(N,S)},[S]);const E=C.useRef(r&&localStorage.getItem(o)||""),L=C.useRef(""),T=C.useRef(null),O=C.useRef(null),B=C.useCallback(()=>{requestAnimationFrame(()=>{k.current&&(k.current.scrollTop=k.current.scrollHeight)})},[]);C.useEffect(()=>{if(y)try{const D=u.filter(M=>M.role!=="meta");localStorage.setItem(y,JSON.stringify(D))}catch{}},[u,y]),C.useEffect(()=>{const D=E.current,M=D?`${e}${e.includes("?")?"&":"?"}resume=${encodeURIComponent(D)}`:e,P=new WebSocket(hs(M));b.current=P;let U=!1;return P.onopen=()=>w(!0),P.onclose=()=>{w(!1),v(!1),U||d(Y=>[...Y,{role:"meta",text:"disconnected — reopen the panel to reconnect",error:!0}])},P.onmessage=Y=>{let H;try{H=JSON.parse(Y.data)}catch{return}switch(H.type){case"session":{const J=H.sessionId||"";if(J&&(E.current=J,o))try{localStorage.setItem(o,J)}catch{}break}case"conv_meta":{const J=H.convUuid||"",I=H.convId||0;J&&x.current&&x.current({convId:I,convUuid:J});break}case"text":{L.current+=H.text||"",d(J=>{const I=J.slice();return T.current==null&&(I.push({role:"assistant",html:""}),T.current=I.length-1),I[T.current]={role:"assistant",html:jr(L.current),text:L.current},I}),B();break}case"tool_use":{T.current=null,L.current="",d(J=>{const I=[...J,{role:"assistant",tool:{name:H.tool||"tool",input:H.input||""}}];return O.current=I.length-1,I}),B();break}case"tool_result":{d(J=>{if(O.current==null)return J;const I=J.slice(),A=I[O.current];return A!=null&&A.tool&&(I[O.current]={...A,tool:{...A.tool,result:H.result||""}}),I}),B();break}case"result":{H.isError?d(J=>[...J,{role:"meta",text:"Claude reported an error for this turn.",error:!0}]):H.model&&d(J=>[...J,{role:"meta",text:H.model}]);break}case"error":d(J=>[...J,{role:"meta",text:H.text||"error",error:!0}]);break;case"canceled":d(J=>[...J,{role:"meta",text:"stopped"}]);break;case"turn_end":if(v(!1),T.current=null,L.current="",O.current=null,a.current!=null){const J=a.current;c(null),a.current=null,setTimeout(()=>l.current(J),0)}break}},()=>{U=!0;try{P.close()}catch{}}},[e,B,_]);const F=C.useCallback(D=>{!b.current||b.current.readyState!==WebSocket.OPEN||(d(M=>[...M,{role:"user",html:jr(D)}]),b.current.send(JSON.stringify({prompt:D,ctx:(t==null?void 0:t())||""})),v(!0),B())},[t,B]);l.current=F;const z=()=>{const D=m.trim();if(!(!g||!D)){if(S){c(D),f("");return}F(D),f("")}},K=()=>{var D;g&&S&&((D=b.current)==null||D.send(JSON.stringify({action:"cancel"})))},$=D=>{!g||S||F(D)},R=()=>{if(E.current="",o)try{localStorage.removeItem(o)}catch{}d([]),c(null),a.current=null,L.current="",T.current=null,O.current=null,j(D=>D+1)};return s.jsxs("div",{className:`chat-root${S?" busy":""}`,children:[s.jsxs("div",{className:"chat-topbar",children:[s.jsxs("p",{className:"muted cfg-note chat-warn",children:["⚠ This runs the ",s.jsx("strong",{children:"host"})," Claude — it is ",s.jsx("strong",{children:"not sandboxed"}),"."," ",n?s.jsxs(s.Fragment,{children:["It can ",s.jsx("strong",{children:"act"})," — Read/Grep/Glob plus ",s.jsx("strong",{children:"Bash"})," (runs commands, ",s.jsx("code",{children:"corral api"}),") on your machine."]}):s.jsx(s.Fragment,{children:"Read-only: Read, Grep, Glob — it can look, not act."})]}),r&&u.length>0&&s.jsx("button",{type:"button",className:"chat-newbtn",onClick:R,title:"Start a fresh conversation",children:"New chat"})]}),s.jsxs("div",{className:"chat-log",id:"log",ref:k,children:[u.map((D,M)=>{if(D.role==="meta")return s.jsx("div",{className:`meta${D.error?" error":""}`,children:D.text},M);if(D.tool)return s.jsx("div",{className:"tool",children:s.jsxs("details",{children:[s.jsxs("summary",{children:[s.jsx("span",{className:"tool-name",children:D.tool.name})," ",s.jsx("span",{className:"tool-arg",children:eg(D.tool.input)})]}),s.jsxs("div",{className:"tool-body",children:[D.tool.input&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"label",children:"input"}),s.jsx("pre",{children:tg(D.tool.input)})]}),D.tool.result!=null&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"label",children:"result"}),s.jsx("pre",{children:D.tool.result})]})]})]})},M);const P=D.role==="assistant"?Ym(D.text||""):null;if(P)return s.jsxs("div",{className:`msg ${D.role}`,children:[s.jsx("div",{className:"avatar",children:"✳"}),s.jsxs("div",{className:"bubble",children:[P.rest&&s.jsx("div",{dangerouslySetInnerHTML:{__html:jr(P.rest)}}),s.jsx(Zm,{data:P})]})]},M);const U=M===u.length-1,Y=D.role==="assistant"&&U&&!S?Qm(D.text||""):null;return Y?s.jsxs("div",{className:`msg ${D.role}`,children:[s.jsx("div",{className:"avatar",children:"✳"}),s.jsxs("div",{className:"bubble",children:[Y.rest&&s.jsx("div",{dangerouslySetInnerHTML:{__html:jr(Y.rest)}}),s.jsxs("div",{className:"chat-question",children:[s.jsx("div",{className:"chat-question-q",children:Y.question}),s.jsx("div",{className:"chat-question-opts",children:Y.options.map((H,J)=>s.jsx("button",{type:"button",className:"chat-question-opt",onClick:()=>$(H),children:H},J))})]})]})]},M):s.jsxs("div",{className:`msg ${D.role}`,children:[s.jsx("div",{className:"avatar",children:D.role==="assistant"?"✳":"Y"}),s.jsx("div",{className:"bubble",dangerouslySetInnerHTML:{__html:D.html||""}})]},M)}),S&&T.current==null&&s.jsxs("div",{className:"msg assistant",children:[s.jsx("div",{className:"avatar",children:"✳"}),s.jsx("div",{className:"bubble",children:s.jsx("span",{className:"typing",children:"Claude is thinking…"})})]}),p!=null&&s.jsxs("div",{className:"msg user chat-queued",title:"Sends when the current turn finishes",children:[s.jsx("div",{className:"avatar",children:"Y"}),s.jsxs("div",{className:"bubble",children:[s.jsx("span",{className:"chat-queued-tag",children:"queued"}),p,s.jsx("button",{type:"button",className:"chat-queued-x",title:"Cancel this queued message",onClick:()=>c(null),children:"×"})]})]})]}),s.jsxs("div",{className:"chat-composer",children:[s.jsx("textarea",{id:"input",placeholder:"Ask Claude about this project…",value:m,onChange:D=>f(D.target.value),onKeyDown:D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),z())},rows:1,style:{maxHeight:160}}),s.jsx("button",{id:"send",disabled:!g||m.trim()==="",onClick:z,title:S?"Queue this message — sends when the current turn finishes":"Send",children:S?"Queue":"Send"}),S&&s.jsx("button",{id:"stop",onClick:K,children:"Stop"})]})]})}function Pc(e,t){return`corral.agentctx.staleDismissed.${e}.${t}`}function sg(e){try{return localStorage.getItem(e)||""}catch{return""}}function rg(e,t){try{localStorage.setItem(e,t)}catch{}}function ng(e){return e>=60?`${Math.round(e/30)} months`:e>=14?`${Math.round(e/7)} weeks`:`${e} days`}function cl({repoId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(!1),[h,y]=C.useState(null),o=C.useCallback(()=>{e&&ee(`/api/repos/${encodeURIComponent(e)}/agent-context`).then(m=>{r(m),i(sg(Pc(e,m.updatedAt))==="1")}).catch(()=>r(null))},[e]);if(C.useEffect(()=>o(),[o]),!e||!t||!t.stale||n)return null;const u=()=>{rg(Pc(e,t.updatedAt),"1"),i(!0)},d=async()=>{try{await oe(`/api/repos/${encodeURIComponent(e)}/generate-agents-md`,{}),y("Regenerating AGENTS.md — watch the Work tab (⌘K); it updates here when done.")}catch(m){y(`Couldn't start regeneration: ${m.message}`)}};return h?s.jsxs("div",{className:"update-banner",role:"status",children:[s.jsx("span",{className:"update-banner-text",children:h}),s.jsx("span",{className:"update-banner-actions",children:s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:()=>y(null),children:"✕"})})]}):s.jsxs("div",{className:"update-banner update-banner-warn",role:"status",children:[s.jsxs("span",{className:"update-banner-text",children:["This repo's ",s.jsx("strong",{children:"AGENTS.md"})," context is ",s.jsx("strong",{children:ng(t.ageDays)})," old"," ",s.jsxs("span",{className:"muted",children:["(stale after ",t.thresholdDays," days)"]})," — the codebase has likely drifted from it."]}),s.jsxs("span",{className:"update-banner-actions",children:[s.jsx("button",{className:"update-banner-btn",onClick:d,title:"Explore the repo and redraft it with AI",children:"Regenerate"}),s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:u,children:"✕"})]})]})}const ig={js:["JS","#f0db4f"],jsx:["JS","#f0db4f"],mjs:["JS","#f0db4f"],cjs:["JS","#f0db4f"],ts:["TS","#3178c6"],tsx:["TS","#3178c6"],go:["GO","#00add8"],py:["PY","#3572a5"],rb:["RB","#cc342d"],rs:["RS","#dea584"],java:["JV","#b07219"],c:["C","#555555"],h:["H","#555555"],cpp:["C+","#f34b7d"],json:["{}","#cbcb41"],yml:["YM","#cb171e"],yaml:["YM","#cb171e"],toml:["TO","#9c4221"],md:["MD","#519aba"],markdown:["MD","#519aba"],txt:["TX","#9aa4b0"],html:["<>","#e34c26"],htm:["<>","#e34c26"],css:["#","#563d7c"],scss:["#","#c6538c"],sh:["SH","#89e051"],bash:["SH","#89e051"],zsh:["SH","#89e051"],dockerfile:["DK","#384d54"],sql:["SQ","#e38c00"],xml:["0?t.slice(r+1):""}function ag(e){return ig[og(e)]||["·","#8a94a6"]}let jn=null;function Pi(){return window.CorralEditor?Promise.resolve(window.CorralEditor):jn||(jn=new Promise((e,t)=>{const r=document.createElement("script");r.src="/static/codemirror.bundle.js",r.onload=()=>{window.CorralEditor?e(window.CorralEditor):t(new Error("codemirror bundle loaded but CorralEditor is missing"))},r.onerror=()=>t(new Error("failed to load codemirror bundle")),document.head.appendChild(r)}),jn)}function gs(e,t){return`/p/${e}${t}`}function Td({name:e}){const[t,r]=ag(e);return s.jsx("span",{className:"ficon",style:{color:r},children:t})}function Pd({projectId:e,relPath:t,name:r,depth:n,openPath:i,onOpenFile:h,onCtx:y,refreshToken:o}){const u=r===null,[d,m]=C.useState(u),[f,g]=C.useState(null),[w,S]=C.useState(null),v=C.useCallback(()=>{ee(gs(e,`/files/tree?path=${encodeURIComponent(t)}`)).then(c=>{g(c.entries||[]),S(null)}).catch(c=>S(c.message))},[e,t]);if(C.useEffect(()=>{d&&v()},[d,v,o]),!u&&!d)return s.jsx("li",{className:"ftree-dir collapsed","data-name":r,children:s.jsxs("span",{className:"ftree-label",onClick:c=>{c.stopPropagation(),m(!0)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),y({x:c.clientX,y:c.clientY,rel:t,isDir:!0})},children:[s.jsx("span",{className:"ficon ficon-dir",children:"▸"}),s.jsx("span",{className:"ftree-name",children:r})]})});const p=s.jsxs(s.Fragment,{children:[w&&s.jsxs("p",{className:"attention",children:["tree error: ",w]}),s.jsx("ul",{children:(f||[]).map(c=>{const a=t?`${t}/${c.name}`:c.name;return c.dir?s.jsx(Pd,{projectId:e,relPath:a,name:c.name,depth:n+1,openPath:i,onOpenFile:h,onCtx:y,refreshToken:o},c.name):s.jsx("li",{className:`ftree-file${i===a?" active":""}`,"data-name":c.name,"data-path":a,children:s.jsxs("span",{className:"ftree-label",onClick:l=>{l.stopPropagation(),h(a)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),y({x:l.clientX,y:l.clientY,rel:a,isDir:!1})},children:[s.jsx(Td,{name:c.name}),s.jsx("span",{className:"ftree-name",children:c.name})]})},c.name)})})]});return u?p:s.jsxs("li",{className:"ftree-dir","data-name":r,"data-dir":"1",children:[s.jsxs("span",{className:"ftree-label",onClick:c=>{c.stopPropagation(),m(!1)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),y({x:c.clientX,y:c.clientY,rel:t,isDir:!0})},children:[s.jsx("span",{className:"ficon ficon-dir",children:"▸"}),s.jsx("span",{className:"ftree-name",children:r})]}),p]})}function lg({projectId:e}){const[t,r]=C.useState(0),n=C.useCallback(()=>r(H=>H+1),[]),i=C.useRef(null),h=C.useRef(null),[y,o]=C.useState(null),u=C.useRef(null),[d,m]=it(`corral.filesOpen.${e}`,null),f=C.useRef(!1),[g,w]=C.useState(!1),S=C.useRef(!1),[v,p]=C.useState(null),[c,a]=C.useState("name"),[l,_]=C.useState(""),[j,b]=C.useState(null),[k,x]=C.useState(null),[N,E]=C.useState(!1),[L,T]=C.useState(null),O=H=>{S.current=H,w(H)},B=C.useCallback(async(H,J)=>{var I,A;if(!(S.current&&!window.confirm(`Discard unsaved changes to ${u.current}?`)))try{const q=await ee(gs(e,`/files/read?path=${encodeURIComponent(H)}`));if(u.current=H,o(H),m(H),q.too_large){(I=h.current)==null||I.destroy(),h.current=null,p(q.size||0),O(!1);return}p(null);const W=await Pi();(A=h.current)==null||A.destroy(),i.current&&(i.current.innerHTML=""),h.current=W.createEditor({parent:i.current,doc:q.content||"",filename:q.filename||H,onChange:()=>{S.current||O(!0)}}),O(!1),J&&h.current.view&&W.scrollToLineEffect}catch(q){i.current&&(i.current.innerHTML=`

read error: ${q.message}

`)}},[e,m]);C.useEffect(()=>{f.current||(f.current=!0,d&&B(d))},[]);const F=C.useCallback(async()=>{if(!(!h.current||u.current==null))try{const H=await fetch(gs(e,`/files/write?path=${encodeURIComponent(u.current)}`),{method:"POST",credentials:"same-origin",body:h.current.getDoc()});if(!H.ok)throw new Error(await H.text()||`HTTP ${H.status}`);O(!1)}catch(H){alert(`save failed: ${H.message}`)}},[e]),z=H=>je(gs(e,H)),K=H=>{const J=H.lastIndexOf("/");return J<0?"":H.slice(0,J)},$=(H,J)=>H?`${H}/${J}`:J;async function R(H,J,I){try{const A=await H;if(!A.ok)throw new Error(await A.text()||`HTTP ${A.status}`);n(),I==null||I()}catch(A){alert(`${J} failed: ${A.message}`)}}const D=H=>{const J=window.prompt("New file name:");J&&R(z(`/files/new?path=${encodeURIComponent($(H,J))}`),"create file",()=>B($(H,J)))},M=H=>{const J=window.prompt("New folder name:");J&&R(z(`/files/mkdir?path=${encodeURIComponent($(H,J))}`),"create folder")},P=H=>{const J=H.split("/").pop(),I=window.prompt("Rename to:",J);if(!I||I===J)return;const A=$(K(H),I);R(z(`/files/rename?from=${encodeURIComponent(H)}&to=${encodeURIComponent(A)}`),"rename")},U=(H,J)=>{window.confirm(`Delete ${J?"folder":"file"} '${H}'?${J?" (recursive)":""}`)&&R(fetch(gs(e,`/files?path=${encodeURIComponent(H)}`),{method:"DELETE",credentials:"same-origin"}),"delete")};C.useEffect(()=>{const H=()=>T(null),J=I=>I.key==="Escape"&&T(null);return document.addEventListener("click",H),document.addEventListener("keydown",J),()=>{document.removeEventListener("click",H),document.removeEventListener("keydown",J)}},[]),C.useEffect(()=>{const H=l.trim();if(!H){b(null),x(null),E(!1);return}E(!0);const J=window.setTimeout(async()=>{try{c==="grep"?(x(await ee(gs(e,`/files/grep?q=${encodeURIComponent(H)}`))),b(null)):(b(await ee(gs(e,`/files/find?q=${encodeURIComponent(H)}`))),x(null))}catch{}},220);return()=>window.clearTimeout(J)},[l,c,e]),C.useEffect(()=>{const H=window.setInterval(()=>{l.trim()||n()},2500);return()=>window.clearInterval(H)},[l,n]),C.useEffect(()=>{const H=i.current;if(!H)return;const J=I=>{(I.ctrlKey||I.metaKey)&&(I.key==="s"||I.key==="S")&&(I.preventDefault(),S.current&&F())};return H.addEventListener("keydown",J),()=>H.removeEventListener("keydown",J)},[F]);const Y=l.trim()!=="";return s.jsxs("div",{className:"files-root",children:[s.jsxs("div",{className:"files-side",children:[s.jsxs("div",{className:"files-search",children:[s.jsx("input",{id:"files-q",type:"text",placeholder:c==="grep"?"search file contents…":"search files…",autoComplete:"off",spellCheck:!1,value:l,onChange:H=>_(H.target.value)}),s.jsxs("div",{className:"files-search-mode",children:[s.jsx("button",{className:c==="name"?"active":"",type:"button",title:"Find files by name",onClick:()=>a("name"),children:"name"}),s.jsx("button",{className:c==="grep"?"active":"",type:"button",title:"Search file contents (grep)",onClick:()=>a("grep"),children:"grep"}),s.jsx("button",{type:"button",title:"Refresh the file tree",onClick:n,children:"⟳"})]})]}),!Y&&s.jsx("div",{className:"files-tree",onContextMenu:H=>{H.target.closest(".ftree-label")||(H.preventDefault(),T({x:H.clientX,y:H.clientY,rel:"",isDir:!0}))},children:s.jsx(Pd,{projectId:e,relPath:"",name:null,depth:0,openPath:y,onOpenFile:B,onCtx:T,refreshToken:t})}),Y&&s.jsxs("div",{className:"files-results",children:[N&&!j&&!k&&s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"searching…"}),c==="name"&&j&&((j.matches||[]).length===0?s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"no matching files"}):s.jsxs(s.Fragment,{children:[(j.matches||[]).map(H=>{const J=H.split("/").pop();return s.jsxs("div",{className:"sresult",onClick:()=>B(H),children:[s.jsx(Td,{name:J}),s.jsx("span",{className:"sresult-path",children:H})]},H)}),j.truncated&&s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"…results truncated — narrow your search"})]})),c==="grep"&&k&&((k.hits||[]).length===0?s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"no matches"}):s.jsxs(s.Fragment,{children:[(k.hits||[]).map((H,J)=>s.jsxs("div",{className:"sresult sresult-grep",onClick:()=>B(H.path,H.line),children:[s.jsxs("div",{className:"sresult-loc",children:[H.path,s.jsxs("span",{className:"sresult-ln",children:[":",H.line]})]}),s.jsx("div",{className:"sresult-text",children:H.text})]},`${H.path}:${H.line}:${J}`)),k.truncated&&s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"…results truncated — narrow your search"})]}))]})]}),s.jsxs("div",{className:"files-editor",children:[s.jsxs("div",{className:"files-editor-bar",children:[s.jsx("span",{className:y?"":"muted",children:(y||"select a file")+(g?" •":"")}),s.jsx("button",{type:"button",disabled:!g||y==null,onClick:F,children:"Save"})]}),v!=null?s.jsxs("p",{className:"muted",style:{padding:"1rem"},children:["file is too large to edit here (",v," bytes)"]}):s.jsx("div",{className:"files-cm",ref:i})]}),L&&s.jsxs("div",{className:"ctx-menu",style:{left:L.x,top:L.y},onClick:H=>H.stopPropagation(),children:[L.isDir&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),D(L.rel)},children:"New file"}),s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),M(L.rel)},children:"New folder"})]}),L.rel!==""&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),P(L.rel)},children:"Rename"}),s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),U(L.rel,L.isDir)},children:"Delete"})]})]})]})}function Nn(e,t){return`/p/${e}${t}`}function cg(e){const t=e.trim();return t==="??"?"new":t.includes("M")?"modified":t.includes("A")?"added":t.includes("D")?"deleted":t.includes("R")?"renamed":t||"changed"}function ug({projectId:e}){var x;const[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState([]),[o,u]=C.useState(""),[d,m]=C.useState(""),[f,g]=C.useState(null),[w,S]=C.useState(!1),[v,p]=C.useState(null),c=C.useRef(null),a=C.useRef(null),l=C.useRef(!1),_=o!==""&&d!=="",j=C.useCallback(()=>{let N=n?`&repo=${encodeURIComponent(n)}`:"";return _&&(N+=`&base=${encodeURIComponent(o)}&target=${encodeURIComponent(d)}`),N},[n,o,d,_]);C.useEffect(()=>{ee(Nn(e,"/git/repos")).then(N=>{r(N);const E=N.repos||[];E.length<=1?E.length===1&&E[0].path&&!N.rootIsRepo&&i(E[0].path):i(N.rootIsRepo?"":E[0].path)}).catch(()=>{})},[e]),C.useEffect(()=>{const N=n?`?repo=${encodeURIComponent(n)}`:"";ee(Nn(e,`/git/refs${N}`)).then(E=>{if(!E.repo){y([]);return}const L=E.branches||[];if(y(L.concat(E.tags||[])),!l.current&&!_&&L.length>0){l.current=!0;const T=E.current||"",O=["main","master","trunk"].filter(B=>L.includes(B))[0];T&&O&&T!==O&&(u(O),m(T))}}).catch(()=>{})},[e,n]),C.useEffect(()=>{g(null),S(!1),ee(Nn(e,`/git/status?_=1${j()}`)).then(N=>{if(!N.repo){S(!0);return}g(N.changes||[])}).catch(()=>g([]))},[e,j]);const b=C.useCallback(async N=>{var E,L;p(N);try{const T=await ee(Nn(e,`/git/file?path=${encodeURIComponent(N)}${j()}`));if((T.original||"")===(T.modified||"")){(E=a.current)==null||E.destroy(),a.current=null,c.current&&(c.current.innerHTML='no differences in this file');return}const O=await Pi();(L=a.current)==null||L.destroy(),c.current&&(c.current.innerHTML=""),a.current=O.createDiff({parent:c.current,original:T.original||"",modified:T.modified||"",filename:T.filename||N})}catch(T){c.current&&(c.current.innerHTML=`diff error: ${T.message}`)}},[e,j]);C.useEffect(()=>{f&&f.length>0&&b(f[0].path)},[f]);const k=(((x=t==null?void 0:t.repos)==null?void 0:x.length)||0)>1;return s.jsxs("div",{className:"diff-root",children:[s.jsxs("div",{className:"diff-side",children:[k&&s.jsx("div",{className:"diff-repo",children:s.jsx("select",{className:"diff-ref",title:"Repository",value:n,onChange:N=>{i(N.target.value),u(""),m("")},children:((t==null?void 0:t.repos)||[]).map(N=>s.jsx("option",{value:N.path,children:N.name},N.path))})}),s.jsxs("div",{className:"diff-refs",children:[s.jsxs("select",{className:"diff-ref",title:"Base ref",value:o,onChange:N=>u(N.target.value),children:[s.jsx("option",{value:"",children:"— working tree —"}),h.map(N=>s.jsx("option",{value:N,children:N},N))]}),s.jsx("span",{className:"diff-refs-arrow",children:"→"}),s.jsxs("select",{className:"diff-ref",title:"Target ref",value:d,onChange:N=>m(N.target.value),children:[s.jsx("option",{value:"",children:"— working tree —"}),h.map(N=>s.jsx("option",{value:N,children:N},N))]}),_&&s.jsx("button",{type:"button",title:"Back to working-tree changes",onClick:()=>{u(""),m("")},children:"✕"})]}),s.jsxs("div",{className:"diff-list",children:[w&&s.jsx("p",{className:"muted",children:"not a git repository"}),!w&&f===null&&s.jsx("p",{className:"muted",children:"loading…"}),!w&&f&&f.length===0&&s.jsx("p",{className:"muted",children:_?`no differences between ${o} and ${d}`:"working tree clean — no changes"}),(f||[]).map(N=>s.jsxs("div",{className:`diff-file${v===N.path?" active":""}`,onClick:()=>b(N.path),children:[s.jsx("span",{className:"d-status",children:cg(N.status)}),s.jsx("span",{className:"d-path",children:N.path}),(N.added||N.removed)&&s.jsxs("span",{className:"d-stat",children:[s.jsxs("span",{className:"d-add",children:["+",N.added]})," ",s.jsxs("span",{className:"d-del",children:["-",N.removed]})]})]},N.path))]})]}),s.jsx("div",{className:"diff-view",children:s.jsx("div",{className:"diff-body",ref:c,children:s.jsx("span",{className:"muted",children:"select a changed file"})})})]})}function Oc(e){if(e==null||e<=0)return"—";const t=["B","KB","MB","GB","TB"];let r=e,n=0;for(;r>=1024&&n{}),[w,S]=C.useState(""),[v,p]=C.useState("minimal"),[c,a]=C.useState(""),[l,_]=C.useState(""),[j,b]=C.useState([]),[k,x]=C.useState({}),[N,E]=C.useState({host:"",kind:"header",name:"",value:""}),[L,T]=C.useState(!1),[O,B]=C.useState(!1),[F,z]=C.useState(!1),[K,$]=C.useState(""),[R,D]=C.useState(!1),[M,P]=C.useState(""),[U,Y]=C.useState(""),[H,J]=C.useState("copy"),[I,A]=C.useState([]),[q,W]=C.useState(""),[X,Q]=C.useState([]),[re,ie]=C.useState({}),[he,Ce]=C.useState(""),[ae,dt]=C.useState(null),wt=V=>V.split(` -`).map(se=>se.trim()).filter(Boolean),nt=C.useCallback(V=>{ee(Dt(e,"/config")).then(se=>{var Ds,ml;n(se),S((se.allowed_hosts||[]).join(` +`)){const o=y.trim();if(!o)continue;const u=o.match(/^question\s*:\s*(.+)$/i);if(u){n=u[1].trim();continue}const d=o.match(/^[-*]\s+(.+)$/);d&&i.push(d[1].trim())}if(!n||i.length<2)return null;const h=(e.slice(0,t.index)+e.slice((t.index??0)+t[0].length)).trim();return{question:n,options:i,rest:h}}function Zm({data:e}){const t=e.status.toLowerCase()==="verified";return s.jsxs("div",{className:`lvr-card${t?" verified":""}`,children:[s.jsxs("div",{className:"lvr-head",children:[s.jsx("span",{className:"lvr-badge",children:t?"✓ Live View ready":`Live View: ${e.status||"unknown"}`}),e.port&&s.jsxs("span",{className:"lvr-port",children:["port ",e.port]})]}),e.note&&s.jsx("div",{className:"lvr-note",children:e.note}),s.jsxs("div",{className:"lvr-fields",children:[e.urlPath&&s.jsxs("div",{className:"lvr-field",children:[s.jsx("span",{className:"lvr-key",children:"page"}),s.jsx("code",{className:"lvr-val",children:e.urlPath})]}),e.login&&s.jsxs("div",{className:"lvr-field",children:[s.jsx("span",{className:"lvr-key",children:"sign in"}),s.jsx("code",{className:"lvr-val",children:e.login})]})]})]})}function eg(e){if(!e)return"";let t;try{t=JSON.parse(e)}catch{return""}for(const n of["file_path","path","pattern","command","query","url"])if(t[n]!=null)return String(t[n]);const r=e.replace(/\s+/g," ");return r.length>80?r.slice(0,79)+"…":r}function tg(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function an({wsPath:e,getCtx:t,persistKey:r,canAct:n=!1,onConvMeta:i,onBusyChange:h}){const y=r?`corral.chat.msgs.${r}`:"",o=r?`corral.chat.sid.${r}`:"",[u,d]=C.useState(()=>{if(!y)return[];try{const F=localStorage.getItem(y);return F?JSON.parse(F):[]}catch{return[]}}),[m,f]=C.useState(""),[g,w]=C.useState(!1),[S,v]=C.useState(!1),[p,c]=C.useState(null),a=C.useRef(null);a.current=p;const l=C.useRef(()=>{}),[_,j]=C.useState(0),b=C.useRef(null),k=C.useRef(null),x=C.useRef(i);x.current=i;const N=C.useRef(h);N.current=h,C.useEffect(()=>{var F;(F=N.current)==null||F.call(N,S)},[S]);const E=C.useRef(r&&localStorage.getItem(o)||""),L=C.useRef(""),T=C.useRef(null),P=C.useRef(null),B=C.useRef(!0),U=F=>F.scrollHeight-F.scrollTop-F.clientHeight<60,K=C.useRef(!1),q=C.useCallback(()=>{if(K.current)return;const F=k.current;F&&(B.current=U(F))},[]),$=C.useCallback(()=>{!k.current||!B.current||requestAnimationFrame(()=>{k.current&&(K.current=!0,k.current.scrollTop=k.current.scrollHeight,requestAnimationFrame(()=>{K.current=!1}))})},[]);C.useEffect(()=>{if(y)try{const F=u.filter(z=>z.role!=="meta");localStorage.setItem(y,JSON.stringify(F))}catch{}},[u,y]),C.useEffect(()=>{const F=E.current,z=F?`${e}${e.includes("?")?"&":"?"}resume=${encodeURIComponent(F)}`:e,X=new WebSocket(hs(z));b.current=X;let I=!1;return X.onopen=()=>w(!0),X.onclose=()=>{w(!1),v(!1),I||d(D=>[...D,{role:"meta",text:"disconnected — reopen the panel to reconnect",error:!0}])},X.onmessage=D=>{let V;try{V=JSON.parse(D.data)}catch{return}switch(V.type){case"session":{const H=V.sessionId||"";if(H&&(E.current=H,o))try{localStorage.setItem(o,H)}catch{}break}case"conv_meta":{const H=V.convUuid||"",J=V.convId||0;H&&x.current&&x.current({convId:J,convUuid:H});break}case"text":{L.current+=V.text||"",d(H=>{const J=H.slice();return T.current==null&&(J.push({role:"assistant",html:""}),T.current=J.length-1),J[T.current]={role:"assistant",html:jr(L.current),text:L.current},J}),$();break}case"tool_use":{T.current=null,L.current="",d(H=>{const J=[...H,{role:"assistant",tool:{name:V.tool||"tool",input:V.input||""}}];return P.current=J.length-1,J}),$();break}case"tool_result":{d(H=>{if(P.current==null)return H;const J=H.slice(),Q=J[P.current];return Q!=null&&Q.tool&&(J[P.current]={...Q,tool:{...Q.tool,result:V.result||""}}),J}),$();break}case"result":{V.isError?d(H=>[...H,{role:"meta",text:"Claude reported an error for this turn.",error:!0}]):V.model&&d(H=>[...H,{role:"meta",text:V.model}]);break}case"error":d(H=>[...H,{role:"meta",text:V.text||"error",error:!0}]);break;case"canceled":d(H=>[...H,{role:"meta",text:"stopped"}]);break;case"turn_end":if(v(!1),T.current=null,L.current="",P.current=null,a.current!=null){const H=a.current;c(null),a.current=null,setTimeout(()=>l.current(H),0)}break}},()=>{I=!0;try{X.close()}catch{}}},[e,$,_]);const R=C.useCallback(F=>{!b.current||b.current.readyState!==WebSocket.OPEN||(d(z=>[...z,{role:"user",html:jr(F)}]),b.current.send(JSON.stringify({prompt:F,ctx:(t==null?void 0:t())||""})),v(!0),B.current=!0,$())},[t,$]);l.current=R;const A=()=>{const F=m.trim();if(!(!g||!F)){if(S){c(F),f("");return}R(F),f("")}},M=()=>{var F;g&&S&&((F=b.current)==null||F.send(JSON.stringify({action:"cancel"})))},O=F=>{!g||S||R(F)},W=()=>{if(E.current="",o)try{localStorage.removeItem(o)}catch{}d([]),c(null),a.current=null,L.current="",T.current=null,P.current=null,j(F=>F+1)};return s.jsxs("div",{className:`chat-root${S?" busy":""}`,children:[s.jsxs("div",{className:"chat-topbar",children:[s.jsxs("p",{className:"muted cfg-note chat-warn",children:["⚠ This runs the ",s.jsx("strong",{children:"host"})," Claude — it is ",s.jsx("strong",{children:"not sandboxed"}),"."," ",n?s.jsxs(s.Fragment,{children:["It can ",s.jsx("strong",{children:"act"})," — Read/Grep/Glob plus ",s.jsx("strong",{children:"Bash"})," (runs commands, ",s.jsx("code",{children:"corral api"}),") on your machine."]}):s.jsx(s.Fragment,{children:"Read-only: Read, Grep, Glob — it can look, not act."})]}),r&&u.length>0&&s.jsx("button",{type:"button",className:"chat-newbtn",onClick:W,title:"Start a fresh conversation",children:"New chat"})]}),s.jsxs("div",{className:"chat-log",id:"log",ref:k,onScroll:q,children:[u.map((F,z)=>{if(F.role==="meta")return s.jsx("div",{className:`meta${F.error?" error":""}`,children:F.text},z);if(F.tool)return s.jsx("div",{className:"tool",children:s.jsxs("details",{children:[s.jsxs("summary",{children:[s.jsx("span",{className:"tool-name",children:F.tool.name})," ",s.jsx("span",{className:"tool-arg",children:eg(F.tool.input)})]}),s.jsxs("div",{className:"tool-body",children:[F.tool.input&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"label",children:"input"}),s.jsx("pre",{children:tg(F.tool.input)})]}),F.tool.result!=null&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"label",children:"result"}),s.jsx("pre",{children:F.tool.result})]})]})]})},z);const X=F.role==="assistant"?Ym(F.text||""):null;if(X)return s.jsxs("div",{className:`msg ${F.role}`,children:[s.jsx("div",{className:"avatar",children:"✳"}),s.jsxs("div",{className:"bubble",children:[X.rest&&s.jsx("div",{dangerouslySetInnerHTML:{__html:jr(X.rest)}}),s.jsx(Zm,{data:X})]})]},z);const I=z===u.length-1,D=F.role==="assistant"&&I&&!S?Qm(F.text||""):null;return D?s.jsxs("div",{className:`msg ${F.role}`,children:[s.jsx("div",{className:"avatar",children:"✳"}),s.jsxs("div",{className:"bubble",children:[D.rest&&s.jsx("div",{dangerouslySetInnerHTML:{__html:jr(D.rest)}}),s.jsxs("div",{className:"chat-question",children:[s.jsx("div",{className:"chat-question-q",children:D.question}),s.jsx("div",{className:"chat-question-opts",children:D.options.map((V,H)=>s.jsx("button",{type:"button",className:"chat-question-opt",onClick:()=>O(V),children:V},H))})]})]})]},z):s.jsxs("div",{className:`msg ${F.role}`,children:[s.jsx("div",{className:"avatar",children:F.role==="assistant"?"✳":"Y"}),s.jsx("div",{className:"bubble",dangerouslySetInnerHTML:{__html:F.html||""}})]},z)}),S&&T.current==null&&s.jsxs("div",{className:"msg assistant",children:[s.jsx("div",{className:"avatar",children:"✳"}),s.jsx("div",{className:"bubble",children:s.jsx("span",{className:"typing",children:"Claude is thinking…"})})]}),p!=null&&s.jsxs("div",{className:"msg user chat-queued",title:"Sends when the current turn finishes",children:[s.jsx("div",{className:"avatar",children:"Y"}),s.jsxs("div",{className:"bubble",children:[s.jsx("span",{className:"chat-queued-tag",children:"queued"}),p,s.jsx("button",{type:"button",className:"chat-queued-x",title:"Cancel this queued message",onClick:()=>c(null),children:"×"})]})]})]}),s.jsxs("div",{className:"chat-composer",children:[s.jsx("textarea",{id:"input",placeholder:"Ask Claude about this project…",value:m,onChange:F=>f(F.target.value),onKeyDown:F=>{F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),A())},rows:1,style:{maxHeight:160}}),s.jsx("button",{id:"send",disabled:!g||m.trim()==="",onClick:A,title:S?"Queue this message — sends when the current turn finishes":"Send",children:S?"Queue":"Send"}),S&&s.jsx("button",{id:"stop",onClick:M,children:"Stop"})]})]})}function Pc(e,t){return`corral.agentctx.staleDismissed.${e}.${t}`}function sg(e){try{return localStorage.getItem(e)||""}catch{return""}}function rg(e,t){try{localStorage.setItem(e,t)}catch{}}function ng(e){return e>=60?`${Math.round(e/30)} months`:e>=14?`${Math.round(e/7)} weeks`:`${e} days`}function cl({repoId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(!1),[h,y]=C.useState(null),o=C.useCallback(()=>{e&&ee(`/api/repos/${encodeURIComponent(e)}/agent-context`).then(m=>{r(m),i(sg(Pc(e,m.updatedAt))==="1")}).catch(()=>r(null))},[e]);if(C.useEffect(()=>o(),[o]),!e||!t||!t.stale||n)return null;const u=()=>{rg(Pc(e,t.updatedAt),"1"),i(!0)},d=async()=>{try{await oe(`/api/repos/${encodeURIComponent(e)}/generate-agents-md`,{}),y("Regenerating AGENTS.md — watch the Work tab (⌘K); it updates here when done.")}catch(m){y(`Couldn't start regeneration: ${m.message}`)}};return h?s.jsxs("div",{className:"update-banner",role:"status",children:[s.jsx("span",{className:"update-banner-text",children:h}),s.jsx("span",{className:"update-banner-actions",children:s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:()=>y(null),children:"✕"})})]}):s.jsxs("div",{className:"update-banner update-banner-warn",role:"status",children:[s.jsxs("span",{className:"update-banner-text",children:["This repo's ",s.jsx("strong",{children:"AGENTS.md"})," context is ",s.jsx("strong",{children:ng(t.ageDays)})," old"," ",s.jsxs("span",{className:"muted",children:["(stale after ",t.thresholdDays," days)"]})," — the codebase has likely drifted from it."]}),s.jsxs("span",{className:"update-banner-actions",children:[s.jsx("button",{className:"update-banner-btn",onClick:d,title:"Explore the repo and redraft it with AI",children:"Regenerate"}),s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:u,children:"✕"})]})]})}const ig={js:["JS","#f0db4f"],jsx:["JS","#f0db4f"],mjs:["JS","#f0db4f"],cjs:["JS","#f0db4f"],ts:["TS","#3178c6"],tsx:["TS","#3178c6"],go:["GO","#00add8"],py:["PY","#3572a5"],rb:["RB","#cc342d"],rs:["RS","#dea584"],java:["JV","#b07219"],c:["C","#555555"],h:["H","#555555"],cpp:["C+","#f34b7d"],json:["{}","#cbcb41"],yml:["YM","#cb171e"],yaml:["YM","#cb171e"],toml:["TO","#9c4221"],md:["MD","#519aba"],markdown:["MD","#519aba"],txt:["TX","#9aa4b0"],html:["<>","#e34c26"],htm:["<>","#e34c26"],css:["#","#563d7c"],scss:["#","#c6538c"],sh:["SH","#89e051"],bash:["SH","#89e051"],zsh:["SH","#89e051"],dockerfile:["DK","#384d54"],sql:["SQ","#e38c00"],xml:["0?t.slice(r+1):""}function ag(e){return ig[og(e)]||["·","#8a94a6"]}let jn=null;function Pi(){return window.CorralEditor?Promise.resolve(window.CorralEditor):jn||(jn=new Promise((e,t)=>{const r=document.createElement("script");r.src="/static/codemirror.bundle.js",r.onload=()=>{window.CorralEditor?e(window.CorralEditor):t(new Error("codemirror bundle loaded but CorralEditor is missing"))},r.onerror=()=>t(new Error("failed to load codemirror bundle")),document.head.appendChild(r)}),jn)}function gs(e,t){return`/p/${e}${t}`}function Td({name:e}){const[t,r]=ag(e);return s.jsx("span",{className:"ficon",style:{color:r},children:t})}function Pd({projectId:e,relPath:t,name:r,depth:n,openPath:i,onOpenFile:h,onCtx:y,refreshToken:o}){const u=r===null,[d,m]=C.useState(u),[f,g]=C.useState(null),[w,S]=C.useState(null),v=C.useCallback(()=>{ee(gs(e,`/files/tree?path=${encodeURIComponent(t)}`)).then(c=>{g(c.entries||[]),S(null)}).catch(c=>S(c.message))},[e,t]);if(C.useEffect(()=>{d&&v()},[d,v,o]),!u&&!d)return s.jsx("li",{className:"ftree-dir collapsed","data-name":r,children:s.jsxs("span",{className:"ftree-label",onClick:c=>{c.stopPropagation(),m(!0)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),y({x:c.clientX,y:c.clientY,rel:t,isDir:!0})},children:[s.jsx("span",{className:"ficon ficon-dir",children:"▸"}),s.jsx("span",{className:"ftree-name",children:r})]})});const p=s.jsxs(s.Fragment,{children:[w&&s.jsxs("p",{className:"attention",children:["tree error: ",w]}),s.jsx("ul",{children:(f||[]).map(c=>{const a=t?`${t}/${c.name}`:c.name;return c.dir?s.jsx(Pd,{projectId:e,relPath:a,name:c.name,depth:n+1,openPath:i,onOpenFile:h,onCtx:y,refreshToken:o},c.name):s.jsx("li",{className:`ftree-file${i===a?" active":""}`,"data-name":c.name,"data-path":a,children:s.jsxs("span",{className:"ftree-label",onClick:l=>{l.stopPropagation(),h(a)},onContextMenu:l=>{l.preventDefault(),l.stopPropagation(),y({x:l.clientX,y:l.clientY,rel:a,isDir:!1})},children:[s.jsx(Td,{name:c.name}),s.jsx("span",{className:"ftree-name",children:c.name})]})},c.name)})})]});return u?p:s.jsxs("li",{className:"ftree-dir","data-name":r,"data-dir":"1",children:[s.jsxs("span",{className:"ftree-label",onClick:c=>{c.stopPropagation(),m(!1)},onContextMenu:c=>{c.preventDefault(),c.stopPropagation(),y({x:c.clientX,y:c.clientY,rel:t,isDir:!0})},children:[s.jsx("span",{className:"ficon ficon-dir",children:"▸"}),s.jsx("span",{className:"ftree-name",children:r})]}),p]})}function lg({projectId:e}){const[t,r]=C.useState(0),n=C.useCallback(()=>r(z=>z+1),[]),i=C.useRef(null),h=C.useRef(null),[y,o]=C.useState(null),u=C.useRef(null),[d,m]=it(`corral.filesOpen.${e}`,null),f=C.useRef(!1),[g,w]=C.useState(!1),S=C.useRef(!1),[v,p]=C.useState(null),[c,a]=C.useState("name"),[l,_]=C.useState(""),[j,b]=C.useState(null),[k,x]=C.useState(null),[N,E]=C.useState(!1),[L,T]=C.useState(null),P=z=>{S.current=z,w(z)},B=C.useCallback(async(z,X)=>{var I,D;if(!(S.current&&!window.confirm(`Discard unsaved changes to ${u.current}?`)))try{const V=await ee(gs(e,`/files/read?path=${encodeURIComponent(z)}`));if(u.current=z,o(z),m(z),V.too_large){(I=h.current)==null||I.destroy(),h.current=null,p(V.size||0),P(!1);return}p(null);const H=await Pi();(D=h.current)==null||D.destroy(),i.current&&(i.current.innerHTML=""),h.current=H.createEditor({parent:i.current,doc:V.content||"",filename:V.filename||z,onChange:()=>{S.current||P(!0)}}),P(!1),X&&h.current.view&&H.scrollToLineEffect}catch(V){i.current&&(i.current.innerHTML=`

read error: ${V.message}

`)}},[e,m]);C.useEffect(()=>{f.current||(f.current=!0,d&&B(d))},[]);const U=C.useCallback(async()=>{if(!(!h.current||u.current==null))try{const z=await fetch(gs(e,`/files/write?path=${encodeURIComponent(u.current)}`),{method:"POST",credentials:"same-origin",body:h.current.getDoc()});if(!z.ok)throw new Error(await z.text()||`HTTP ${z.status}`);P(!1)}catch(z){alert(`save failed: ${z.message}`)}},[e]),K=z=>je(gs(e,z)),q=z=>{const X=z.lastIndexOf("/");return X<0?"":z.slice(0,X)},$=(z,X)=>z?`${z}/${X}`:X;async function R(z,X,I){try{const D=await z;if(!D.ok)throw new Error(await D.text()||`HTTP ${D.status}`);n(),I==null||I()}catch(D){alert(`${X} failed: ${D.message}`)}}const A=z=>{const X=window.prompt("New file name:");X&&R(K(`/files/new?path=${encodeURIComponent($(z,X))}`),"create file",()=>B($(z,X)))},M=z=>{const X=window.prompt("New folder name:");X&&R(K(`/files/mkdir?path=${encodeURIComponent($(z,X))}`),"create folder")},O=z=>{const X=z.split("/").pop(),I=window.prompt("Rename to:",X);if(!I||I===X)return;const D=$(q(z),I);R(K(`/files/rename?from=${encodeURIComponent(z)}&to=${encodeURIComponent(D)}`),"rename")},W=(z,X)=>{window.confirm(`Delete ${X?"folder":"file"} '${z}'?${X?" (recursive)":""}`)&&R(fetch(gs(e,`/files?path=${encodeURIComponent(z)}`),{method:"DELETE",credentials:"same-origin"}),"delete")};C.useEffect(()=>{const z=()=>T(null),X=I=>I.key==="Escape"&&T(null);return document.addEventListener("click",z),document.addEventListener("keydown",X),()=>{document.removeEventListener("click",z),document.removeEventListener("keydown",X)}},[]),C.useEffect(()=>{const z=l.trim();if(!z){b(null),x(null),E(!1);return}E(!0);const X=window.setTimeout(async()=>{try{c==="grep"?(x(await ee(gs(e,`/files/grep?q=${encodeURIComponent(z)}`))),b(null)):(b(await ee(gs(e,`/files/find?q=${encodeURIComponent(z)}`))),x(null))}catch{}},220);return()=>window.clearTimeout(X)},[l,c,e]),C.useEffect(()=>{const z=window.setInterval(()=>{l.trim()||n()},2500);return()=>window.clearInterval(z)},[l,n]),C.useEffect(()=>{const z=i.current;if(!z)return;const X=I=>{(I.ctrlKey||I.metaKey)&&(I.key==="s"||I.key==="S")&&(I.preventDefault(),S.current&&U())};return z.addEventListener("keydown",X),()=>z.removeEventListener("keydown",X)},[U]);const F=l.trim()!=="";return s.jsxs("div",{className:"files-root",children:[s.jsxs("div",{className:"files-side",children:[s.jsxs("div",{className:"files-search",children:[s.jsx("input",{id:"files-q",type:"text",placeholder:c==="grep"?"search file contents…":"search files…",autoComplete:"off",spellCheck:!1,value:l,onChange:z=>_(z.target.value)}),s.jsxs("div",{className:"files-search-mode",children:[s.jsx("button",{className:c==="name"?"active":"",type:"button",title:"Find files by name",onClick:()=>a("name"),children:"name"}),s.jsx("button",{className:c==="grep"?"active":"",type:"button",title:"Search file contents (grep)",onClick:()=>a("grep"),children:"grep"}),s.jsx("button",{type:"button",title:"Refresh the file tree",onClick:n,children:"⟳"})]})]}),!F&&s.jsx("div",{className:"files-tree",onContextMenu:z=>{z.target.closest(".ftree-label")||(z.preventDefault(),T({x:z.clientX,y:z.clientY,rel:"",isDir:!0}))},children:s.jsx(Pd,{projectId:e,relPath:"",name:null,depth:0,openPath:y,onOpenFile:B,onCtx:T,refreshToken:t})}),F&&s.jsxs("div",{className:"files-results",children:[N&&!j&&!k&&s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"searching…"}),c==="name"&&j&&((j.matches||[]).length===0?s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"no matching files"}):s.jsxs(s.Fragment,{children:[(j.matches||[]).map(z=>{const X=z.split("/").pop();return s.jsxs("div",{className:"sresult",onClick:()=>B(z),children:[s.jsx(Td,{name:X}),s.jsx("span",{className:"sresult-path",children:z})]},z)}),j.truncated&&s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"…results truncated — narrow your search"})]})),c==="grep"&&k&&((k.hits||[]).length===0?s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"no matches"}):s.jsxs(s.Fragment,{children:[(k.hits||[]).map((z,X)=>s.jsxs("div",{className:"sresult sresult-grep",onClick:()=>B(z.path,z.line),children:[s.jsxs("div",{className:"sresult-loc",children:[z.path,s.jsxs("span",{className:"sresult-ln",children:[":",z.line]})]}),s.jsx("div",{className:"sresult-text",children:z.text})]},`${z.path}:${z.line}:${X}`)),k.truncated&&s.jsx("p",{className:"muted",style:{padding:"0.5rem"},children:"…results truncated — narrow your search"})]}))]})]}),s.jsxs("div",{className:"files-editor",children:[s.jsxs("div",{className:"files-editor-bar",children:[s.jsx("span",{className:y?"":"muted",children:(y||"select a file")+(g?" •":"")}),s.jsx("button",{type:"button",disabled:!g||y==null,onClick:U,children:"Save"})]}),v!=null?s.jsxs("p",{className:"muted",style:{padding:"1rem"},children:["file is too large to edit here (",v," bytes)"]}):s.jsx("div",{className:"files-cm",ref:i})]}),L&&s.jsxs("div",{className:"ctx-menu",style:{left:L.x,top:L.y},onClick:z=>z.stopPropagation(),children:[L.isDir&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),A(L.rel)},children:"New file"}),s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),M(L.rel)},children:"New folder"})]}),L.rel!==""&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),O(L.rel)},children:"Rename"}),s.jsx("div",{className:"ctx-item",onClick:()=>{T(null),W(L.rel,L.isDir)},children:"Delete"})]})]})]})}function Nn(e,t){return`/p/${e}${t}`}function cg(e){const t=e.trim();return t==="??"?"new":t.includes("M")?"modified":t.includes("A")?"added":t.includes("D")?"deleted":t.includes("R")?"renamed":t||"changed"}function ug({projectId:e}){var x;const[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState([]),[o,u]=C.useState(""),[d,m]=C.useState(""),[f,g]=C.useState(null),[w,S]=C.useState(!1),[v,p]=C.useState(null),c=C.useRef(null),a=C.useRef(null),l=C.useRef(!1),_=o!==""&&d!=="",j=C.useCallback(()=>{let N=n?`&repo=${encodeURIComponent(n)}`:"";return _&&(N+=`&base=${encodeURIComponent(o)}&target=${encodeURIComponent(d)}`),N},[n,o,d,_]);C.useEffect(()=>{ee(Nn(e,"/git/repos")).then(N=>{r(N);const E=N.repos||[];E.length<=1?E.length===1&&E[0].path&&!N.rootIsRepo&&i(E[0].path):i(N.rootIsRepo?"":E[0].path)}).catch(()=>{})},[e]),C.useEffect(()=>{const N=n?`?repo=${encodeURIComponent(n)}`:"";ee(Nn(e,`/git/refs${N}`)).then(E=>{if(!E.repo){y([]);return}const L=E.branches||[];if(y(L.concat(E.tags||[])),!l.current&&!_&&L.length>0){l.current=!0;const T=E.current||"",P=["main","master","trunk"].filter(B=>L.includes(B))[0];T&&P&&T!==P&&(u(P),m(T))}}).catch(()=>{})},[e,n]),C.useEffect(()=>{g(null),S(!1),ee(Nn(e,`/git/status?_=1${j()}`)).then(N=>{if(!N.repo){S(!0);return}g(N.changes||[])}).catch(()=>g([]))},[e,j]);const b=C.useCallback(async N=>{var E,L;p(N);try{const T=await ee(Nn(e,`/git/file?path=${encodeURIComponent(N)}${j()}`));if((T.original||"")===(T.modified||"")){(E=a.current)==null||E.destroy(),a.current=null,c.current&&(c.current.innerHTML='no differences in this file');return}const P=await Pi();(L=a.current)==null||L.destroy(),c.current&&(c.current.innerHTML=""),a.current=P.createDiff({parent:c.current,original:T.original||"",modified:T.modified||"",filename:T.filename||N})}catch(T){c.current&&(c.current.innerHTML=`diff error: ${T.message}`)}},[e,j]);C.useEffect(()=>{f&&f.length>0&&b(f[0].path)},[f]);const k=(((x=t==null?void 0:t.repos)==null?void 0:x.length)||0)>1;return s.jsxs("div",{className:"diff-root",children:[s.jsxs("div",{className:"diff-side",children:[k&&s.jsx("div",{className:"diff-repo",children:s.jsx("select",{className:"diff-ref",title:"Repository",value:n,onChange:N=>{i(N.target.value),u(""),m("")},children:((t==null?void 0:t.repos)||[]).map(N=>s.jsx("option",{value:N.path,children:N.name},N.path))})}),s.jsxs("div",{className:"diff-refs",children:[s.jsxs("select",{className:"diff-ref",title:"Base ref",value:o,onChange:N=>u(N.target.value),children:[s.jsx("option",{value:"",children:"— working tree —"}),h.map(N=>s.jsx("option",{value:N,children:N},N))]}),s.jsx("span",{className:"diff-refs-arrow",children:"→"}),s.jsxs("select",{className:"diff-ref",title:"Target ref",value:d,onChange:N=>m(N.target.value),children:[s.jsx("option",{value:"",children:"— working tree —"}),h.map(N=>s.jsx("option",{value:N,children:N},N))]}),_&&s.jsx("button",{type:"button",title:"Back to working-tree changes",onClick:()=>{u(""),m("")},children:"✕"})]}),s.jsxs("div",{className:"diff-list",children:[w&&s.jsx("p",{className:"muted",children:"not a git repository"}),!w&&f===null&&s.jsx("p",{className:"muted",children:"loading…"}),!w&&f&&f.length===0&&s.jsx("p",{className:"muted",children:_?`no differences between ${o} and ${d}`:"working tree clean — no changes"}),(f||[]).map(N=>s.jsxs("div",{className:`diff-file${v===N.path?" active":""}`,onClick:()=>b(N.path),children:[s.jsx("span",{className:"d-status",children:cg(N.status)}),s.jsx("span",{className:"d-path",children:N.path}),(N.added||N.removed)&&s.jsxs("span",{className:"d-stat",children:[s.jsxs("span",{className:"d-add",children:["+",N.added]})," ",s.jsxs("span",{className:"d-del",children:["-",N.removed]})]})]},N.path))]})]}),s.jsx("div",{className:"diff-view",children:s.jsx("div",{className:"diff-body",ref:c,children:s.jsx("span",{className:"muted",children:"select a changed file"})})})]})}function Oc(e){if(e==null||e<=0)return"—";const t=["B","KB","MB","GB","TB"];let r=e,n=0;for(;r>=1024&&n{}),[w,S]=C.useState(""),[v,p]=C.useState("minimal"),[c,a]=C.useState(""),[l,_]=C.useState(""),[j,b]=C.useState([]),[k,x]=C.useState({}),[N,E]=C.useState({host:"",kind:"header",name:"",value:""}),[L,T]=C.useState(!1),[P,B]=C.useState(!1),[U,K]=C.useState(!1),[q,$]=C.useState(""),[R,A]=C.useState(!1),[M,O]=C.useState(""),[W,F]=C.useState(""),[z,X]=C.useState("copy"),[I,D]=C.useState([]),[V,H]=C.useState(""),[J,Q]=C.useState([]),[re,ie]=C.useState({}),[he,Ce]=C.useState(""),[ae,dt]=C.useState(null),wt=G=>G.split(` +`).map(se=>se.trim()).filter(Boolean),nt=C.useCallback(G=>{ee(Dt(e,"/config")).then(se=>{var Ds,ml;n(se),S((se.allowed_hosts||[]).join(` `)),p(se.mitm_preset||"minimal"),a((se.monitor_hosts||[]).join(` `)),_((se.mitm_ports||[]).join(` -`)),T(se.proxy_enabled),B(se.passthrough_firewall),z(se.dind_enabled),$((se.dind_ports||[]).join(` -`)),Y(((Ds=se.dind_cache)==null?void 0:Ds.name)||""),J(((ml=se.dind_cache)==null?void 0:ml.mode)==="shared"?"shared":"copy"),D(se.launch_tmux),P(se.seccomp_mode||""),b([]),x({}),new Set((se.ssh_keys_global||[]).map(kt));const ue={};(se.ssh_keys||[]).forEach(Gd=>{ue[Gd]=!0}),ie(ue),V&&h({text:V,err:!1})}).catch(se=>h({text:`load failed: ${se.message}`,err:!0}))},[e]);C.useEffect(()=>nt(),[nt]);const ft=C.useCallback(()=>{ee("/api/dind/caches").then(V=>A(V.caches||[])).catch(()=>A([]))},[]);C.useEffect(()=>ft(),[ft]);const Ie=V=>V.split(` +`)),T(se.proxy_enabled),B(se.passthrough_firewall),K(se.dind_enabled),$((se.dind_ports||[]).join(` +`)),F(((Ds=se.dind_cache)==null?void 0:Ds.name)||""),X(((ml=se.dind_cache)==null?void 0:ml.mode)==="shared"?"shared":"copy"),A(se.launch_tmux),O(se.seccomp_mode||""),b([]),x({}),new Set((se.ssh_keys_global||[]).map(kt));const ue={};(se.ssh_keys||[]).forEach(Gd=>{ue[Gd]=!0}),ie(ue),G&&h({text:G,err:!1})}).catch(se=>h({text:`load failed: ${se.message}`,err:!0}))},[e]);C.useEffect(()=>nt(),[nt]);const ft=C.useCallback(()=>{ee("/api/dind/caches").then(G=>D(G.caches||[])).catch(()=>D([]))},[]);C.useEffect(()=>ft(),[ft]);const Ie=G=>G.split(` `).map(se=>se.trim()).filter(Boolean).join(` `),Le=!!r&&(Ie(w)!==Ie((r.allowed_hosts||[]).join(` `))||v!==(r.mitm_preset||"minimal")||Ie(c)!==Ie((r.monitor_hosts||[]).join(` `))||Ie(l)!==Ie((r.mitm_ports||[]).join(` -`))||j.length>0||Object.keys(k).length>0||L!==r.proxy_enabled||O!==r.passthrough_firewall||F!==r.dind_enabled||Ie(K)!==Ie((r.dind_ports||[]).join(` -`))||U!==(((fl=r.dind_cache)==null?void 0:fl.name)||"")||!!U&&H!==(((pl=r.dind_cache)==null?void 0:pl.mode)==="shared"?"shared":"copy")||R!==r.launch_tmux||M!==(r.seccomp_mode||"")),G=C.useRef(Le);G.current=Le,C.useEffect(()=>{t&&(G.current||nt())},[t]),C.useEffect(()=>{const V=()=>{document.visibilityState!=="hidden"&&!G.current&&nt()};return window.addEventListener("focus",V),document.addEventListener("visibilitychange",V),()=>{window.removeEventListener("focus",V),document.removeEventListener("visibilitychange",V)}},[nt]),C.useEffect(()=>{ee(Dt(e,"/sshkeys/available")).then(V=>Q(V.keys||[])).catch(()=>{})},[e]);const te=C.useCallback(()=>{ee(Dt(e,"/sshkeys/status")).then(dt).catch(()=>dt(null))},[e]);C.useEffect(()=>te(),[te]);const Se=C.useCallback(()=>{const V=new Set(((r==null?void 0:r.ssh_keys_global)||[]).map(kt));return Object.keys(re).filter(se=>re[se]&&!V.has(kt(se)))},[re,r]);function Ut(){const V={};V.allowed_hosts=wt(w),V.mitm_preset=v,v==="custom"&&(V.monitor_hosts=wt(c)),V.mitm_ports=wt(l),j.length&&(V.set_creds=j.slice());const se=Object.keys(k).filter(ue=>k[ue]);return se.length&&(V.unset_creds=se),V}function Te(){return{proxy_enabled:L,passthrough_firewall:O,dind_enabled:F,dind_ports:wt(K),dind_cache:U?{name:U,mode:H}:null,launch_tmux:R,seccomp_mode:M,ssh_keys:Se()}}async function Rs(){const V=Ut();try{const ue=(await oe(Dt(e,"/config/diff"),V)).entries||[];if(!ue.length){h({text:"no changes",err:!1});return}o(ue)}catch(se){h({text:`diff failed: ${se.message}`,err:!0})}}async function bt(){const V=Ut();try{const se=await oe(Dt(e,"/config/apply"),V);o(null),nt((se.results||[]).join(" • ")||"✓ applied")}catch(se){o(null),h({text:`apply failed: ${se.message}`,err:!0})}}const Lt=C.useCallback(async V=>{d(!0);try{const se=await je(Dt(e,"/config/restart"),V),ue=await se.json().catch(()=>({}));if(se.status===409&&(ue!=null&&ue.ssh_keys_pending)){h({text:"load SSH keys to continue the restart…",err:!1}),d(!1),g.current=()=>{h({text:"keys loaded — restarting…",err:!1}),Lt(V)},f(!0);return}if(se.status>=400)throw new Error((ue==null?void 0:ue.error)||`HTTP ${se.status}`);h({text:((ue==null?void 0:ue.results)||[]).join(" • "),err:!1})}catch(se){h({text:`restart failed: ${se.message}`,err:!0})}finally{d(!1)}},[e]);function pe(){window.confirm("Restart this project now? This kills the container and any running session in it.")&&Lt(Te())}const[Ls,ln]=C.useState(!1);async function Fd(){const V=q.trim();if(!/^[a-zA-Z0-9_-]{1,64}$/.test(V)){h({text:"cache name: letters, digits, dashes, underscores (max 64)",err:!0});return}ln(!0),h({text:`saving cache “${V}” — copying the DinD volume, this can take a while…`,err:!1});try{await oe("/api/dind/caches",{name:V,project:e}),W(""),h({text:`✓ saved cache “${V}”`,err:!1}),ft()}catch(se){h({text:`save cache failed: ${se.message}`,err:!0})}finally{ln(!1)}}async function Ud(V,se){const ue=`repo-${V}`;if(!(se&&!window.confirm(`Update the repo baseline “${ue}” to this project's current inner-docker data? New projects from this repo will start from it.`))){ln(!0),h({text:`saving repo baseline “${ue}” — copying the DinD volume, this can take a while…`,err:!1});try{se&&await St(`/api/dind/caches/${encodeURIComponent(ue)}`),await oe("/api/dind/caches",{name:ue,project:e}),h({text:`✓ saved repo baseline “${ue}” — new projects from this repo will reuse it`,err:!1}),ft()}catch(Ds){h({text:`save repo cache failed: ${Ds.message}`,err:!0})}finally{ln(!1)}}}async function zd(V){if(window.confirm(`Delete DinD cache “${V}”? Projects still set to use it will fail to start until you re-point them.`))try{await St(`/api/dind/caches/${encodeURIComponent(V)}`),U===V&&Y(""),h({text:`✓ deleted cache “${V}”`,err:!1}),ft()}catch(se){h({text:`delete cache failed: ${se.message}`,err:!0})}}function Wd(){const V=N.host.trim().toLowerCase(),se=N.name.trim();if(!V||!se||!N.value){h({text:"credential needs host, name, and value",err:!0});return}b(ue=>[...ue,{host:V,kind:N.kind,name:se,value:N.value}]),E({host:"",kind:"header",name:"",value:""}),h({text:"credential queued — click Review changes to apply",err:!1})}const Kd=new Set(((r==null?void 0:r.ssh_keys_global)||[]).map(kt)),hl=X.map(V=>{const se=Kd.has(kt(V.name));return{value:V.name,locked:se,checked:se||!!re[V.name],meta:V.comment||V.type}}),Vd=new Set(hl.map(V=>kt(V.value))),qd=((r==null?void 0:r.ssh_keys)||[]).filter(V=>!Vd.has(kt(V))).map(V=>({value:V,locked:!1,checked:!0,meta:"custom path"})),dl=[...hl,...qd],Oi=new Set;return((r==null?void 0:r.ssh_keys_global)||[]).forEach(V=>Oi.add(kt(V))),Se().forEach(V=>Oi.add(kt(V))),r?s.jsxs("div",{id:"config-root",children:[s.jsx("p",{className:"cfg-status",children:r.container_up?s.jsx("span",{className:"s-2xx",children:"container running — live changes apply immediately"}):s.jsx("span",{className:"muted",children:"container not running — live changes save for next start"})}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Live ",s.jsx("span",{className:"muted",children:"— hot-reloaded, no restart"})]}),s.jsx(Xe,{label:"Allowed hosts",children:s.jsx("textarea",{className:"cfg-edit",rows:Math.max(2,w.split(` -`).length+1),spellCheck:!1,value:w,onChange:V=>S(V.target.value)})}),s.jsxs(Xe,{label:"Capture (mitm)",children:[s.jsxs("select",{className:"cfg-select",value:v,onChange:V=>p(V.target.value),children:[s.jsx("option",{value:"minimal",children:"Minimal — Claude + GitHub only"}),s.jsx("option",{value:"all",children:"All — every allowed host"}),s.jsx("option",{value:"none",children:"None — decrypt nothing"}),s.jsx("option",{value:"custom",children:"Custom — the host list below"})]}),v==="custom"&&s.jsxs("div",{children:[s.jsx(dg,{value:c,onChange:a,onPersist:async V=>{a(V.join(` -`));try{const se=await oe(Dt(e,"/config/apply"),{mitm_preset:"custom",monitor_hosts:V});h({text:(se.results||[]).join(" • ")||"✓ monitor list updated",err:!1})}catch(se){h({text:`apply failed: ${se.message}`,err:!0})}}}),s.jsx("div",{className:"muted cfg-note",children:"only these hosts are decrypted; others allowed+logged but direct-dialed. Hosts with an injected credential are always decrypted regardless (required for credential injection) and aren't listed here."})]}),s.jsxs("div",{className:"cfg-warn",children:[s.jsx("strong",{children:"⚠ Monitoring a host makes the proxy present its own CA."})," Clients that pin certificates or statically link their TLS with a bundled root store won’t trust it — the handshake fails and the request never completes (so a broken host won’t even appear in the Mitm tab). If a host breaks when monitored, remove it here; it falls back to direct-dial (undecrypted) and works again."]})]}),s.jsxs(Xe,{label:"Mitm ports",children:[s.jsx("textarea",{className:"cfg-edit",rows:Math.max(2,l.split(` -`).length+1),spellCheck:!1,value:l,onChange:V=>_(V.target.value)}),s.jsx("div",{className:"muted cfg-note",children:"other ports (ssh, socks, git-over-ssh) are direct-dialed"})]}),s.jsxs(Xe,{label:"Credentials",children:[s.jsx("table",{className:"cfg-creds",children:s.jsxs("tbody",{children:[(r.credentials||[]).map(V=>s.jsxs("tr",{style:{opacity:k[V.host]?.4:1},children:[s.jsx("td",{children:V.host}),s.jsxs("td",{children:[V.kind,": ",V.name]}),s.jsx("td",{className:"muted",children:V.masked}),s.jsx("td",{children:s.jsx("button",{className:"cfg-cred-rm",onClick:()=>{x(se=>({...se,[V.host]:!0})),h({text:`credential ${V.host} queued for removal — Review to apply`,err:!1})},children:"remove"})})]},V.host)),j.map((V,se)=>s.jsxs("tr",{children:[s.jsx("td",{children:V.host}),s.jsxs("td",{children:[V.kind,": ",V.name]}),s.jsx("td",{className:"s-2xx",children:"pending"}),s.jsx("td",{})]},`new-${se}`))]})}),s.jsxs("div",{className:"cfg-cred-add",children:[s.jsx("input",{placeholder:"host (api.foo.com)",value:N.host,onChange:V=>E({...N,host:V.target.value})}),s.jsxs("select",{value:N.kind,onChange:V=>E({...N,kind:V.target.value}),children:[s.jsx("option",{value:"header",children:"header"}),s.jsx("option",{value:"url_param",children:"url_param"})]}),s.jsx("input",{placeholder:"name (X-API-Key)",value:N.name,onChange:V=>E({...N,name:V.target.value})}),s.jsx("input",{placeholder:"value (secret)",type:"password",value:N.value,onChange:V=>E({...N,value:V.target.value})}),s.jsx("button",{className:"cfg-btn",onClick:Wd,children:"Add credential"})]})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn",onClick:Rs,children:"Review changes"}),i&&s.jsx("span",{className:`cfg-msg ${i.err?"s-4xx":"s-2xx"}`,children:i.text})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Restart required ",s.jsx("span",{className:"muted",children:"— needs a project restart"})]}),s.jsx(Xe,{label:"Workspace",children:s.jsx("code",{children:r.workspace})}),s.jsxs(Xe,{label:"Network protection",children:[s.jsx(En,{checked:L,onChange:T}),s.jsx("div",{className:"muted cfg-note",children:"On: traffic goes through the proxy — MITM inspection, credential injection, and the allowlist firewall. Off: fully open network (no proxy, no firewall)."})]}),s.jsxs(Xe,{label:"Passthrough firewall",children:[s.jsx(En,{checked:O,onChange:B}),s.jsxs("div",{className:"muted cfg-note",children:["Keeps the proxy on (inspection + credentials) but ALLOWS + logs unknown domains instead of blocking, and permits direct TCP so ",s.jsx("code",{children:"git"})," over SSH works. Needs Network protection on."]})]}),s.jsx(Xe,{label:"Docker-in-Docker",children:s.jsx(En,{checked:F,onChange:z})}),s.jsx(Xe,{label:"Published ports",children:s.jsx("textarea",{className:"cfg-edit",rows:Math.max(2,K.split(` -`).length+1),spellCheck:!1,value:K,onChange:V=>$(V.target.value)})}),F&&s.jsx(Xe,{label:"Start from cache",children:s.jsxs("div",{className:"cfg-cache",children:[s.jsxs("div",{className:"cfg-cache-row",children:[s.jsxs("select",{className:"cfg-select",value:U,onChange:V=>Y(V.target.value),children:[s.jsx("option",{value:"",children:"None — fresh, empty inner docker"}),I.map(V=>s.jsxs("option",{value:V.name,children:[V.name," (",Oc(V.bytes),")"]},V.name))]}),U&&s.jsxs("select",{className:"cfg-select",value:H,onChange:V=>J(V.target.value==="shared"?"shared":"copy"),children:[s.jsx("option",{value:"copy",children:"Copy — throwaway (cache untouched)"}),s.jsx("option",{value:"shared",children:"Shared — changes persist to the cache"})]})]}),s.jsxs("div",{className:"muted cfg-note",children:["A cache is a prebuilt inner-docker data root (images + volumes) so a project doesn't rebuild/re-seed each time. ",s.jsx("b",{children:"Copy"})," seeds a fresh per-project volume from the cache on first start; ",s.jsx("b",{children:"Shared"})," mounts the cache directly so a migration writes back. Changing this needs a restart."]}),(r==null?void 0:r.repo_id)&&(()=>{const V=r.repo_id,se=`repo-${V}`,ue=I.some(Ds=>Ds.name===se);return s.jsxs("div",{className:"cfg-repo-cache",children:[s.jsxs("div",{className:"cfg-repo-cache-head",children:[s.jsx("b",{children:"Repo baseline"}),s.jsx("code",{children:se}),ue?s.jsx("span",{className:"cfg-repo-cache-badge on",children:"saved · reused by new projects from this repo"}):s.jsx("span",{className:"cfg-repo-cache-badge",children:"not saved yet"})]}),s.jsx("div",{className:"muted cfg-note",children:"Save this project's built images + seeded volumes as the shared baseline for this repo. New projects created from the same repo auto-start from it (copy mode) instead of building from an empty inner docker."}),s.jsx("button",{className:"cfg-btn",disabled:Ls,onClick:()=>Ud(V,ue),children:Ls?"Saving…":ue?"Update repo baseline":"Save as repo baseline"})]})})(),s.jsxs("div",{className:"cfg-cache-save",children:[s.jsx("input",{className:"cfg-edit cfg-cache-name",placeholder:"new-cache-name",value:q,spellCheck:!1,onChange:V=>W(V.target.value)}),s.jsx("button",{className:"cfg-btn",disabled:Ls||!q.trim(),onClick:Fd,children:Ls?"Saving…":"Save current data as cache"})]}),s.jsx("div",{className:"muted cfg-note",children:"Snapshots this project's current inner-docker data (built images + seeded volumes) into a reusable cache. Full copy — can take a while for large data roots."}),I.length>0&&s.jsx("ul",{className:"cfg-cache-list",children:I.map(V=>s.jsxs("li",{children:[s.jsx("code",{children:V.name})," ",s.jsx("span",{className:"muted",children:Oc(V.bytes)}),s.jsx("button",{className:"cfg-cache-del",title:"Delete cache",onClick:()=>zd(V.name),children:"×"})]},V.name))})]})}),s.jsx(Xe,{label:"Launch tmux",children:s.jsx(En,{checked:R,onChange:D})}),s.jsxs(Xe,{label:"Seccomp",children:[s.jsxs("select",{className:"cfg-select",value:M,onChange:V=>P(V.target.value),children:[s.jsx("option",{value:"",children:"Default (Docker profile)"}),s.jsx("option",{value:"unconfined",children:"Unconfined — no filtering"})]}),s.jsx("div",{className:"muted cfg-note",children:"unconfined allows syscalls the default profile blocks (e.g. Erlang/BEAM). No effect with Docker-in-Docker (already privileged)."})]}),s.jsxs(Xe,{label:"SSH keys",children:[s.jsxs("div",{className:"cfg-ssh-list",children:[dl.length===0&&s.jsx("div",{className:"muted cfg-note",children:"no keys found under ~/.ssh"}),dl.map(V=>s.jsxs("label",{className:`cfg-ssh-item${V.locked?" locked":""}`,children:[s.jsx("input",{type:"checkbox",className:"cfg-ssh-key",checked:V.locked?!0:!!re[V.value],disabled:V.locked,onChange:se=>ie(ue=>({...ue,[V.value]:se.target.checked}))}),s.jsx("span",{className:"cfg-ssh-name",children:kt(V.value)})," ",V.meta&&s.jsx("span",{className:"muted cfg-ssh-meta",children:V.meta}),V.locked&&s.jsx("span",{className:"cfg-ssh-badge",children:"from global"})]},V.value))]}),s.jsxs("div",{className:"cfg-ssh-extra-add",children:[s.jsx("input",{placeholder:"other key path (~/.ssh/... or /abs/path)",value:he,onChange:V=>Ce(V.target.value)}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>{const V=he.trim();V&&(ie(se=>({...se,[V]:!0})),Ce(""))},children:"+ add path"})]}),s.jsxs("div",{className:"muted cfg-note",children:["will load: ",[...Oi].join(", ")||"no keys — no ssh-agent is mounted"]}),s.jsxs("div",{className:"cfg-ssh-load",children:[s.jsx(fg,{status:ae,onRestart:()=>Lt(Te())})," ",s.jsx("button",{className:"cfg-btn",onClick:async()=>{await je(Dt(e,"/sshkeys/select"),{ssh_keys:Se()}).catch(()=>{}),g.current=V=>{te(),V&&r&&!r.container_up&&(h({text:"keys loaded — starting project…",err:!1}),je(Dt(e,"/start")).catch(()=>{}))},f(!0)},children:"Load keys…"})]})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn cfg-btn-danger",disabled:u,onClick:pe,children:u?"restarting…":"Restart project now"}),s.jsx("span",{className:"muted",children:" — interrupts the running session in this project"})]})]}),y&&s.jsx("div",{className:"cfg-modal",style:{display:"block"},children:s.jsxs("div",{className:"cfg-modal-box",children:[s.jsx("h3",{children:"Review changes"}),s.jsx("table",{className:"cfg-diff",children:s.jsx("tbody",{children:y.map((V,se)=>s.jsxs("tr",{children:[s.jsx("td",{className:"cfg-diff-field",children:V.field}),s.jsx("td",{children:V.change})]},se))})}),s.jsxs("div",{className:"cfg-modal-actions",children:[s.jsx("button",{className:"cfg-btn",onClick:bt,children:"Confirm & apply"}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>o(null),children:"Cancel"})]})]})}),m&&s.jsx(nn,{projectId:e,onDone:V=>{f(!1);const se=g.current;g.current=()=>{},se(V)}})]}):s.jsx("p",{className:"muted",children:"loading config…"})}function dg({value:e,onChange:t,onPersist:r}){const[n,i]=C.useState(""),h=e.split(` +`))||j.length>0||Object.keys(k).length>0||L!==r.proxy_enabled||P!==r.passthrough_firewall||U!==r.dind_enabled||Ie(q)!==Ie((r.dind_ports||[]).join(` +`))||W!==(((fl=r.dind_cache)==null?void 0:fl.name)||"")||!!W&&z!==(((pl=r.dind_cache)==null?void 0:pl.mode)==="shared"?"shared":"copy")||R!==r.launch_tmux||M!==(r.seccomp_mode||"")),Y=C.useRef(Le);Y.current=Le,C.useEffect(()=>{t&&(Y.current||nt())},[t]),C.useEffect(()=>{const G=()=>{document.visibilityState!=="hidden"&&!Y.current&&nt()};return window.addEventListener("focus",G),document.addEventListener("visibilitychange",G),()=>{window.removeEventListener("focus",G),document.removeEventListener("visibilitychange",G)}},[nt]),C.useEffect(()=>{ee(Dt(e,"/sshkeys/available")).then(G=>Q(G.keys||[])).catch(()=>{})},[e]);const te=C.useCallback(()=>{ee(Dt(e,"/sshkeys/status")).then(dt).catch(()=>dt(null))},[e]);C.useEffect(()=>te(),[te]);const Se=C.useCallback(()=>{const G=new Set(((r==null?void 0:r.ssh_keys_global)||[]).map(kt));return Object.keys(re).filter(se=>re[se]&&!G.has(kt(se)))},[re,r]);function Ut(){const G={};G.allowed_hosts=wt(w),G.mitm_preset=v,v==="custom"&&(G.monitor_hosts=wt(c)),G.mitm_ports=wt(l),j.length&&(G.set_creds=j.slice());const se=Object.keys(k).filter(ue=>k[ue]);return se.length&&(G.unset_creds=se),G}function Te(){return{proxy_enabled:L,passthrough_firewall:P,dind_enabled:U,dind_ports:wt(q),dind_cache:W?{name:W,mode:z}:null,launch_tmux:R,seccomp_mode:M,ssh_keys:Se()}}async function Rs(){const G=Ut();try{const ue=(await oe(Dt(e,"/config/diff"),G)).entries||[];if(!ue.length){h({text:"no changes",err:!1});return}o(ue)}catch(se){h({text:`diff failed: ${se.message}`,err:!0})}}async function bt(){const G=Ut();try{const se=await oe(Dt(e,"/config/apply"),G);o(null),nt((se.results||[]).join(" • ")||"✓ applied")}catch(se){o(null),h({text:`apply failed: ${se.message}`,err:!0})}}const Lt=C.useCallback(async G=>{d(!0);try{const se=await je(Dt(e,"/config/restart"),G),ue=await se.json().catch(()=>({}));if(se.status===409&&(ue!=null&&ue.ssh_keys_pending)){h({text:"load SSH keys to continue the restart…",err:!1}),d(!1),g.current=()=>{h({text:"keys loaded — restarting…",err:!1}),Lt(G)},f(!0);return}if(se.status>=400)throw new Error((ue==null?void 0:ue.error)||`HTTP ${se.status}`);h({text:((ue==null?void 0:ue.results)||[]).join(" • "),err:!1})}catch(se){h({text:`restart failed: ${se.message}`,err:!0})}finally{d(!1)}},[e]);function pe(){window.confirm("Restart this project now? This kills the container and any running session in it.")&&Lt(Te())}const[Ls,ln]=C.useState(!1);async function Fd(){const G=V.trim();if(!/^[a-zA-Z0-9_-]{1,64}$/.test(G)){h({text:"cache name: letters, digits, dashes, underscores (max 64)",err:!0});return}ln(!0),h({text:`saving cache “${G}” — copying the DinD volume, this can take a while…`,err:!1});try{await oe("/api/dind/caches",{name:G,project:e}),H(""),h({text:`✓ saved cache “${G}”`,err:!1}),ft()}catch(se){h({text:`save cache failed: ${se.message}`,err:!0})}finally{ln(!1)}}async function Ud(G,se){const ue=`repo-${G}`;if(!(se&&!window.confirm(`Update the repo baseline “${ue}” to this project's current inner-docker data? New projects from this repo will start from it.`))){ln(!0),h({text:`saving repo baseline “${ue}” — copying the DinD volume, this can take a while…`,err:!1});try{se&&await St(`/api/dind/caches/${encodeURIComponent(ue)}`),await oe("/api/dind/caches",{name:ue,project:e}),h({text:`✓ saved repo baseline “${ue}” — new projects from this repo will reuse it`,err:!1}),ft()}catch(Ds){h({text:`save repo cache failed: ${Ds.message}`,err:!0})}finally{ln(!1)}}}async function zd(G){if(window.confirm(`Delete DinD cache “${G}”? Projects still set to use it will fail to start until you re-point them.`))try{await St(`/api/dind/caches/${encodeURIComponent(G)}`),W===G&&F(""),h({text:`✓ deleted cache “${G}”`,err:!1}),ft()}catch(se){h({text:`delete cache failed: ${se.message}`,err:!0})}}function Wd(){const G=N.host.trim().toLowerCase(),se=N.name.trim();if(!G||!se||!N.value){h({text:"credential needs host, name, and value",err:!0});return}b(ue=>[...ue,{host:G,kind:N.kind,name:se,value:N.value}]),E({host:"",kind:"header",name:"",value:""}),h({text:"credential queued — click Review changes to apply",err:!1})}const Kd=new Set(((r==null?void 0:r.ssh_keys_global)||[]).map(kt)),hl=J.map(G=>{const se=Kd.has(kt(G.name));return{value:G.name,locked:se,checked:se||!!re[G.name],meta:G.comment||G.type}}),Vd=new Set(hl.map(G=>kt(G.value))),qd=((r==null?void 0:r.ssh_keys)||[]).filter(G=>!Vd.has(kt(G))).map(G=>({value:G,locked:!1,checked:!0,meta:"custom path"})),dl=[...hl,...qd],Oi=new Set;return((r==null?void 0:r.ssh_keys_global)||[]).forEach(G=>Oi.add(kt(G))),Se().forEach(G=>Oi.add(kt(G))),r?s.jsxs("div",{id:"config-root",children:[s.jsx("p",{className:"cfg-status",children:r.container_up?s.jsx("span",{className:"s-2xx",children:"container running — live changes apply immediately"}):s.jsx("span",{className:"muted",children:"container not running — live changes save for next start"})}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Live ",s.jsx("span",{className:"muted",children:"— hot-reloaded, no restart"})]}),s.jsx(Xe,{label:"Allowed hosts",children:s.jsx("textarea",{className:"cfg-edit",rows:Math.max(2,w.split(` +`).length+1),spellCheck:!1,value:w,onChange:G=>S(G.target.value)})}),s.jsxs(Xe,{label:"Capture (mitm)",children:[s.jsxs("select",{className:"cfg-select",value:v,onChange:G=>p(G.target.value),children:[s.jsx("option",{value:"minimal",children:"Minimal — Claude + GitHub only"}),s.jsx("option",{value:"all",children:"All — every allowed host"}),s.jsx("option",{value:"none",children:"None — decrypt nothing"}),s.jsx("option",{value:"custom",children:"Custom — the host list below"})]}),v==="custom"&&s.jsxs("div",{children:[s.jsx(dg,{value:c,onChange:a,onPersist:async G=>{a(G.join(` +`));try{const se=await oe(Dt(e,"/config/apply"),{mitm_preset:"custom",monitor_hosts:G});h({text:(se.results||[]).join(" • ")||"✓ monitor list updated",err:!1})}catch(se){h({text:`apply failed: ${se.message}`,err:!0})}}}),s.jsx("div",{className:"muted cfg-note",children:"only these hosts are decrypted; others allowed+logged but direct-dialed. Hosts with an injected credential are always decrypted regardless (required for credential injection) and aren't listed here."})]}),s.jsxs("div",{className:"cfg-warn",children:[s.jsx("strong",{children:"⚠ Monitoring a host makes the proxy present its own CA."})," Clients that pin certificates or statically link their TLS with a bundled root store won’t trust it — the handshake fails and the request never completes (so a broken host won’t even appear in the Mitm tab). If a host breaks when monitored, remove it here; it falls back to direct-dial (undecrypted) and works again."]})]}),s.jsxs(Xe,{label:"Mitm ports",children:[s.jsx("textarea",{className:"cfg-edit",rows:Math.max(2,l.split(` +`).length+1),spellCheck:!1,value:l,onChange:G=>_(G.target.value)}),s.jsx("div",{className:"muted cfg-note",children:"other ports (ssh, socks, git-over-ssh) are direct-dialed"})]}),s.jsxs(Xe,{label:"Credentials",children:[s.jsx("table",{className:"cfg-creds",children:s.jsxs("tbody",{children:[(r.credentials||[]).map(G=>s.jsxs("tr",{style:{opacity:k[G.host]?.4:1},children:[s.jsx("td",{children:G.host}),s.jsxs("td",{children:[G.kind,": ",G.name]}),s.jsx("td",{className:"muted",children:G.masked}),s.jsx("td",{children:s.jsx("button",{className:"cfg-cred-rm",onClick:()=>{x(se=>({...se,[G.host]:!0})),h({text:`credential ${G.host} queued for removal — Review to apply`,err:!1})},children:"remove"})})]},G.host)),j.map((G,se)=>s.jsxs("tr",{children:[s.jsx("td",{children:G.host}),s.jsxs("td",{children:[G.kind,": ",G.name]}),s.jsx("td",{className:"s-2xx",children:"pending"}),s.jsx("td",{})]},`new-${se}`))]})}),s.jsxs("div",{className:"cfg-cred-add",children:[s.jsx("input",{placeholder:"host (api.foo.com)",value:N.host,onChange:G=>E({...N,host:G.target.value})}),s.jsxs("select",{value:N.kind,onChange:G=>E({...N,kind:G.target.value}),children:[s.jsx("option",{value:"header",children:"header"}),s.jsx("option",{value:"url_param",children:"url_param"})]}),s.jsx("input",{placeholder:"name (X-API-Key)",value:N.name,onChange:G=>E({...N,name:G.target.value})}),s.jsx("input",{placeholder:"value (secret)",type:"password",value:N.value,onChange:G=>E({...N,value:G.target.value})}),s.jsx("button",{className:"cfg-btn",onClick:Wd,children:"Add credential"})]})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn",onClick:Rs,children:"Review changes"}),i&&s.jsx("span",{className:`cfg-msg ${i.err?"s-4xx":"s-2xx"}`,children:i.text})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Restart required ",s.jsx("span",{className:"muted",children:"— needs a project restart"})]}),s.jsx(Xe,{label:"Workspace",children:s.jsx("code",{children:r.workspace})}),s.jsxs(Xe,{label:"Network protection",children:[s.jsx(En,{checked:L,onChange:T}),s.jsx("div",{className:"muted cfg-note",children:"On: traffic goes through the proxy — MITM inspection, credential injection, and the allowlist firewall. Off: fully open network (no proxy, no firewall)."})]}),s.jsxs(Xe,{label:"Passthrough firewall",children:[s.jsx(En,{checked:P,onChange:B}),s.jsxs("div",{className:"muted cfg-note",children:["Keeps the proxy on (inspection + credentials) but ALLOWS + logs unknown domains instead of blocking, and permits direct TCP so ",s.jsx("code",{children:"git"})," over SSH works. Needs Network protection on."]})]}),s.jsx(Xe,{label:"Docker-in-Docker",children:s.jsx(En,{checked:U,onChange:K})}),s.jsx(Xe,{label:"Published ports",children:s.jsx("textarea",{className:"cfg-edit",rows:Math.max(2,q.split(` +`).length+1),spellCheck:!1,value:q,onChange:G=>$(G.target.value)})}),U&&s.jsx(Xe,{label:"Start from cache",children:s.jsxs("div",{className:"cfg-cache",children:[s.jsxs("div",{className:"cfg-cache-row",children:[s.jsxs("select",{className:"cfg-select",value:W,onChange:G=>F(G.target.value),children:[s.jsx("option",{value:"",children:"None — fresh, empty inner docker"}),I.map(G=>s.jsxs("option",{value:G.name,children:[G.name," (",Oc(G.bytes),")"]},G.name))]}),W&&s.jsxs("select",{className:"cfg-select",value:z,onChange:G=>X(G.target.value==="shared"?"shared":"copy"),children:[s.jsx("option",{value:"copy",children:"Copy — throwaway (cache untouched)"}),s.jsx("option",{value:"shared",children:"Shared — changes persist to the cache"})]})]}),s.jsxs("div",{className:"muted cfg-note",children:["A cache is a prebuilt inner-docker data root (images + volumes) so a project doesn't rebuild/re-seed each time. ",s.jsx("b",{children:"Copy"})," seeds a fresh per-project volume from the cache on first start; ",s.jsx("b",{children:"Shared"})," mounts the cache directly so a migration writes back. Changing this needs a restart."]}),(r==null?void 0:r.repo_id)&&(()=>{const G=r.repo_id,se=`repo-${G}`,ue=I.some(Ds=>Ds.name===se);return s.jsxs("div",{className:"cfg-repo-cache",children:[s.jsxs("div",{className:"cfg-repo-cache-head",children:[s.jsx("b",{children:"Repo baseline"}),s.jsx("code",{children:se}),ue?s.jsx("span",{className:"cfg-repo-cache-badge on",children:"saved · reused by new projects from this repo"}):s.jsx("span",{className:"cfg-repo-cache-badge",children:"not saved yet"})]}),s.jsx("div",{className:"muted cfg-note",children:"Save this project's built images + seeded volumes as the shared baseline for this repo. New projects created from the same repo auto-start from it (copy mode) instead of building from an empty inner docker."}),s.jsx("button",{className:"cfg-btn",disabled:Ls,onClick:()=>Ud(G,ue),children:Ls?"Saving…":ue?"Update repo baseline":"Save as repo baseline"})]})})(),s.jsxs("div",{className:"cfg-cache-save",children:[s.jsx("input",{className:"cfg-edit cfg-cache-name",placeholder:"new-cache-name",value:V,spellCheck:!1,onChange:G=>H(G.target.value)}),s.jsx("button",{className:"cfg-btn",disabled:Ls||!V.trim(),onClick:Fd,children:Ls?"Saving…":"Save current data as cache"})]}),s.jsx("div",{className:"muted cfg-note",children:"Snapshots this project's current inner-docker data (built images + seeded volumes) into a reusable cache. Full copy — can take a while for large data roots."}),I.length>0&&s.jsx("ul",{className:"cfg-cache-list",children:I.map(G=>s.jsxs("li",{children:[s.jsx("code",{children:G.name})," ",s.jsx("span",{className:"muted",children:Oc(G.bytes)}),s.jsx("button",{className:"cfg-cache-del",title:"Delete cache",onClick:()=>zd(G.name),children:"×"})]},G.name))})]})}),s.jsx(Xe,{label:"Launch tmux",children:s.jsx(En,{checked:R,onChange:A})}),s.jsxs(Xe,{label:"Seccomp",children:[s.jsxs("select",{className:"cfg-select",value:M,onChange:G=>O(G.target.value),children:[s.jsx("option",{value:"",children:"Default (Docker profile)"}),s.jsx("option",{value:"unconfined",children:"Unconfined — no filtering"})]}),s.jsx("div",{className:"muted cfg-note",children:"unconfined allows syscalls the default profile blocks (e.g. Erlang/BEAM). No effect with Docker-in-Docker (already privileged)."})]}),s.jsxs(Xe,{label:"SSH keys",children:[s.jsxs("div",{className:"cfg-ssh-list",children:[dl.length===0&&s.jsx("div",{className:"muted cfg-note",children:"no keys found under ~/.ssh"}),dl.map(G=>s.jsxs("label",{className:`cfg-ssh-item${G.locked?" locked":""}`,children:[s.jsx("input",{type:"checkbox",className:"cfg-ssh-key",checked:G.locked?!0:!!re[G.value],disabled:G.locked,onChange:se=>ie(ue=>({...ue,[G.value]:se.target.checked}))}),s.jsx("span",{className:"cfg-ssh-name",children:kt(G.value)})," ",G.meta&&s.jsx("span",{className:"muted cfg-ssh-meta",children:G.meta}),G.locked&&s.jsx("span",{className:"cfg-ssh-badge",children:"from global"})]},G.value))]}),s.jsxs("div",{className:"cfg-ssh-extra-add",children:[s.jsx("input",{placeholder:"other key path (~/.ssh/... or /abs/path)",value:he,onChange:G=>Ce(G.target.value)}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>{const G=he.trim();G&&(ie(se=>({...se,[G]:!0})),Ce(""))},children:"+ add path"})]}),s.jsxs("div",{className:"muted cfg-note",children:["will load: ",[...Oi].join(", ")||"no keys — no ssh-agent is mounted"]}),s.jsxs("div",{className:"cfg-ssh-load",children:[s.jsx(fg,{status:ae,onRestart:()=>Lt(Te())})," ",s.jsx("button",{className:"cfg-btn",onClick:async()=>{await je(Dt(e,"/sshkeys/select"),{ssh_keys:Se()}).catch(()=>{}),g.current=G=>{te(),G&&r&&!r.container_up&&(h({text:"keys loaded — starting project…",err:!1}),je(Dt(e,"/start")).catch(()=>{}))},f(!0)},children:"Load keys…"})]})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn cfg-btn-danger",disabled:u,onClick:pe,children:u?"restarting…":"Restart project now"}),s.jsx("span",{className:"muted",children:" — interrupts the running session in this project"})]})]}),y&&s.jsx("div",{className:"cfg-modal",style:{display:"block"},children:s.jsxs("div",{className:"cfg-modal-box",children:[s.jsx("h3",{children:"Review changes"}),s.jsx("table",{className:"cfg-diff",children:s.jsx("tbody",{children:y.map((G,se)=>s.jsxs("tr",{children:[s.jsx("td",{className:"cfg-diff-field",children:G.field}),s.jsx("td",{children:G.change})]},se))})}),s.jsxs("div",{className:"cfg-modal-actions",children:[s.jsx("button",{className:"cfg-btn",onClick:bt,children:"Confirm & apply"}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>o(null),children:"Cancel"})]})]})}),m&&s.jsx(nn,{projectId:e,onDone:G=>{f(!1);const se=g.current;g.current=()=>{},se(G)}})]}):s.jsx("p",{className:"muted",children:"loading config…"})}function dg({value:e,onChange:t,onPersist:r}){const[n,i]=C.useState(""),h=e.split(` `).map(d=>d.trim()).filter(Boolean),y=d=>{const m=new Set,f=[];for(const g of d){const w=g.toLowerCase();g&&!m.has(w)&&(m.add(w),f.push(g))}t(f.join(` -`)),r(f)},o=()=>{const d=n.split(/[\s,]+/).map(m=>m.trim()).filter(Boolean);d.length&&(y([...h,...d]),i(""))},u=d=>y(h.filter(m=>m!==d));return s.jsxs("div",{className:"monitor-list",children:[h.length===0?s.jsx("div",{className:"muted cfg-note",style:{marginBottom:6},children:"nothing monitored yet — every allowed host is direct-dialed (undecrypted). Add a host to decrypt it."}):s.jsx("div",{className:"monitor-chips",children:h.map(d=>s.jsxs("span",{className:"monitor-chip",children:[s.jsx("span",{className:"monitor-chip-host",children:d}),s.jsx("button",{type:"button",className:"monitor-chip-x",title:`Stop monitoring ${d}`,onClick:()=>u(d),children:"✕"})]},d))}),s.jsxs("div",{className:"monitor-add",children:[s.jsx("input",{type:"text",placeholder:"add a host (api.example.com)",autoComplete:"off",spellCheck:!1,value:n,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),o())}}),s.jsx("button",{type:"button",className:"cfg-btn cfg-btn-ghost",onClick:o,children:"+ add"})]})]})}function Xe({label:e,children:t}){return s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:e}),s.jsx("div",{className:"cfg-value",children:t})]})}function En({checked:e,onChange:t}){return s.jsxs("label",{className:"cfg-inline",children:[s.jsx("input",{type:"checkbox",checked:e,onChange:r=>t(r.target.checked)})," ",s.jsx("span",{className:"cfg-slider"})]})}function fg({status:e,onRestart:t}){return e?e.configured?e.container_stale?s.jsxs("span",{className:"attention",children:["⚠ keys loaded on host, but the running container can't reach them — restart it to use SSH."," ",s.jsx("button",{className:"cfg-btn cfg-btn-danger",onClick:t,children:"Restart container"})]}):e.loaded?s.jsxs("span",{className:"s-2xx",children:["✓ ",e.count," key(s) loaded — start won't prompt"]}):s.jsx("span",{className:"muted",children:"not loaded — start will need passphrases"}):s.jsx("span",{className:"muted",children:"no keys configured"}):s.jsx("span",{className:"muted",children:"checking…"})}const Mc="corral.monitorWarnAck";function Ts(e,t){return`/p/${e}${t}`}function Od(e){return e==null||e<0?"":e<1024?`${e}b`:e<1024*1024?`${(e/1024).toFixed(1)}kb`:`${(e/(1024*1024)).toFixed(1)}mb`}function ho(e){return(e<10?"0":"")+e}function Ic(e){if(!e)return"";const t=new Date(e*1e3);return`${ho(t.getHours())}:${ho(t.getMinutes())}:${ho(t.getSeconds())}`}function pg(e){const t=e.match(/(\d\d):(\d\d):(\d\d)/);return t?`${t[1]}:${t[2]}:${t[3]}`:e}function mg(e){return e?e>=500?"s-5xx":e>=400?"s-4xx":e>=300?"s-3xx":"s-2xx":"s-pending"}function gg(e){var r;const t=e.response;return!t||!t.timestamp_end||!((r=e.request)!=null&&r.timestamp_start)?"":`${Math.round((t.timestamp_end-e.request.timestamp_start)*1e3)}ms`}function vg(e){for(const t of(e==null?void 0:e.headers)||[])if(t[0].toLowerCase()==="content-type")return t[1];return""}const _g=512*1024,Bc=6,$c=700;function yg({projectId:e,flowId:t,side:r,msg:n}){const[i,h]=C.useState({status:"loading",text:""});return C.useEffect(()=>{let y=!0;if((n==null?void 0:n.contentLength)===0){h({status:"ready",text:"(empty)"});return}h(m=>m.status==="ready"?m:{status:"loading",text:""});let o;const u=()=>r==="response"&&!(n!=null&&n.timestamp_end),d=m=>{Nm(Ts(e,`/mitm/flows/${t}/${r}/content`)).then(f=>{if(!y)return;if(f.length>_g){h({status:"ready",text:`body too large to display (${Od(f.length)})`});return}if(f===""&&u()&&my&&d(m+1),$c);return}let g=f;if(vg(n).toLowerCase().includes("json"))try{g=JSON.stringify(JSON.parse(f),null,2)}catch{}h({status:"ready",text:g||"(empty)"})}).catch(f=>{if(y){if(my&&d(m+1),$c);return}h({status:"error",text:`couldn't load body: ${f.message}`})}})};return d(0),()=>{y=!1,o&&window.clearTimeout(o)}},[e,t,r,n]),i.status==="loading"?s.jsxs("div",{className:"mitm-body mitm-body-loading",children:[s.jsx("span",{className:"mitm-spinner","aria-hidden":"true"}),"loading body…"]}):s.jsx("pre",{className:`mitm-body${i.status==="error"?" mitm-body-error":""}`,children:i.text})}function xg(){const e=[0,1,2,3,4,5];return s.jsxs("table",{className:"mitm-table mitm-skeleton","aria-hidden":"true",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"When"}),s.jsx("th",{}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Host"}),s.jsx("th",{children:"Path"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Size"}),s.jsx("th",{children:"Dur"})]})}),s.jsx("tbody",{children:e.map(t=>s.jsxs("tr",{className:"m-row",children:[s.jsx("td",{className:"m-when",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-caret"}),s.jsx("td",{className:"m-method",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-host",children:s.jsx("span",{className:"sk sk-cell",style:{width:"80%"}})}),s.jsx("td",{className:"m-path",children:s.jsx("span",{className:"sk sk-cell",style:{width:`${55+t*13%40}%`}})}),s.jsx("td",{className:"m-status",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-size",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-dur",children:s.jsx("span",{className:"sk sk-cell"})})]},t))})]})}function Sg({headers:e}){return!e||!e.length?s.jsx("div",{className:"mitm-empty",children:"(none)"}):s.jsx("table",{className:"mitm-headers",children:s.jsx("tbody",{children:e.map((t,r)=>s.jsxs("tr",{children:[s.jsx("td",{children:t[0]}),s.jsx("td",{children:t[1]})]},r))})})}function wg({projectId:e,flowId:t,req:r,resp:n}){const[i,h]=C.useState("response"),y=i==="request"?r:n;return s.jsxs("div",{className:"mitm-detail",children:[s.jsxs("div",{className:"mitm-tabs",children:[s.jsx("button",{type:"button",className:`mitm-tab${i==="request"?" active":""}`,onClick:()=>h("request"),children:"Request"}),s.jsx("button",{type:"button",className:`mitm-tab${i==="response"?" active":""}`,onClick:()=>h("response"),children:"Response"})]}),s.jsx("div",{className:"mitm-sec",children:"Headers"}),s.jsx(Sg,{headers:y.headers}),s.jsx("div",{className:"mitm-sec",children:"Body"}),s.jsx(yg,{projectId:e,flowId:t,side:i,msg:y})]})}function bg({projectId:e,mitmUp:t}){var M,P,U,Y,H,J;const[r,n]=C.useState([]),[i,h]=C.useState([]),[y,o]=C.useState(""),[u,d]=C.useState(""),[m,f]=C.useState({}),[g,w]=C.useState("loading flows…"),[S,v]=C.useState(!1),[p,c]=C.useState(!1),[a,l]=C.useState({}),[_,j]=C.useState(new Set),b=C.useRef(!0),[k,x]=C.useState(null),[N,E]=C.useState(!1),[L,T]=C.useState(()=>{try{return localStorage.getItem(Mc)==="1"}catch{return!1}}),O=I=>{T(I);try{localStorage.setItem(Mc,I?"1":"0")}catch{}};C.useEffect(()=>{const I=window.setTimeout(()=>d(y.trim()),250);return()=>window.clearTimeout(I)},[y]);const B=C.useCallback(async()=>{try{const I=await ee(Ts(e,"/mitm/flows"));n(I),w(`${I.length} flow${I.length===1?"":"s"}`),v(!1)}catch(I){w(`mitm unavailable: ${I.message}`),v(!0)}try{const I=u?`?q=${encodeURIComponent(u)}`:"",A=await ee(Ts(e,`/mitm/direct${I}`));h(A.direct||[])}catch{}c(!0)},[e,u]);C.useEffect(()=>{if(!t)return;B();const I=window.setInterval(()=>b.current&&B(),2e3);return()=>window.clearInterval(I)},[t,B]);const F=C.useCallback(async()=>{try{const I=await ee(Ts(e,"/config"));j(new Set((I.monitor_hosts||[]).map(A=>A.toLowerCase())))}catch{}},[e]);C.useEffect(()=>{if(!t)return;F();const I=window.setInterval(()=>b.current&&F(),3e3),A=()=>F();return window.addEventListener("focus",A),()=>{window.clearInterval(I),window.removeEventListener("focus",A)}},[t,F]);const z=C.useCallback(async I=>{const A=I.split(":")[0];l(q=>({...q,[I]:"busy"}));try{const q=await ee(Ts(e,"/config")),W=new Set(q.monitor_hosts||[]);W.add(A),await oe(Ts(e,"/config/apply"),{mitm_preset:"custom",monitor_hosts:[...W]}),l(X=>({...X,[I]:"done"})),F()}catch(q){l(W=>{const X={...W};return delete X[I],X}),alert(`couldn't start monitoring ${A}: ${q.message}`)}},[e]),K=C.useCallback(I=>{if(L){z(I);return}E(!1),x(I)},[L,z]);if(!t)return s.jsx("p",{className:"empty",children:"Credential proxy isn't running for this project."});const $=y.trim().toLowerCase().split(/\s+/).filter(Boolean),R=[];for(const I of r){const A=[(M=I.request)==null?void 0:M.method,((P=I.request)==null?void 0:P.pretty_host)||((U=I.request)==null?void 0:U.host),(Y=I.request)==null?void 0:Y.path,(H=I.response)==null?void 0:H.status_code].join(" ").toLowerCase();$.length&&!$.every(q=>A.includes(q))||R.push({kind:"flow",ts:((J=I.request)==null?void 0:J.timestamp_start)||I.timestamp_created||0,flow:I})}i.forEach((I,A)=>{R.push({kind:"direct",ts:I.ts,host:I.host,when:I.when,key:`${I.host}|${I.when}|${A}`})}),R.sort((I,A)=>A.ts-I.ts);const D=R;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mitm-toolbar",children:[s.jsx("input",{type:"text",placeholder:"filter: host, path, method, status…",autoComplete:"off",spellCheck:!1,value:y,onChange:I=>o(I.target.value)}),s.jsx("span",{className:S?"s-4xx":"muted",children:g})]}),s.jsxs("p",{className:"muted cfg-note",style:{padding:"0 0.5rem 0.5rem"},children:["Decrypted flows (monitored hosts) and individual direct-dialed requests are interleaved by time. Direct rows are dimmed with a “not decrypted” badge — their TLS isn’t intercepted, so contents aren’t available; click ",s.jsx("em",{children:"Monitor"})," to decrypt future requests to that host (the already-completed one can’t be retroactively decrypted). Filtering by host searches the full proxy-log history for direct requests; decrypted flows filter over mitmweb’s current set."]}),s.jsxs("div",{id:"mitm-flows",children:[!p&&s.jsx(xg,{}),p&&R.length===0&&s.jsx("p",{className:"empty",children:"No traffic captured yet."}),p&&R.length>0&&D.length===0&&s.jsxs("p",{className:"empty",children:["No flows match “",y,"”."]}),p&&D.length>0&&s.jsxs("table",{className:"mitm-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"When"}),s.jsx("th",{}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Host"}),s.jsx("th",{children:"Path"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Size"}),s.jsx("th",{children:"Dur"})]})}),s.jsx("tbody",{children:D.map(I=>{if(I.kind==="direct"){const ie=a[I.host],he=_.has(I.host.split(":")[0].toLowerCase());return s.jsxs("tr",{className:"m-row m-direct",style:{opacity:.62},children:[s.jsx("td",{className:"m-when",children:I.ts?Ic(I.ts):pg(I.when)}),s.jsx("td",{className:"m-caret"}),s.jsx("td",{className:"m-method",children:"—"}),s.jsx("td",{className:"m-host",children:s.jsx("div",{className:"cell-scroll",children:I.host})}),s.jsx("td",{className:"m-path",children:s.jsx("span",{className:"cfg-ssh-badge",children:"not decrypted"})}),s.jsx("td",{className:"m-status",children:"—"}),s.jsx("td",{className:"m-size",children:"—"}),s.jsx("td",{className:"m-dur",children:he?s.jsx("span",{className:"s-2xx",title:"This host is now monitored — this was an earlier direct-dialed request; newer ones are decrypted",children:"now monitored"}):s.jsx("button",{className:"cfg-btn cfg-btn-ghost",disabled:ie==="busy",title:"Decrypt future requests to this host",onClick:()=>K(I.host),children:ie==="busy"?"…":"Monitor"})})]},I.key)}const A=I.flow,q=A.request||{},W=A.response||{},X=W.status_code||0,Q=W.contentLength!=null?W.contentLength:q.contentLength,re=!!m[A.id];return s.jsxs(C.Fragment,{children:[s.jsxs("tr",{className:"m-row",onClick:()=>f(ie=>({...ie,[A.id]:!ie[A.id]})),children:[s.jsx("td",{className:"m-when",children:Ic(q.timestamp_start||A.timestamp_created)}),s.jsx("td",{className:"m-caret",children:re?"▾":"▸"}),s.jsx("td",{className:"m-method",children:q.method||""}),s.jsx("td",{className:"m-host",children:s.jsx("div",{className:"cell-scroll",children:q.pretty_host||q.host||""})}),s.jsx("td",{className:"m-path",title:q.path||"",children:s.jsx("div",{className:"cell-scroll",children:q.path||""})}),s.jsx("td",{className:`m-status ${mg(X)}`,children:X||"…"}),s.jsx("td",{className:"m-size",children:Od(Q)}),s.jsx("td",{className:"m-dur",children:gg(A)})]}),re&&s.jsx("tr",{className:"m-detailrow",children:s.jsx("td",{colSpan:8,children:s.jsx(wg,{projectId:e,flowId:A.id,req:q,resp:W})})})]},A.id)})})]})]}),k&&s.jsxs(hr,{title:"Monitor this host?",onClose:()=>x(null),children:[s.jsxs("p",{className:"mitm-tldr",children:[s.jsx("strong",{children:"TL;DR:"})," this will most likely just work. If requests to this host stop showing up here after you monitor it, it’s a CA-trust issue — remove it from the monitor list in ",s.jsx("em",{children:"Config → Capture"})," and it goes back to working (undecrypted)."]}),s.jsxs("div",{className:"cfg-warn",style:{marginTop:0},children:[s.jsx("strong",{children:"⚠ Monitoring makes the proxy present its own CA."})," Clients that pin certificates or statically link their TLS with a bundled root store won’t trust it — the handshake fails and the request never completes (so a broken host won’t even appear here). If a host breaks after you monitor it, remove it from the monitor list in ",s.jsx("em",{children:"Config → Capture"}),"; it falls back to direct-dial (undecrypted) and works again."]}),s.jsxs("p",{className:"muted",style:{fontSize:"0.82rem"},children:["Future requests to ",s.jsx("code",{children:k.split(":")[0]})," will be decrypted. The already-completed request can’t be retroactively decrypted."]}),s.jsxs("details",{className:"mitm-readmore",children:[s.jsx("summary",{children:"Read more — how the CA is trusted, and what to do when it isn’t"}),s.jsxs("div",{className:"mitm-readmore-body",children:[s.jsxs("p",{children:["The sandbox already trusts the proxy CA for most tooling: it installs the CA into the system trust store and exports"," ",s.jsx("code",{children:"SSL_CERT_FILE"}),", ",s.jsx("code",{children:"REQUESTS_CA_BUNDLE"}),", ",s.jsx("code",{children:"NODE_EXTRA_CA_CERTS"}),", and"," ",s.jsx("code",{children:"CURL_CA_BUNDLE"})," — so Python, Node, curl, and anything using the OS store or those variables work."]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Docker-in-Docker & docker builds are handled too:"})," a cert-injector daemon adds the CA to every inner container, and builds read it from ",s.jsx("code",{children:"/etc/docker/certs.d//ca.crt"}),"."]}),s.jsxs("p",{children:[s.jsx("strong",{children:"If a runtime has its own trust store,"})," point it at the CA the same way — most respect an env var, e.g."," ",s.jsx("code",{children:"SSL_CERT_FILE"})," / ",s.jsx("code",{children:"SSL_CERT_DIR"})," (Go, OpenSSL), ",s.jsx("code",{children:"NODE_EXTRA_CA_CERTS"})," (Node),"," ",s.jsx("code",{children:"REQUESTS_CA_BUNDLE"})," (Python requests), ",s.jsx("code",{children:"GIT_SSL_CAINFO"})," (git). The CA is at"," ",s.jsx("code",{children:"~/.mitmproxy/mitmproxy-ca-cert.pem"}),"."]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Statically-linked binaries that embed their own root store"})," ignore both the system store and those env vars — there’s no way to make them trust the proxy CA. For those, don’t monitor the host; instead route just that binary’s traffic through an internal proxy of your own that re-terminates and forwards the payloads, or leave it direct-dialed (undecrypted)."]})]})]}),s.jsxs("label",{className:"cfg-inline",style:{margin:"0.6rem 0 0.3rem"},children:[s.jsx("input",{type:"checkbox",checked:N,onChange:I=>E(I.target.checked)})," I understand the consequences"]}),s.jsxs("label",{className:"cfg-inline",style:{margin:"0 0 0.9rem"},children:[s.jsx("input",{type:"checkbox",checked:L,onChange:I=>O(I.target.checked),disabled:!N})," Don’t show this again"]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{className:"btn primary",disabled:!N,onClick:()=>{const I=k;x(null),z(I)},children:"Monitor host"}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>x(null),children:"Cancel"})]})]})]})}function Cg({projectId:e}){const[t,r]=C.useState([]),n=C.useRef(null);return C.useEffect(()=>{const i=new EventSource(`/p/${e}/firewall/stream`);return i.onmessage=h=>r(y=>[...y,h.data]),i.addEventListener("error",()=>r(h=>[...h,"[stream disconnected]"])),()=>i.close()},[e]),C.useEffect(()=>{n.current&&(n.current.scrollTop=n.current.scrollHeight)},[t]),s.jsxs("div",{className:"screen-frame",children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"allowlist proxy · live log"]}),s.jsx("pre",{className:"screen-body",ref:n,children:t.join(` -`)})]})}const kg="allow-scripts allow-forms allow-popups allow-modals allow-same-origin";function jg({projectId:e,containerUp:t}){const[r,n]=C.useState([]),[i,h]=C.useState(null),[y,o]=C.useState(""),[u,d]=C.useState(""),[m,f]=C.useState(""),[g,w]=C.useState(0),[S,v]=C.useState(null);C.useEffect(()=>{ee("/api/live-origin").then(v).catch(()=>v(null))},[]);const p=C.useRef(!1),c=C.useCallback(()=>{ee(`/p/${e}/live-ports`).then(k=>{n(k.ports||[]),h(x=>x==null&&!p.current&&k.ports&&k.ports.length?k.ports[0]:x)}).catch(()=>n([]))},[e]),a=C.useCallback(()=>{ee(`/p/${e}/live-port`).then(k=>{if(k.port&&!p.current){h(N=>N==null||N!==k.port?k.port:N);const x=k.path||"";d(N=>N!==x?x:N),f(N=>N===""?x:N)}}).catch(()=>{})},[e]);C.useEffect(()=>{if(!t)return;c(),a();const k=setInterval(a,4e3);return()=>clearInterval(k)},[t,c,a]);const l=k=>{p.current=!0,h(k),w(x=>x+1)},_=()=>{const k=parseInt(y.trim(),10);k>=1&&k<=65535&&l(k)},j=i!=null&&S?`${S.base_url}/p/${e}/live/${i}${u||"/"}?__live_token=${encodeURIComponent(S.token)}`:"",b=()=>{d(m.trim()),w(k=>k+1)};return t?s.jsxs("div",{className:"live-view",children:[s.jsxs("div",{className:"live-hint muted",children:["Pick a port and path above, or ask the ",s.jsx("strong",{children:"Ask Claude"})," host chat (the global one — it can run ",s.jsx("code",{children:"corral api"}),") to start your app and set the Live View port for you."]}),s.jsxs("div",{className:"live-bar",children:[s.jsx("span",{className:"live-label",children:"Port"}),r.map(k=>s.jsx("button",{className:`live-port${k===i?" active":""}`,onClick:()=>l(k),children:k},k)),s.jsx("input",{className:"live-port-input",placeholder:"port",inputMode:"numeric",value:y,onChange:k=>o(k.target.value.replace(/[^0-9]/g,"")),onKeyDown:k=>{k.key==="Enter"&&_()}}),s.jsx("button",{className:"live-btn",onClick:_,disabled:!y.trim(),children:"Go"}),s.jsx("span",{className:"live-label live-path-label",children:"Path"}),s.jsx("input",{className:"live-port-input live-path-input",placeholder:"/",value:m,onChange:k=>f(k.target.value),onKeyDown:k=>{k.key==="Enter"&&b()},title:"Open the app at this path (e.g. /docs/node/)"}),s.jsx("button",{className:"live-btn",onClick:b,title:"Open this path",children:"Go"}),s.jsx("span",{className:"live-spacer"}),s.jsx("button",{className:"live-btn",onClick:c,title:"Re-scan listening ports",children:"⟳ Ports"}),i!=null&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"live-btn",onClick:()=>w(k=>k+1),title:"Reload the view",children:"⟳ Reload"}),s.jsx("a",{className:"live-btn",href:j,target:"_blank",rel:"noreferrer",title:"Open in a new tab",children:"↗ Open"})]})]}),i==null?s.jsxs("div",{className:"live-empty",children:[s.jsx("p",{children:"No port selected."}),r.length===0&&s.jsxs("p",{className:"muted",children:["No listening ports detected. Start your app’s container with"," ",s.jsx("code",{children:"-p 3000:3000"})," (or bind it in the outer container) to view it here, then ⟳ Ports."]})]}):s.jsx("div",{className:"live-frame-wrap",children:s.jsx("iframe",{className:"live-frame",src:j,title:`live view on port ${i}`,sandbox:kg},g)})]}):s.jsxs("div",{className:"live-empty",children:[s.jsx("p",{children:"The project container isn’t running."}),s.jsx("p",{className:"muted",children:"Start the project, then run your app to view it here."})]})}const Ng={"global-chat":"Global chat","project-chat":"Project chat","pr-review-chat":"PR review chat",merge:"Merge",worker:"Worker","issue-draft":"Issue draft","prompt-draft":"Prompt draft","script-draft":"Script draft",analysis:"Analysis","log-analysis":"Log analysis",sandbox:"Sandbox"};function ha(e){return Ng[e]||e}function Md({projectId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(""),[o,u]=C.useState(""),[d,m]=C.useState([]),[f,g]=C.useState(new Set),w=C.useCallback(v=>{g(p=>{const c=new Set(p);return c.has(v)?c.delete(v):c.add(v),c})},[]);C.useEffect(()=>{ee("/api/conversations/facets").then(v=>m(v.origins||[])).catch(()=>{})},[]);const S=C.useCallback(()=>{const v=new URLSearchParams;e&&v.set("project",e),o&&v.set("origin",o),h.trim()&&v.set("q",h.trim()),ee(`/api/conversations?${v.toString()}`).then(p=>{r(p.conversations||[]),i(null)}).catch(p=>i(p.message))},[e,o,h]);return C.useEffect(()=>{const v=setTimeout(S,250);return()=>clearTimeout(v)},[S]),s.jsxs("div",{className:"conv-panel",children:[s.jsxs("div",{className:"conv-toolbar",children:[s.jsx("input",{className:"auto-input conv-search",placeholder:"🔍 search all conversations (messages + tool calls)…",value:h,onChange:v=>y(v.target.value)}),s.jsxs("select",{className:"cfg-select conv-origin",value:o,onChange:v=>u(v.target.value),children:[s.jsx("option",{value:"",children:"All origins"}),d.map(v=>s.jsx("option",{value:v,children:ha(v)},v))]})]}),n&&s.jsxs("p",{className:"tab-note err",children:["Failed to load conversations: ",n]}),t===null?s.jsx("p",{className:"tab-note",children:"Loading conversations…"}):t.length===0?s.jsx("p",{className:"tab-note",children:h.trim()||o?"No conversations match.":"No conversations captured yet. They appear here as Claude works across the app."}):s.jsx("ul",{className:"conv-list",children:t.map(v=>{const p=f.has(v.id);return s.jsxs("li",{className:`conv-row${p?" open":""}`,children:[s.jsxs("button",{type:"button",className:"conv-head","aria-expanded":p,onClick:()=>w(v.id),children:[s.jsx("span",{className:`conv-caret${p?" open":""}`,"aria-hidden":!0,children:"▸"}),s.jsx("span",{className:`conv-origin-chip origin-${v.originKind}`,children:ha(v.originKind)}),s.jsx("span",{className:"conv-title",children:v.title||v.firstPrompt||`Conversation #${v.id}`}),s.jsx(Eg,{status:v.status})]}),s.jsxs("div",{className:"conv-byline",children:[v.projectLabel&&s.jsx("span",{children:v.projectLabel}),v.prNumber?s.jsxs("span",{children:[" · PR #",v.prNumber]}):null,s.jsxs("span",{children:[" · ",v.messageCount," msg"]}),v.model&&s.jsxs("span",{children:[" · ",v.model]}),s.jsxs("span",{children:[" · ",v.createdAt]})]}),p&&s.jsx(Rg,{conv:v})]},v.id)})})]})}function Eg({status:e}){const t=e==="running"||e==="idle"?"running":e==="failed"||e==="interrupted"||e==="canceled"?"err":"done";return s.jsx("span",{className:`conv-status-dot ${t}`,title:e})}function Rg({conv:e}){const[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState(null),[o,u]=C.useState(null),[d,m]=C.useState(!1),[f,g]=C.useState(null),w=()=>{m(v=>!v),o===null&&ee(`/api/conversations/${e.id}/chain`).then(v=>u(v.conversations||[])).catch(v=>y(v.message))},S=()=>{g("Starting analysis…"),oe("/api/conversations/analyze",{conversationId:e.id}).then(()=>{g("Analyzing — see the Work tab (⌘K)"),window.dispatchEvent(new CustomEvent("corral:open-work"))}).catch(v=>g(v.message))};return C.useEffect(()=>{const v=new URLSearchParams;n.trim()&&v.set("q",n.trim());const p=setTimeout(()=>{ee(`/api/conversations/${e.id}/messages?${v.toString()}`).then(c=>{r(c.messages||[]),y(null)}).catch(c=>y(c.message))},200);return()=>clearTimeout(p)},[e.id,n]),s.jsxs("div",{className:"conv-detail",children:[s.jsxs("div",{className:"conv-detail-head",children:[s.jsx("span",{className:"conv-detail-title",children:e.title||`Conversation #${e.id}`}),e.parentConversationId?s.jsxs("span",{className:"conv-chain-hint",title:"This conversation was spawned by another",children:["⤴ from #",e.parentConversationId]}):null]}),s.jsxs("div",{className:"conv-detail-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:w,children:d?"Hide chain":"View chain"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:S,title:"Spawn a Claude to analyze this conversation (runs in the Work tab; itself captured)",children:"✦ Analyze with AI"}),f&&s.jsx("span",{className:"conv-analyze-msg",children:f})]}),d&&s.jsx("div",{className:"conv-chain",children:o===null?s.jsx("p",{className:"tab-note",children:"Loading chain…"}):o.length<=1?s.jsx("p",{className:"tab-note",children:"This conversation isn't linked to any others."}):s.jsx("ul",{className:"conv-chain-list",children:o.map(v=>s.jsxs("li",{className:`conv-chain-item${v.id===e.id?" current":""}`,children:[s.jsx("span",{className:`conv-origin-chip origin-${v.originKind}`,children:ha(v.originKind)}),s.jsx("span",{className:"conv-chain-title",children:v.title||`Conversation #${v.id}`}),v.id===e.id&&s.jsx("span",{className:"conv-chain-you",children:"← this one"}),s.jsxs("span",{className:"conv-chain-count",children:[v.messageCount," msg"]})]},v.id))})}),s.jsx("input",{className:"auto-input conv-search",placeholder:"🔍 search within this conversation…",value:n,onChange:v=>i(v.target.value)}),h&&s.jsx("p",{className:"tab-note err",children:h}),t===null?s.jsx("p",{className:"tab-note",children:"Loading…"}):t.length===0?s.jsx("p",{className:"tab-note",children:n.trim()?"No messages match.":"No messages."}):s.jsx("ul",{className:"conv-msgs",children:t.map(v=>s.jsxs("li",{className:`conv-msg role-${v.role}${v.isError?" err":""}`,children:[s.jsx("span",{className:"conv-msg-role",children:v.role}),v.type==="tool_use"?s.jsxs("span",{className:"conv-msg-tool",children:["🔧 ",s.jsx("b",{children:v.toolName})," ",s.jsx("code",{children:v.toolInput})]}):v.type==="tool_result"?s.jsxs("span",{className:"conv-msg-toolresult",children:["↳ ",v.toolResult]}):s.jsx("span",{className:"conv-msg-text",children:v.text})]},v.id))})]})}function Lg({projectId:e}){return s.jsxs("div",{className:"conv-tab",children:[s.jsx("div",{className:"conv-tab-note muted",children:"Captured Claude conversations for this project — host-side chats and the sandbox's own Claude sessions. Searchable; kept per your retention setting even after the project is removed."}),s.jsx(Md,{projectId:e})]})}const Dg=[{key:"files",label:"Files"},{key:"diff",label:"Diff"},{key:"container",label:"Container"},{key:"liveview",label:"Live View"},{key:"mitm",label:"Mitm Proxy"},{key:"firewall",label:"Firewall Log"},{key:"conversations",label:"Conversations"},{key:"config",label:"Config"}],Ag="corral.dockCollapsed",Tg="corral.chatDock",Pg="corral.dockWidth",Og="corral.hostHeight",Mg="corral.chatWidth",Ig=480,Bg=320,$g=420;function Hg({id:e}){const{projects:t,loaded:r}=xd(4e3),n=C.useMemo(()=>t.find(X=>X.id===e),[t,e]),i=(n==null?void 0:n.name)||e,[h,y]=C.useState(null),[o,u]=C.useState(void 0);C.useEffect(()=>{ee(`/p/${e}/config`).then(X=>{y(X.source||null),u(X.repo_id||void 0)}).catch(()=>{})},[e]);const[d,m]=C.useState(null),[f,g]=C.useState("files"),[w,S]=C.useState({files:!0,diff:!1,container:!1,liveview:!1,mitm:!1,firewall:!1,conversations:!1,config:!1}),[v,p]=C.useState(0),c=X=>{g(X),S(Q=>Q[X]?Q:{...Q,[X]:!0}),X==="config"&&p(Q=>Q+1)},[a,l]=it(Ag,!1),[_,j]=C.useState(!a),[b,k]=it(`corral.hostOpen.${e}`,!1),[x,N]=it(`corral.chatOpen.${e}`,!1),[E,L]=it(Tg,"right"),[T,O]=it(Pg,Ig),[B,F]=it(Og,Bg),[z,K]=it(Mg,$g),$=Qs({axis:"x",edge:"start",get:()=>T,min:240,max:()=>Math.round(window.innerWidth*.8),onResize:O}),R=Qs({axis:"y",edge:"start",get:()=>B,min:120,max:()=>Math.round(window.innerHeight*.85),onResize:F}),D=Qs({axis:"x",edge:E==="right"?"start":"end",get:()=>z,min:300,max:()=>Math.round(window.innerWidth*.8),onResize:K}),M=C.useCallback(()=>{l(X=>{const Q=!X;return Q||j(!0),Q})},[l]),P=C.useCallback(()=>k(X=>!X),[k]),U=C.useCallback(()=>N(X=>!X),[N]),[Y,H]=C.useState(""),[J,I]=C.useState(!1),A=!!(n!=null&&n.container_up);C.useEffect(()=>{ee(`/p/${e}/dind/status`).then(m).catch(()=>m(null))},[e,A]),C.useEffect(()=>{if(!Y)return;A===(Y==="starting")&&H("")},[A,Y]);const q=C.useCallback(async(X=!1)=>{const Q=X?!1:A;H(Q?"stopping":"starting");try{const re=await je(`/p/${e}/${Q?"stop":"start"}`),ie=await re.json().catch(()=>({}));if(!Q&&re.status===409&&(ie!=null&&ie.ssh_keys_pending)){H(""),I(!0);return}if(re.status>=400)throw new Error((ie==null?void 0:ie.message)||`HTTP ${re.status}`)}catch(re){H(""),alert(`${Q?"stop":"start"} failed: ${re.message}`)}},[e,A]);C.useEffect(()=>{const X=()=>{const re=document.activeElement;if(!re)return!1;const ie=(re.tagName||"").toLowerCase();return ie==="input"||ie==="textarea"||re.isContentEditable||re.classList.contains("xterm-helper-textarea")},Q=re=>{if(!(re.metaKey||re.ctrlKey)||re.altKey||X())return;const ie=(re.key||"").toLowerCase();ie==="j"?(re.preventDefault(),P()):ie==="k"?(re.preventDefault(),U()):ie===";"&&(re.preventDefault(),M())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[P,U,M]);const W=()=>L(X=>X==="left"?"right":"left");return s.jsxs("div",{className:"project-page",children:[s.jsxs("header",{children:[s.jsx(be,{to:"/",className:"back",children:"← All projects"}),s.jsx("h1",{children:i}),h&&h.kind==="pr"&&h.repo_id&&s.jsxs("a",{className:"proj-source-link",href:`/repos/${encodeURIComponent(h.repo_id)}/prs/${h.number}`,title:h.title||`PR #${h.number}`,children:["↩ from PR #",h.number]}),s.jsx("button",{className:`dock-toggle power-toggle${A?" is-up":""}${Y||!r?" busy":""}`,type:"button",disabled:!!Y||!r,title:"Start or stop this project's container",onClick:()=>q(!1),children:Y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"power-spin",children:"↻"})," ",Y==="starting"?"starting…":"stopping…"]}):r?A?"■ Stop":"▶ Start":s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"power-spin",children:"↻"})," …"]})}),s.jsx("button",{className:`dock-toggle${a?"":" on"}`,type:"button",title:"Show/hide the Claude terminal",onClick:M,children:"⌨ Terminal"}),s.jsx("button",{className:`dock-toggle${b?" on":""}`,type:"button",title:"Show/hide a host shell (⌘J)",onClick:P,children:"▂ Host shell"}),s.jsx("button",{className:`dock-toggle${x?" on":""}`,type:"button",title:"Ask Claude — a host claude chat (⌘K)",onClick:U,children:"💬 Ask Claude"})]}),s.jsx(cl,{repoId:o}),d&&(d.cacheName||d.reason)&&(()=>{const X=d.reused&&d.verified==="no",Q=d.reused&&d.verified!=="no",re=X?" stalled":Q?" reused":"";return s.jsxs("div",{className:`dind-banner${re}`,title:"Docker-in-Docker cache reuse for this project",children:[s.jsx("span",{className:"dind-banner-tag",children:"DinD"}),d.cacheName?s.jsxs("span",{className:"dind-banner-cache",children:[d.isRepo?"repo baseline ":"cache ",s.jsx("code",{children:d.cacheName}),d.mode?` · ${d.mode}`:""]}):null,s.jsx("span",{className:`dind-banner-verdict${Q?" on":X?" warn":""}`,children:Q?"✓ reused":X?"⚠ not landed":"○ not reused"}),s.jsx("span",{className:"dind-banner-reason",children:d.reason})]})})(),s.jsxs("div",{className:`project-layout${a?" dock-collapsed":""}`,id:"project-layout",children:[s.jsxs("div",{className:"tab-area",children:[s.jsx("div",{className:"tabs",children:Dg.map(X=>s.jsx("button",{className:`tab-btn${f===X.key?" active":""}`,onClick:()=>c(X.key),children:X.label},X.key))}),s.jsx("div",{id:"tab-files",className:"tab-panel",style:{display:f==="files"?"flex":"none",flex:"1 1 auto",minHeight:0},children:w.files&&s.jsx(lg,{projectId:e})}),s.jsx("div",{id:"tab-diff",className:"tab-panel",style:{display:f==="diff"?"flex":"none",flex:"1 1 auto",minHeight:0},children:w.diff&&s.jsx(ug,{projectId:e})}),s.jsxs("div",{id:"tab-container",className:"tab-panel",style:{display:f==="container"?"flex":"none",flexDirection:"column",flex:"1 1 auto",minHeight:0},children:[(n==null?void 0:n.workspace)&&s.jsxs("p",{className:"container-mount-note",children:["Workspace is mounted at the same path inside the container (not under ",s.jsx("code",{children:"~"}),"):"," ",s.jsx("code",{className:"container-mount-path",title:"Click to copy",onClick:()=>{var X;return(X=navigator.clipboard)==null?void 0:X.writeText(n.workspace)},children:n.workspace})," ","— the shell already starts here."]}),s.jsxs("div",{className:"screen-frame screen-frame-fill",children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"container shell · ",i]}),w.container&&A?s.jsx(Zs,{projectId:e,wsPath:"/container/ws",kind:"container"}):r?s.jsx("p",{className:"empty",children:A?"open to connect":"container not running"}):s.jsx("p",{className:"empty screen-loading",children:"checking status…"})]})]}),s.jsx("div",{id:"tab-liveview",className:"tab-panel",style:{display:f==="liveview"?"flex":"none",flexDirection:"column",flex:"1 1 auto",minHeight:0},children:w.liveview&&s.jsx(jg,{projectId:e,containerUp:!!A})}),s.jsx("div",{id:"tab-mitm",className:"tab-panel",style:{display:f==="mitm"?"block":"none"},children:w.mitm&&s.jsx(bg,{projectId:e,mitmUp:!!(n!=null&&n.mitm_up)})}),s.jsx("div",{id:"tab-firewall",className:"tab-panel",style:{display:f==="firewall"?"block":"none"},children:w.firewall&&s.jsx(Cg,{projectId:e})}),s.jsx("div",{id:"tab-conversations",className:"tab-panel",style:{display:f==="conversations"?"block":"none",flex:"1 1 auto",minHeight:0,overflow:"auto"},children:w.conversations&&s.jsx(Lg,{projectId:e})}),s.jsx("div",{id:"tab-config",className:"tab-panel",style:{display:f==="config"?"block":"none",flex:"1 1 auto",minHeight:0},children:w.config&&s.jsx(hg,{projectId:e,refreshKey:v})})]}),s.jsxs("aside",{className:"term-dock",id:"term-dock",style:{flex:`0 0 ${T}px`},children:[s.jsx("div",{className:"term-dock-handle",ref:$,title:"Drag to resize"}),s.jsxs("div",{className:"screen-frame",children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),i," · Claude"]}),_&&(n!=null&&n.tmux_up)?s.jsx(Zs,{projectId:e,wsPath:"/terminal/ws",kind:"claude"}):r?s.jsx("p",{className:"empty",children:n!=null&&n.tmux_up?"open to connect":"this project isn't running — press ▶ Start above"}):s.jsx("p",{className:"empty screen-loading",children:"checking status…"})]})]})]}),b&&s.jsxs("div",{className:"host-overlay",id:"host-overlay",style:{height:`${B}px`},children:[s.jsx("div",{className:"host-overlay-handle",ref:R,title:"Drag to resize"}),s.jsxs("div",{className:"host-overlay-bar",children:[s.jsxs("span",{children:[s.jsx("i",{className:"screen-dot"}),"host shell · ",i]}),s.jsx("button",{type:"button",title:"Close (⌘J)",onClick:()=>k(!1),children:"✕"})]}),s.jsx("div",{className:"host-overlay-iframe",children:s.jsx(Zs,{projectId:e,wsPath:"/host/ws",kind:"host"})})]}),x&&s.jsxs("div",{className:`chat-panel${E==="left"?" dock-left":""}`,id:"chat-panel",style:{width:`${z}px`},children:[s.jsx("div",{className:"chat-panel-handle",ref:D}),s.jsxs("div",{className:"chat-panel-bar",children:[s.jsxs("span",{children:[s.jsx("i",{className:"screen-dot"}),"ask claude · host"]}),s.jsxs("span",{className:"chat-panel-actions",children:[s.jsx("button",{type:"button",title:"Dock left/right",onClick:W,children:"⇄"}),s.jsx("button",{type:"button",title:"Close (⌘K)",onClick:()=>N(!1),children:"✕"})]})]}),s.jsx("div",{className:"chat-panel-iframe",children:s.jsx(an,{wsPath:`/p/${e}/chat/ws?tools=Read,Grep,Glob`})})]}),J&&s.jsx(nn,{projectId:e,onDone:X=>{I(!1),X&&q(!0)}})]})}function Fg({repoId:e,onMsg:t}){const r=e?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState(0),[o,u]=C.useState(""),[d,m]=C.useState(!1),[f,g]=C.useState(""),[w,S]=C.useState(!1),[v,p]=C.useState(""),c=C.useRef(null);C.useEffect(()=>()=>{var E;return(E=c.current)==null?void 0:E.close()},[]);const a=C.useCallback(()=>{ee(`/api/prompts${r}`).then(E=>i(E.prompts||[])).catch(E=>t({text:E.message,err:!0}))},[r,t]);C.useEffect(()=>{a()},[a]);const l=n[h];if(C.useEffect(()=>{l&&(u(l.effective),m(!1),p(""),g(""))},[l==null?void 0:l.key,l==null?void 0:l.effective]),n.length===0||!l)return null;const _=E=>{y(L=>(L+E+n.length)%n.length)},j=async()=>{await fetch(`/api/prompts/${encodeURIComponent(l.key)}${r}`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({template:o})}).then(E=>E.json()).then(E=>{i(L=>L.map(T=>T.key===E.key?E:T)),t({text:"✓ prompt saved",err:!1})}).catch(E=>t({text:E.message,err:!0}))},b=async()=>{await fetch(`/api/prompts/${encodeURIComponent(l.key)}${r}`,{method:"DELETE",credentials:"same-origin"}).then(E=>E.json()).then(E=>{i(L=>L.map(T=>T.key===E.key?E:T)),t({text:"↺ reset to default",err:!1})}).catch(E=>t({text:E.message,err:!0}))},k=l.key==="worker.boot_guidance",x=()=>{var T;if(!k&&!f.trim())return;(T=c.current)==null||T.close(),S(!0),p("");const E=e?`/api/prompts/draft?repoId=${encodeURIComponent(e)}`:"/api/prompts/draft",L=new WebSocket(hs(E));c.current=L,L.onopen=()=>L.send(JSON.stringify({description:f,key:l.key})),L.onmessage=O=>{let B;try{B=JSON.parse(O.data)}catch{return}B.type==="text"?p(F=>F+B.text):B.type==="tool_use"?p(F=>F+`› ${B.tool} -`):B.type==="error"?p(F=>F+` -⚠ ${B.text||""}`):B.type==="draft"&&B.result&&(u(B.result),m(!0))},L.onclose=()=>{S(!1),c.current=null},L.onerror=()=>p(O=>O+` -⚠ draft connection failed`)},N=n.filter(E=>E.overridden).length;return s.jsxs("section",{className:"prompts-section",children:[s.jsxs("div",{className:"prompts-head",children:[s.jsxs("div",{className:"prompts-title",children:[s.jsx("span",{className:"prompts-icon","aria-hidden":!0,children:"✎"}),s.jsxs("div",{children:[s.jsx("h3",{className:"auto-mgr-h",style:{margin:0},children:"Prompts"}),s.jsxs("p",{className:"prompts-sub",children:["The editable instructions Corral gives Claude — ",n.length," built-in",N>0?`, ${N} modified here`:"","."]})]})]}),s.jsxs("div",{className:"prompts-picker",children:[s.jsx("select",{className:"cfg-select prompts-select",value:h,onChange:E=>y(Number(E.target.value)),"aria-label":"Choose a prompt to edit",children:n.map((E,L)=>s.jsxs("option",{value:L,children:[E.name,E.overridden?" • modified":""]},E.key))}),s.jsxs("div",{className:"prompts-pager",children:[s.jsx("button",{type:"button",className:"carousel-arrow",onClick:()=>_(-1),"aria-label":"Previous prompt",children:"‹"}),s.jsxs("span",{className:"prompts-count",children:[h+1," / ",n.length]}),s.jsx("button",{type:"button",className:"carousel-arrow",onClick:()=>_(1),"aria-label":"Next prompt",children:"›"})]})]})]}),s.jsxs("div",{className:"prompt-card",children:[s.jsxs("div",{className:"prompt-card-head",children:[l.name,s.jsx("span",{className:"auto-scope",children:e?"repo":"global"}),l.overridden&&s.jsx("span",{className:"modified-pill",children:"modified"}),!l.overridden&&l.source!=="default"&&s.jsxs("span",{className:"inherited-pill",children:["from ",l.source]})]}),s.jsxs("p",{className:"prompt-usedwhen",children:["↳ ",l.usedWhen]}),l.slots.length>0&&s.jsxs("div",{className:"prompt-slots",children:[s.jsx("span",{className:"prompt-slots-label",children:"Available:"}),l.slots.map(E=>s.jsx("code",{className:"prompt-slot-chip",children:`{{${E}}}`},E))]}),s.jsx("textarea",{className:"prompt-textarea",rows:8,value:o,onChange:E=>{u(E.target.value),m(!0)}}),s.jsxs("div",{className:"prompt-actions-row",children:[s.jsx("button",{type:"button",className:"auto-btn",disabled:!d,onClick:j,children:"Save"}),s.jsx("button",{type:"button",className:"auto-btn",disabled:!l.overridden,onClick:b,children:"Reset to default"})]}),s.jsxs("details",{className:"prompt-ai",children:[s.jsxs("summary",{children:["✨ Build with AI"," ",s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude, not the sandbox; read-only",children:"host · not sandboxed · read-only"})]}),k&&s.jsxs("p",{className:"prompt-usedwhen",style:{marginTop:0},children:["↳ Recommends a caching recipe for this repo from what we learned booting it",e?"":" (select a repo to ground it in that repo's boot history)"," — reads its captured boot runs + the codebase. Notes below are optional."]}),s.jsx("textarea",{className:"prompt-textarea",rows:2,value:f,onChange:E=>g(E.target.value),placeholder:k?"Optional notes to steer the recommendation…":"Describe what this prompt should do…"}),s.jsx("button",{type:"button",className:"auto-btn",disabled:w||!k&&!f.trim(),onClick:x,children:w?"Drafting…":k?"Recommend from our boot history":"Draft with AI"}),v&&s.jsx("pre",{className:"split-menu-ai-log",children:v})]})]})]})}function Ug({repoId:e,onMsg:t}){const r=e?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState(null),[o,u]=C.useState(""),[d,m]=C.useState(""),[f,g]=C.useState(""),w=C.useCallback(()=>{ee(`/api/prompts/library${r}`).then(a=>i(a.prompts||[])).catch(a=>t==null?void 0:t({text:a.message,err:!0}))},[r,t]);C.useEffect(()=>w(),[w]);function S(){y("new"),u(""),m(""),g("")}function v(a){y(a.id),u(a.name),m(a.template),g(a.description||"")}async function p(){if(!o.trim()||!d.trim()){t==null||t({text:"A name and a template are required.",err:!0});return}try{h==="new"?(await oe("/api/prompts/library",{name:o.trim(),template:d,description:f.trim(),repo:e||void 0}),t==null||t({text:`Saved "${o.trim()}".`,err:!1})):typeof h=="number"&&(await zg(`/api/prompts/library/${h}`,{name:o.trim(),template:d,description:f.trim()}),t==null||t({text:`Updated "${o.trim()}".`,err:!1})),y(null),w()}catch(a){t==null||t({text:`Couldn't save: ${a.message}`,err:!0})}}async function c(a){if(confirm(`Delete the "${a.name}" prompt?`))try{await St(`/api/prompts/library/${a.id}`),w()}catch(l){t==null||t({text:`Couldn't delete: ${l.message}`,err:!0})}}return s.jsxs("section",{className:"promptlib",children:[s.jsxs("div",{className:"promptlib-head",children:[s.jsxs("h3",{className:"auto-mgr-h",style:{margin:0},children:["Saved prompts ",s.jsx("span",{className:"auto-hint",style:{fontWeight:400},children:"— pick these when you start a project or work an issue"})]}),h===null&&s.jsx("button",{type:"button",className:"auto-btn",onClick:S,children:"+ New prompt"})]}),h!==null?s.jsxs("div",{className:"promptlib-editor",children:[s.jsx("input",{className:"auto-input",placeholder:"Name (e.g. Thorough refactor)",value:o,onChange:a=>u(a.target.value)}),s.jsx("input",{className:"auto-input",placeholder:"Short description (optional)",value:f,onChange:a=>g(a.target.value)}),s.jsx("textarea",{className:"auto-input promptlib-template",placeholder:"The prompt text. Use {{repo}}, {{branch}}, {{number}}, {{title}} where the start flow fills them in.",value:d,onChange:a=>m(a.target.value),rows:6}),s.jsxs("div",{className:"promptlib-editor-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:p,children:"Save"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>y(null),children:"Cancel"})]})]}):n.length===0?s.jsx("p",{className:"auto-empty",children:"No saved prompts yet. Create one to reuse it at project or issue start."}):s.jsx("ul",{className:"promptlib-list",children:n.map(a=>s.jsxs("li",{className:"promptlib-item",children:[s.jsxs("div",{className:"promptlib-item-main",children:[s.jsx("span",{className:"promptlib-name",children:a.name}),a.scope==="repo"&&s.jsx("span",{className:"promptlib-scope",children:"this repo"}),a.description&&s.jsx("span",{className:"promptlib-desc",children:a.description}),s.jsx("div",{className:"promptlib-preview",children:a.template})]}),s.jsxs("div",{className:"promptlib-item-actions",children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>v(a),children:"edit"}),s.jsx("button",{type:"button",className:"promptlib-x",title:"Delete",onClick:()=>c(a),children:"×"})]})]},a.id))})]})}function zg(e,t){return fetch(e,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`)})}const Wg=["CORRAL_EVENT","CORRAL_REPO_ID","CORRAL_PR_NUMBER","CORRAL_PR_URL","CORRAL_PR_TITLE","CORRAL_OWNER_NAME","CORRAL_HEAD_SHA"];function Id({script:e,onChange:t}){const r=C.useRef(null),n=C.useRef(null),i=C.useRef(e),[h,y]=C.useState(!1);C.useEffect(()=>{let L=null,T=!1;return Pi().then(O=>{T||!r.current||(L=O.createEditor({parent:r.current,doc:i.current,language:"bash",onChange:B=>{i.current=B,t(B)}}),n.current=L,y(!0))}).catch(()=>y(!1)),()=>{T=!0,L==null||L.destroy(),n.current=null}},[]);const[o,u]=C.useState(null);C.useEffect(()=>{ee("/api/scripts/env").then(u).catch(()=>u(null))},[]);const[d,m]=C.useState(!1),[f,g]=C.useState(null),[w,S]=C.useState(!1),[v,p]=C.useState(""),[c,a]=C.useState(!1),[l,_]=C.useState(""),j=C.useRef(null),b=L=>{var T,O;i.current=L,t(L),(O=(T=n.current)==null?void 0:T.setDoc)==null||O.call(T,L)},k=L=>{if(n.current){b((i.current||"")+L);return}b((i.current||"")+L)},x=async()=>{m(!0),g(null);try{const L=await fetch("/api/actions:test",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"bash",spec:JSON.stringify({script:i.current}),context:{event:"test",vars:{pr_number:"0",pr_url:"https://example/pr/0",pr_title:"Test PR",owner_name:"owner/repo"}}})});g(await L.json())}catch(L){g({status:"error",error:L.message})}finally{m(!1)}},N=()=>{var T;if(!v.trim())return;(T=j.current)==null||T.close(),a(!0),_("");const L=new WebSocket(hs("/api/scripts/draft"));j.current=L,L.onopen=()=>L.send(JSON.stringify({description:v})),L.onmessage=O=>{let B;try{B=JSON.parse(O.data)}catch{return}B.type==="text"?_(F=>F+B.text):B.type==="tool_use"?_(F=>F+`› ${B.tool} -`):B.type==="error"?_(F=>F+` -⚠ ${B.text||""}`):B.type==="draft"&&B.result&&b(B.result)},L.onclose=()=>{a(!1),j.current=null},L.onerror=()=>_(O=>O+` +`)),r(f)},o=()=>{const d=n.split(/[\s,]+/).map(m=>m.trim()).filter(Boolean);d.length&&(y([...h,...d]),i(""))},u=d=>y(h.filter(m=>m!==d));return s.jsxs("div",{className:"monitor-list",children:[h.length===0?s.jsx("div",{className:"muted cfg-note",style:{marginBottom:6},children:"nothing monitored yet — every allowed host is direct-dialed (undecrypted). Add a host to decrypt it."}):s.jsx("div",{className:"monitor-chips",children:h.map(d=>s.jsxs("span",{className:"monitor-chip",children:[s.jsx("span",{className:"monitor-chip-host",children:d}),s.jsx("button",{type:"button",className:"monitor-chip-x",title:`Stop monitoring ${d}`,onClick:()=>u(d),children:"✕"})]},d))}),s.jsxs("div",{className:"monitor-add",children:[s.jsx("input",{type:"text",placeholder:"add a host (api.example.com)",autoComplete:"off",spellCheck:!1,value:n,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),o())}}),s.jsx("button",{type:"button",className:"cfg-btn cfg-btn-ghost",onClick:o,children:"+ add"})]})]})}function Xe({label:e,children:t}){return s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:e}),s.jsx("div",{className:"cfg-value",children:t})]})}function En({checked:e,onChange:t}){return s.jsxs("label",{className:"cfg-inline",children:[s.jsx("input",{type:"checkbox",checked:e,onChange:r=>t(r.target.checked)})," ",s.jsx("span",{className:"cfg-slider"})]})}function fg({status:e,onRestart:t}){return e?e.configured?e.container_stale?s.jsxs("span",{className:"attention",children:["⚠ keys loaded on host, but the running container can't reach them — restart it to use SSH."," ",s.jsx("button",{className:"cfg-btn cfg-btn-danger",onClick:t,children:"Restart container"})]}):e.loaded?s.jsxs("span",{className:"s-2xx",children:["✓ ",e.count," key(s) loaded — start won't prompt"]}):s.jsx("span",{className:"muted",children:"not loaded — start will need passphrases"}):s.jsx("span",{className:"muted",children:"no keys configured"}):s.jsx("span",{className:"muted",children:"checking…"})}const Mc="corral.monitorWarnAck";function Ts(e,t){return`/p/${e}${t}`}function Od(e){return e==null||e<0?"":e<1024?`${e}b`:e<1024*1024?`${(e/1024).toFixed(1)}kb`:`${(e/(1024*1024)).toFixed(1)}mb`}function ho(e){return(e<10?"0":"")+e}function Ic(e){if(!e)return"";const t=new Date(e*1e3);return`${ho(t.getHours())}:${ho(t.getMinutes())}:${ho(t.getSeconds())}`}function pg(e){const t=e.match(/(\d\d):(\d\d):(\d\d)/);return t?`${t[1]}:${t[2]}:${t[3]}`:e}function mg(e){return e?e>=500?"s-5xx":e>=400?"s-4xx":e>=300?"s-3xx":"s-2xx":"s-pending"}function gg(e){var r;const t=e.response;return!t||!t.timestamp_end||!((r=e.request)!=null&&r.timestamp_start)?"":`${Math.round((t.timestamp_end-e.request.timestamp_start)*1e3)}ms`}function vg(e){for(const t of(e==null?void 0:e.headers)||[])if(t[0].toLowerCase()==="content-type")return t[1];return""}const _g=512*1024,Bc=6,$c=700;function yg({projectId:e,flowId:t,side:r,msg:n}){const[i,h]=C.useState({status:"loading",text:""});return C.useEffect(()=>{let y=!0;if((n==null?void 0:n.contentLength)===0){h({status:"ready",text:"(empty)"});return}h(m=>m.status==="ready"?m:{status:"loading",text:""});let o;const u=()=>r==="response"&&!(n!=null&&n.timestamp_end),d=m=>{Nm(Ts(e,`/mitm/flows/${t}/${r}/content`)).then(f=>{if(!y)return;if(f.length>_g){h({status:"ready",text:`body too large to display (${Od(f.length)})`});return}if(f===""&&u()&&my&&d(m+1),$c);return}let g=f;if(vg(n).toLowerCase().includes("json"))try{g=JSON.stringify(JSON.parse(f),null,2)}catch{}h({status:"ready",text:g||"(empty)"})}).catch(f=>{if(y){if(my&&d(m+1),$c);return}h({status:"error",text:`couldn't load body: ${f.message}`})}})};return d(0),()=>{y=!1,o&&window.clearTimeout(o)}},[e,t,r,n]),i.status==="loading"?s.jsxs("div",{className:"mitm-body mitm-body-loading",children:[s.jsx("span",{className:"mitm-spinner","aria-hidden":"true"}),"loading body…"]}):s.jsx("pre",{className:`mitm-body${i.status==="error"?" mitm-body-error":""}`,children:i.text})}function xg(){const e=[0,1,2,3,4,5];return s.jsxs("table",{className:"mitm-table mitm-skeleton","aria-hidden":"true",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"When"}),s.jsx("th",{}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Host"}),s.jsx("th",{children:"Path"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Size"}),s.jsx("th",{children:"Dur"})]})}),s.jsx("tbody",{children:e.map(t=>s.jsxs("tr",{className:"m-row",children:[s.jsx("td",{className:"m-when",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-caret"}),s.jsx("td",{className:"m-method",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-host",children:s.jsx("span",{className:"sk sk-cell",style:{width:"80%"}})}),s.jsx("td",{className:"m-path",children:s.jsx("span",{className:"sk sk-cell",style:{width:`${55+t*13%40}%`}})}),s.jsx("td",{className:"m-status",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-size",children:s.jsx("span",{className:"sk sk-cell"})}),s.jsx("td",{className:"m-dur",children:s.jsx("span",{className:"sk sk-cell"})})]},t))})]})}function Sg({headers:e}){return!e||!e.length?s.jsx("div",{className:"mitm-empty",children:"(none)"}):s.jsx("table",{className:"mitm-headers",children:s.jsx("tbody",{children:e.map((t,r)=>s.jsxs("tr",{children:[s.jsx("td",{children:t[0]}),s.jsx("td",{children:t[1]})]},r))})})}function wg({projectId:e,flowId:t,req:r,resp:n}){const[i,h]=C.useState("response"),y=i==="request"?r:n;return s.jsxs("div",{className:"mitm-detail",children:[s.jsxs("div",{className:"mitm-tabs",children:[s.jsx("button",{type:"button",className:`mitm-tab${i==="request"?" active":""}`,onClick:()=>h("request"),children:"Request"}),s.jsx("button",{type:"button",className:`mitm-tab${i==="response"?" active":""}`,onClick:()=>h("response"),children:"Response"})]}),s.jsx("div",{className:"mitm-sec",children:"Headers"}),s.jsx(Sg,{headers:y.headers}),s.jsx("div",{className:"mitm-sec",children:"Body"}),s.jsx(yg,{projectId:e,flowId:t,side:i,msg:y})]})}function bg({projectId:e,mitmUp:t}){var M,O,W,F,z,X;const[r,n]=C.useState([]),[i,h]=C.useState([]),[y,o]=C.useState(""),[u,d]=C.useState(""),[m,f]=C.useState({}),[g,w]=C.useState("loading flows…"),[S,v]=C.useState(!1),[p,c]=C.useState(!1),[a,l]=C.useState({}),[_,j]=C.useState(new Set),b=C.useRef(!0),[k,x]=C.useState(null),[N,E]=C.useState(!1),[L,T]=C.useState(()=>{try{return localStorage.getItem(Mc)==="1"}catch{return!1}}),P=I=>{T(I);try{localStorage.setItem(Mc,I?"1":"0")}catch{}};C.useEffect(()=>{const I=window.setTimeout(()=>d(y.trim()),250);return()=>window.clearTimeout(I)},[y]);const B=C.useCallback(async()=>{try{const I=await ee(Ts(e,"/mitm/flows"));n(I),w(`${I.length} flow${I.length===1?"":"s"}`),v(!1)}catch(I){w(`mitm unavailable: ${I.message}`),v(!0)}try{const I=u?`?q=${encodeURIComponent(u)}`:"",D=await ee(Ts(e,`/mitm/direct${I}`));h(D.direct||[])}catch{}c(!0)},[e,u]);C.useEffect(()=>{if(!t)return;B();const I=window.setInterval(()=>b.current&&B(),2e3);return()=>window.clearInterval(I)},[t,B]);const U=C.useCallback(async()=>{try{const I=await ee(Ts(e,"/config"));j(new Set((I.monitor_hosts||[]).map(D=>D.toLowerCase())))}catch{}},[e]);C.useEffect(()=>{if(!t)return;U();const I=window.setInterval(()=>b.current&&U(),3e3),D=()=>U();return window.addEventListener("focus",D),()=>{window.clearInterval(I),window.removeEventListener("focus",D)}},[t,U]);const K=C.useCallback(async I=>{const D=I.split(":")[0];l(V=>({...V,[I]:"busy"}));try{const V=await ee(Ts(e,"/config")),H=new Set(V.monitor_hosts||[]);H.add(D),await oe(Ts(e,"/config/apply"),{mitm_preset:"custom",monitor_hosts:[...H]}),l(J=>({...J,[I]:"done"})),U()}catch(V){l(H=>{const J={...H};return delete J[I],J}),alert(`couldn't start monitoring ${D}: ${V.message}`)}},[e]),q=C.useCallback(I=>{if(L){K(I);return}E(!1),x(I)},[L,K]);if(!t)return s.jsx("p",{className:"empty",children:"Credential proxy isn't running for this project."});const $=y.trim().toLowerCase().split(/\s+/).filter(Boolean),R=[];for(const I of r){const D=[(M=I.request)==null?void 0:M.method,((O=I.request)==null?void 0:O.pretty_host)||((W=I.request)==null?void 0:W.host),(F=I.request)==null?void 0:F.path,(z=I.response)==null?void 0:z.status_code].join(" ").toLowerCase();$.length&&!$.every(V=>D.includes(V))||R.push({kind:"flow",ts:((X=I.request)==null?void 0:X.timestamp_start)||I.timestamp_created||0,flow:I})}i.forEach((I,D)=>{R.push({kind:"direct",ts:I.ts,host:I.host,when:I.when,key:`${I.host}|${I.when}|${D}`})}),R.sort((I,D)=>D.ts-I.ts);const A=R;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mitm-toolbar",children:[s.jsx("input",{type:"text",placeholder:"filter: host, path, method, status…",autoComplete:"off",spellCheck:!1,value:y,onChange:I=>o(I.target.value)}),s.jsx("span",{className:S?"s-4xx":"muted",children:g})]}),s.jsxs("p",{className:"muted cfg-note",style:{padding:"0 0.5rem 0.5rem"},children:["Decrypted flows (monitored hosts) and individual direct-dialed requests are interleaved by time. Direct rows are dimmed with a “not decrypted” badge — their TLS isn’t intercepted, so contents aren’t available; click ",s.jsx("em",{children:"Monitor"})," to decrypt future requests to that host (the already-completed one can’t be retroactively decrypted). Filtering by host searches the full proxy-log history for direct requests; decrypted flows filter over mitmweb’s current set."]}),s.jsxs("div",{id:"mitm-flows",children:[!p&&s.jsx(xg,{}),p&&R.length===0&&s.jsx("p",{className:"empty",children:"No traffic captured yet."}),p&&R.length>0&&A.length===0&&s.jsxs("p",{className:"empty",children:["No flows match “",y,"”."]}),p&&A.length>0&&s.jsxs("table",{className:"mitm-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"When"}),s.jsx("th",{}),s.jsx("th",{children:"Method"}),s.jsx("th",{children:"Host"}),s.jsx("th",{children:"Path"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Size"}),s.jsx("th",{children:"Dur"})]})}),s.jsx("tbody",{children:A.map(I=>{if(I.kind==="direct"){const ie=a[I.host],he=_.has(I.host.split(":")[0].toLowerCase());return s.jsxs("tr",{className:"m-row m-direct",style:{opacity:.62},children:[s.jsx("td",{className:"m-when",children:I.ts?Ic(I.ts):pg(I.when)}),s.jsx("td",{className:"m-caret"}),s.jsx("td",{className:"m-method",children:"—"}),s.jsx("td",{className:"m-host",children:s.jsx("div",{className:"cell-scroll",children:I.host})}),s.jsx("td",{className:"m-path",children:s.jsx("span",{className:"cfg-ssh-badge",children:"not decrypted"})}),s.jsx("td",{className:"m-status",children:"—"}),s.jsx("td",{className:"m-size",children:"—"}),s.jsx("td",{className:"m-dur",children:he?s.jsx("span",{className:"s-2xx",title:"This host is now monitored — this was an earlier direct-dialed request; newer ones are decrypted",children:"now monitored"}):s.jsx("button",{className:"cfg-btn cfg-btn-ghost",disabled:ie==="busy",title:"Decrypt future requests to this host",onClick:()=>q(I.host),children:ie==="busy"?"…":"Monitor"})})]},I.key)}const D=I.flow,V=D.request||{},H=D.response||{},J=H.status_code||0,Q=H.contentLength!=null?H.contentLength:V.contentLength,re=!!m[D.id];return s.jsxs(C.Fragment,{children:[s.jsxs("tr",{className:"m-row",onClick:()=>f(ie=>({...ie,[D.id]:!ie[D.id]})),children:[s.jsx("td",{className:"m-when",children:Ic(V.timestamp_start||D.timestamp_created)}),s.jsx("td",{className:"m-caret",children:re?"▾":"▸"}),s.jsx("td",{className:"m-method",children:V.method||""}),s.jsx("td",{className:"m-host",children:s.jsx("div",{className:"cell-scroll",children:V.pretty_host||V.host||""})}),s.jsx("td",{className:"m-path",title:V.path||"",children:s.jsx("div",{className:"cell-scroll",children:V.path||""})}),s.jsx("td",{className:`m-status ${mg(J)}`,children:J||"…"}),s.jsx("td",{className:"m-size",children:Od(Q)}),s.jsx("td",{className:"m-dur",children:gg(D)})]}),re&&s.jsx("tr",{className:"m-detailrow",children:s.jsx("td",{colSpan:8,children:s.jsx(wg,{projectId:e,flowId:D.id,req:V,resp:H})})})]},D.id)})})]})]}),k&&s.jsxs(hr,{title:"Monitor this host?",onClose:()=>x(null),children:[s.jsxs("p",{className:"mitm-tldr",children:[s.jsx("strong",{children:"TL;DR:"})," this will most likely just work. If requests to this host stop showing up here after you monitor it, it’s a CA-trust issue — remove it from the monitor list in ",s.jsx("em",{children:"Config → Capture"})," and it goes back to working (undecrypted)."]}),s.jsxs("div",{className:"cfg-warn",style:{marginTop:0},children:[s.jsx("strong",{children:"⚠ Monitoring makes the proxy present its own CA."})," Clients that pin certificates or statically link their TLS with a bundled root store won’t trust it — the handshake fails and the request never completes (so a broken host won’t even appear here). If a host breaks after you monitor it, remove it from the monitor list in ",s.jsx("em",{children:"Config → Capture"}),"; it falls back to direct-dial (undecrypted) and works again."]}),s.jsxs("p",{className:"muted",style:{fontSize:"0.82rem"},children:["Future requests to ",s.jsx("code",{children:k.split(":")[0]})," will be decrypted. The already-completed request can’t be retroactively decrypted."]}),s.jsxs("details",{className:"mitm-readmore",children:[s.jsx("summary",{children:"Read more — how the CA is trusted, and what to do when it isn’t"}),s.jsxs("div",{className:"mitm-readmore-body",children:[s.jsxs("p",{children:["The sandbox already trusts the proxy CA for most tooling: it installs the CA into the system trust store and exports"," ",s.jsx("code",{children:"SSL_CERT_FILE"}),", ",s.jsx("code",{children:"REQUESTS_CA_BUNDLE"}),", ",s.jsx("code",{children:"NODE_EXTRA_CA_CERTS"}),", and"," ",s.jsx("code",{children:"CURL_CA_BUNDLE"})," — so Python, Node, curl, and anything using the OS store or those variables work."]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Docker-in-Docker & docker builds are handled too:"})," a cert-injector daemon adds the CA to every inner container, and builds read it from ",s.jsx("code",{children:"/etc/docker/certs.d//ca.crt"}),"."]}),s.jsxs("p",{children:[s.jsx("strong",{children:"If a runtime has its own trust store,"})," point it at the CA the same way — most respect an env var, e.g."," ",s.jsx("code",{children:"SSL_CERT_FILE"})," / ",s.jsx("code",{children:"SSL_CERT_DIR"})," (Go, OpenSSL), ",s.jsx("code",{children:"NODE_EXTRA_CA_CERTS"})," (Node),"," ",s.jsx("code",{children:"REQUESTS_CA_BUNDLE"})," (Python requests), ",s.jsx("code",{children:"GIT_SSL_CAINFO"})," (git). The CA is at"," ",s.jsx("code",{children:"~/.mitmproxy/mitmproxy-ca-cert.pem"}),"."]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Statically-linked binaries that embed their own root store"})," ignore both the system store and those env vars — there’s no way to make them trust the proxy CA. For those, don’t monitor the host; instead route just that binary’s traffic through an internal proxy of your own that re-terminates and forwards the payloads, or leave it direct-dialed (undecrypted)."]})]})]}),s.jsxs("label",{className:"cfg-inline",style:{margin:"0.6rem 0 0.3rem"},children:[s.jsx("input",{type:"checkbox",checked:N,onChange:I=>E(I.target.checked)})," I understand the consequences"]}),s.jsxs("label",{className:"cfg-inline",style:{margin:"0 0 0.9rem"},children:[s.jsx("input",{type:"checkbox",checked:L,onChange:I=>P(I.target.checked),disabled:!N})," Don’t show this again"]}),s.jsxs("div",{className:"form-actions",children:[s.jsx("button",{className:"btn primary",disabled:!N,onClick:()=>{const I=k;x(null),K(I)},children:"Monitor host"}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>x(null),children:"Cancel"})]})]})]})}function Cg({projectId:e}){const[t,r]=C.useState([]),n=C.useRef(null);return C.useEffect(()=>{const i=new EventSource(`/p/${e}/firewall/stream`);return i.onmessage=h=>r(y=>[...y,h.data]),i.addEventListener("error",()=>r(h=>[...h,"[stream disconnected]"])),()=>i.close()},[e]),C.useEffect(()=>{n.current&&(n.current.scrollTop=n.current.scrollHeight)},[t]),s.jsxs("div",{className:"screen-frame",children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"allowlist proxy · live log"]}),s.jsx("pre",{className:"screen-body",ref:n,children:t.join(` +`)})]})}const kg="allow-scripts allow-forms allow-popups allow-modals allow-same-origin";function jg({projectId:e,containerUp:t}){const[r,n]=C.useState([]),[i,h]=C.useState(null),[y,o]=C.useState(""),[u,d]=C.useState(""),[m,f]=C.useState(""),[g,w]=C.useState(0),[S,v]=C.useState(null);C.useEffect(()=>{ee("/api/live-origin").then(v).catch(()=>v(null))},[]);const p=C.useRef(!1),c=C.useCallback(()=>{ee(`/p/${e}/live-ports`).then(k=>{n(k.ports||[]),h(x=>x==null&&!p.current&&k.ports&&k.ports.length?k.ports[0]:x)}).catch(()=>n([]))},[e]),a=C.useCallback(()=>{ee(`/p/${e}/live-port`).then(k=>{if(k.port&&!p.current){h(N=>N==null||N!==k.port?k.port:N);const x=k.path||"";d(N=>N!==x?x:N),f(N=>N===""?x:N)}}).catch(()=>{})},[e]);C.useEffect(()=>{if(!t)return;c(),a();const k=setInterval(a,4e3);return()=>clearInterval(k)},[t,c,a]);const l=k=>{p.current=!0,h(k),w(x=>x+1)},_=()=>{const k=parseInt(y.trim(),10);k>=1&&k<=65535&&l(k)},j=i!=null&&S?`${S.base_url}/p/${e}/live/${i}${u||"/"}?__live_token=${encodeURIComponent(S.token)}`:"",b=()=>{d(m.trim()),w(k=>k+1)};return t?s.jsxs("div",{className:"live-view",children:[s.jsxs("div",{className:"live-hint muted",children:["Pick a port and path above, or ask the ",s.jsx("strong",{children:"Ask Claude"})," host chat (the global one — it can run ",s.jsx("code",{children:"corral api"}),") to start your app and set the Live View port for you."]}),s.jsxs("div",{className:"live-bar",children:[s.jsx("span",{className:"live-label",children:"Port"}),r.map(k=>s.jsx("button",{className:`live-port${k===i?" active":""}`,onClick:()=>l(k),children:k},k)),s.jsx("input",{className:"live-port-input",placeholder:"port",inputMode:"numeric",value:y,onChange:k=>o(k.target.value.replace(/[^0-9]/g,"")),onKeyDown:k=>{k.key==="Enter"&&_()}}),s.jsx("button",{className:"live-btn",onClick:_,disabled:!y.trim(),children:"Go"}),s.jsx("span",{className:"live-label live-path-label",children:"Path"}),s.jsx("input",{className:"live-port-input live-path-input",placeholder:"/",value:m,onChange:k=>f(k.target.value),onKeyDown:k=>{k.key==="Enter"&&b()},title:"Open the app at this path (e.g. /docs/node/)"}),s.jsx("button",{className:"live-btn",onClick:b,title:"Open this path",children:"Go"}),s.jsx("span",{className:"live-spacer"}),s.jsx("button",{className:"live-btn",onClick:c,title:"Re-scan listening ports",children:"⟳ Ports"}),i!=null&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"live-btn",onClick:()=>w(k=>k+1),title:"Reload the view",children:"⟳ Reload"}),s.jsx("a",{className:"live-btn",href:j,target:"_blank",rel:"noreferrer",title:"Open in a new tab",children:"↗ Open"})]})]}),i==null?s.jsxs("div",{className:"live-empty",children:[s.jsx("p",{children:"No port selected."}),r.length===0&&s.jsxs("p",{className:"muted",children:["No listening ports detected. Start your app’s container with"," ",s.jsx("code",{children:"-p 3000:3000"})," (or bind it in the outer container) to view it here, then ⟳ Ports."]})]}):s.jsx("div",{className:"live-frame-wrap",children:s.jsx("iframe",{className:"live-frame",src:j,title:`live view on port ${i}`,sandbox:kg},g)})]}):s.jsxs("div",{className:"live-empty",children:[s.jsx("p",{children:"The project container isn’t running."}),s.jsx("p",{className:"muted",children:"Start the project, then run your app to view it here."})]})}const Ng={"global-chat":"Global chat","project-chat":"Project chat","pr-review-chat":"PR review chat",merge:"Merge",worker:"Worker","issue-draft":"Issue draft","prompt-draft":"Prompt draft","script-draft":"Script draft",analysis:"Analysis","log-analysis":"Log analysis",sandbox:"Sandbox"};function ha(e){return Ng[e]||e}function Md({projectId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(""),[o,u]=C.useState(""),[d,m]=C.useState([]),[f,g]=C.useState(new Set),w=C.useCallback(v=>{g(p=>{const c=new Set(p);return c.has(v)?c.delete(v):c.add(v),c})},[]);C.useEffect(()=>{ee("/api/conversations/facets").then(v=>m(v.origins||[])).catch(()=>{})},[]);const S=C.useCallback(()=>{const v=new URLSearchParams;e&&v.set("project",e),o&&v.set("origin",o),h.trim()&&v.set("q",h.trim()),ee(`/api/conversations?${v.toString()}`).then(p=>{r(p.conversations||[]),i(null)}).catch(p=>i(p.message))},[e,o,h]);return C.useEffect(()=>{const v=setTimeout(S,250);return()=>clearTimeout(v)},[S]),s.jsxs("div",{className:"conv-panel",children:[s.jsxs("div",{className:"conv-toolbar",children:[s.jsx("input",{className:"auto-input conv-search",placeholder:"🔍 search all conversations (messages + tool calls)…",value:h,onChange:v=>y(v.target.value)}),s.jsxs("select",{className:"cfg-select conv-origin",value:o,onChange:v=>u(v.target.value),children:[s.jsx("option",{value:"",children:"All origins"}),d.map(v=>s.jsx("option",{value:v,children:ha(v)},v))]})]}),n&&s.jsxs("p",{className:"tab-note err",children:["Failed to load conversations: ",n]}),t===null?s.jsx("p",{className:"tab-note",children:"Loading conversations…"}):t.length===0?s.jsx("p",{className:"tab-note",children:h.trim()||o?"No conversations match.":"No conversations captured yet. They appear here as Claude works across the app."}):s.jsx("ul",{className:"conv-list",children:t.map(v=>{const p=f.has(v.id);return s.jsxs("li",{className:`conv-row${p?" open":""}`,children:[s.jsxs("button",{type:"button",className:"conv-head","aria-expanded":p,onClick:()=>w(v.id),children:[s.jsx("span",{className:`conv-caret${p?" open":""}`,"aria-hidden":!0,children:"▸"}),s.jsx("span",{className:`conv-origin-chip origin-${v.originKind}`,children:ha(v.originKind)}),s.jsx("span",{className:"conv-title",children:v.title||v.firstPrompt||`Conversation #${v.id}`}),s.jsx(Eg,{status:v.status})]}),s.jsxs("div",{className:"conv-byline",children:[v.projectLabel&&s.jsx("span",{children:v.projectLabel}),v.prNumber?s.jsxs("span",{children:[" · PR #",v.prNumber]}):null,s.jsxs("span",{children:[" · ",v.messageCount," msg"]}),v.model&&s.jsxs("span",{children:[" · ",v.model]}),s.jsxs("span",{children:[" · ",v.createdAt]})]}),p&&s.jsx(Rg,{conv:v})]},v.id)})})]})}function Eg({status:e}){const t=e==="running"||e==="idle"?"running":e==="failed"||e==="interrupted"||e==="canceled"?"err":"done";return s.jsx("span",{className:`conv-status-dot ${t}`,title:e})}function Rg({conv:e}){const[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState(null),[o,u]=C.useState(null),[d,m]=C.useState(!1),[f,g]=C.useState(null),w=()=>{m(v=>!v),o===null&&ee(`/api/conversations/${e.id}/chain`).then(v=>u(v.conversations||[])).catch(v=>y(v.message))},S=()=>{g("Starting analysis…"),oe("/api/conversations/analyze",{conversationId:e.id}).then(()=>{g("Analyzing — see the Work tab (⌘K)"),window.dispatchEvent(new CustomEvent("corral:open-work"))}).catch(v=>g(v.message))};return C.useEffect(()=>{const v=new URLSearchParams;n.trim()&&v.set("q",n.trim());const p=setTimeout(()=>{ee(`/api/conversations/${e.id}/messages?${v.toString()}`).then(c=>{r(c.messages||[]),y(null)}).catch(c=>y(c.message))},200);return()=>clearTimeout(p)},[e.id,n]),s.jsxs("div",{className:"conv-detail",children:[s.jsxs("div",{className:"conv-detail-head",children:[s.jsx("span",{className:"conv-detail-title",children:e.title||`Conversation #${e.id}`}),e.parentConversationId?s.jsxs("span",{className:"conv-chain-hint",title:"This conversation was spawned by another",children:["⤴ from #",e.parentConversationId]}):null]}),s.jsxs("div",{className:"conv-detail-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:w,children:d?"Hide chain":"View chain"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:S,title:"Spawn a Claude to analyze this conversation (runs in the Work tab; itself captured)",children:"✦ Analyze with AI"}),f&&s.jsx("span",{className:"conv-analyze-msg",children:f})]}),d&&s.jsx("div",{className:"conv-chain",children:o===null?s.jsx("p",{className:"tab-note",children:"Loading chain…"}):o.length<=1?s.jsx("p",{className:"tab-note",children:"This conversation isn't linked to any others."}):s.jsx("ul",{className:"conv-chain-list",children:o.map(v=>s.jsxs("li",{className:`conv-chain-item${v.id===e.id?" current":""}`,children:[s.jsx("span",{className:`conv-origin-chip origin-${v.originKind}`,children:ha(v.originKind)}),s.jsx("span",{className:"conv-chain-title",children:v.title||`Conversation #${v.id}`}),v.id===e.id&&s.jsx("span",{className:"conv-chain-you",children:"← this one"}),s.jsxs("span",{className:"conv-chain-count",children:[v.messageCount," msg"]})]},v.id))})}),s.jsx("input",{className:"auto-input conv-search",placeholder:"🔍 search within this conversation…",value:n,onChange:v=>i(v.target.value)}),h&&s.jsx("p",{className:"tab-note err",children:h}),t===null?s.jsx("p",{className:"tab-note",children:"Loading…"}):t.length===0?s.jsx("p",{className:"tab-note",children:n.trim()?"No messages match.":"No messages."}):s.jsx("ul",{className:"conv-msgs",children:t.map(v=>s.jsxs("li",{className:`conv-msg role-${v.role}${v.isError?" err":""}`,children:[s.jsx("span",{className:"conv-msg-role",children:v.role}),v.type==="tool_use"?s.jsxs("span",{className:"conv-msg-tool",children:["🔧 ",s.jsx("b",{children:v.toolName})," ",s.jsx("code",{children:v.toolInput})]}):v.type==="tool_result"?s.jsxs("span",{className:"conv-msg-toolresult",children:["↳ ",v.toolResult]}):s.jsx("span",{className:"conv-msg-text",children:v.text})]},v.id))})]})}function Lg({projectId:e}){return s.jsxs("div",{className:"conv-tab",children:[s.jsx("div",{className:"conv-tab-note muted",children:"Captured Claude conversations for this project — host-side chats and the sandbox's own Claude sessions. Searchable; kept per your retention setting even after the project is removed."}),s.jsx(Md,{projectId:e})]})}const Dg=[{key:"files",label:"Files"},{key:"diff",label:"Diff"},{key:"container",label:"Container"},{key:"liveview",label:"Live View"},{key:"mitm",label:"Mitm Proxy"},{key:"firewall",label:"Firewall Log"},{key:"conversations",label:"Conversations"},{key:"config",label:"Config"}],Ag="corral.dockCollapsed",Tg="corral.chatDock",Pg="corral.dockWidth",Og="corral.hostHeight",Mg="corral.chatWidth",Ig=480,Bg=320,$g=420;function Hg({id:e}){const{projects:t,loaded:r}=xd(4e3),n=C.useMemo(()=>t.find(J=>J.id===e),[t,e]),i=(n==null?void 0:n.name)||e,[h,y]=C.useState(null),[o,u]=C.useState(void 0);C.useEffect(()=>{ee(`/p/${e}/config`).then(J=>{y(J.source||null),u(J.repo_id||void 0)}).catch(()=>{})},[e]);const[d,m]=C.useState(null),[f,g]=C.useState("files"),[w,S]=C.useState({files:!0,diff:!1,container:!1,liveview:!1,mitm:!1,firewall:!1,conversations:!1,config:!1}),[v,p]=C.useState(0),c=J=>{g(J),S(Q=>Q[J]?Q:{...Q,[J]:!0}),J==="config"&&p(Q=>Q+1)},[a,l]=it(Ag,!1),[_,j]=C.useState(!a),[b,k]=it(`corral.hostOpen.${e}`,!1),[x,N]=it(`corral.chatOpen.${e}`,!1),[E,L]=it(Tg,"right"),[T,P]=it(Pg,Ig),[B,U]=it(Og,Bg),[K,q]=it(Mg,$g),$=Qs({axis:"x",edge:"start",get:()=>T,min:240,max:()=>Math.round(window.innerWidth*.8),onResize:P}),R=Qs({axis:"y",edge:"start",get:()=>B,min:120,max:()=>Math.round(window.innerHeight*.85),onResize:U}),A=Qs({axis:"x",edge:E==="right"?"start":"end",get:()=>K,min:300,max:()=>Math.round(window.innerWidth*.8),onResize:q}),M=C.useCallback(()=>{l(J=>{const Q=!J;return Q||j(!0),Q})},[l]),O=C.useCallback(()=>k(J=>!J),[k]),W=C.useCallback(()=>N(J=>!J),[N]),[F,z]=C.useState(""),[X,I]=C.useState(!1),D=!!(n!=null&&n.container_up);C.useEffect(()=>{ee(`/p/${e}/dind/status`).then(m).catch(()=>m(null))},[e,D]),C.useEffect(()=>{if(!F)return;D===(F==="starting")&&z("")},[D,F]);const V=C.useCallback(async(J=!1)=>{const Q=J?!1:D;z(Q?"stopping":"starting");try{const re=await je(`/p/${e}/${Q?"stop":"start"}`),ie=await re.json().catch(()=>({}));if(!Q&&re.status===409&&(ie!=null&&ie.ssh_keys_pending)){z(""),I(!0);return}if(re.status>=400)throw new Error((ie==null?void 0:ie.message)||`HTTP ${re.status}`)}catch(re){z(""),alert(`${Q?"stop":"start"} failed: ${re.message}`)}},[e,D]);C.useEffect(()=>{const J=()=>{const re=document.activeElement;if(!re)return!1;const ie=(re.tagName||"").toLowerCase();return ie==="input"||ie==="textarea"||re.isContentEditable||re.classList.contains("xterm-helper-textarea")},Q=re=>{if(!(re.metaKey||re.ctrlKey)||re.altKey||J())return;const ie=(re.key||"").toLowerCase();ie==="j"?(re.preventDefault(),O()):ie==="k"?(re.preventDefault(),W()):ie===";"&&(re.preventDefault(),M())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[O,W,M]);const H=()=>L(J=>J==="left"?"right":"left");return s.jsxs("div",{className:"project-page",children:[s.jsxs("header",{children:[s.jsx(be,{to:"/",className:"back",children:"← All projects"}),s.jsx("h1",{children:i}),h&&h.kind==="pr"&&h.repo_id&&s.jsxs("a",{className:"proj-source-link",href:`/repos/${encodeURIComponent(h.repo_id)}/prs/${h.number}`,title:h.title||`PR #${h.number}`,children:["↩ from PR #",h.number]}),s.jsx("button",{className:`dock-toggle power-toggle${D?" is-up":""}${F||!r?" busy":""}`,type:"button",disabled:!!F||!r,title:"Start or stop this project's container",onClick:()=>V(!1),children:F?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"power-spin",children:"↻"})," ",F==="starting"?"starting…":"stopping…"]}):r?D?"■ Stop":"▶ Start":s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"power-spin",children:"↻"})," …"]})}),s.jsx("button",{className:`dock-toggle${a?"":" on"}`,type:"button",title:"Show/hide the Claude terminal",onClick:M,children:"⌨ Terminal"}),s.jsx("button",{className:`dock-toggle${b?" on":""}`,type:"button",title:"Show/hide a host shell (⌘J)",onClick:O,children:"▂ Host shell"}),s.jsx("button",{className:`dock-toggle${x?" on":""}`,type:"button",title:"Ask Claude — a host claude chat (⌘K)",onClick:W,children:"💬 Ask Claude"})]}),s.jsx(cl,{repoId:o}),d&&(d.cacheName||d.reason)&&(()=>{const J=d.reused&&d.verified==="no",Q=d.reused&&d.verified!=="no",re=J?" stalled":Q?" reused":"";return s.jsxs("div",{className:`dind-banner${re}`,title:"Docker-in-Docker cache reuse for this project",children:[s.jsx("span",{className:"dind-banner-tag",children:"DinD"}),d.cacheName?s.jsxs("span",{className:"dind-banner-cache",children:[d.isRepo?"repo baseline ":"cache ",s.jsx("code",{children:d.cacheName}),d.mode?` · ${d.mode}`:""]}):null,s.jsx("span",{className:`dind-banner-verdict${Q?" on":J?" warn":""}`,children:Q?"✓ reused":J?"⚠ not landed":"○ not reused"}),s.jsx("span",{className:"dind-banner-reason",children:d.reason})]})})(),s.jsxs("div",{className:`project-layout${a?" dock-collapsed":""}`,id:"project-layout",children:[s.jsxs("div",{className:"tab-area",children:[s.jsx("div",{className:"tabs",children:Dg.map(J=>s.jsx("button",{className:`tab-btn${f===J.key?" active":""}`,onClick:()=>c(J.key),children:J.label},J.key))}),s.jsx("div",{id:"tab-files",className:"tab-panel",style:{display:f==="files"?"flex":"none",flex:"1 1 auto",minHeight:0},children:w.files&&s.jsx(lg,{projectId:e})}),s.jsx("div",{id:"tab-diff",className:"tab-panel",style:{display:f==="diff"?"flex":"none",flex:"1 1 auto",minHeight:0},children:w.diff&&s.jsx(ug,{projectId:e})}),s.jsxs("div",{id:"tab-container",className:"tab-panel",style:{display:f==="container"?"flex":"none",flexDirection:"column",flex:"1 1 auto",minHeight:0},children:[(n==null?void 0:n.workspace)&&s.jsxs("p",{className:"container-mount-note",children:["Workspace is mounted at the same path inside the container (not under ",s.jsx("code",{children:"~"}),"):"," ",s.jsx("code",{className:"container-mount-path",title:"Click to copy",onClick:()=>{var J;return(J=navigator.clipboard)==null?void 0:J.writeText(n.workspace)},children:n.workspace})," ","— the shell already starts here."]}),s.jsxs("div",{className:"screen-frame screen-frame-fill",children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"container shell · ",i]}),w.container&&D?s.jsx(Zs,{projectId:e,wsPath:"/container/ws",kind:"container"}):r?s.jsx("p",{className:"empty",children:D?"open to connect":"container not running"}):s.jsx("p",{className:"empty screen-loading",children:"checking status…"})]})]}),s.jsx("div",{id:"tab-liveview",className:"tab-panel",style:{display:f==="liveview"?"flex":"none",flexDirection:"column",flex:"1 1 auto",minHeight:0},children:w.liveview&&s.jsx(jg,{projectId:e,containerUp:!!D})}),s.jsx("div",{id:"tab-mitm",className:"tab-panel",style:{display:f==="mitm"?"block":"none"},children:w.mitm&&s.jsx(bg,{projectId:e,mitmUp:!!(n!=null&&n.mitm_up)})}),s.jsx("div",{id:"tab-firewall",className:"tab-panel",style:{display:f==="firewall"?"block":"none"},children:w.firewall&&s.jsx(Cg,{projectId:e})}),s.jsx("div",{id:"tab-conversations",className:"tab-panel",style:{display:f==="conversations"?"block":"none",flex:"1 1 auto",minHeight:0,overflow:"auto"},children:w.conversations&&s.jsx(Lg,{projectId:e})}),s.jsx("div",{id:"tab-config",className:"tab-panel",style:{display:f==="config"?"block":"none",flex:"1 1 auto",minHeight:0},children:w.config&&s.jsx(hg,{projectId:e,refreshKey:v})})]}),s.jsxs("aside",{className:"term-dock",id:"term-dock",style:{flex:`0 0 ${T}px`},children:[s.jsx("div",{className:"term-dock-handle",ref:$,title:"Drag to resize"}),s.jsxs("div",{className:"screen-frame",children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),i," · Claude"]}),_&&(n!=null&&n.tmux_up)?s.jsx(Zs,{projectId:e,wsPath:"/terminal/ws",kind:"claude"}):r?s.jsx("p",{className:"empty",children:n!=null&&n.tmux_up?"open to connect":"this project isn't running — press ▶ Start above"}):s.jsx("p",{className:"empty screen-loading",children:"checking status…"})]})]})]}),b&&s.jsxs("div",{className:"host-overlay",id:"host-overlay",style:{height:`${B}px`},children:[s.jsx("div",{className:"host-overlay-handle",ref:R,title:"Drag to resize"}),s.jsxs("div",{className:"host-overlay-bar",children:[s.jsxs("span",{children:[s.jsx("i",{className:"screen-dot"}),"host shell · ",i]}),s.jsx("button",{type:"button",title:"Close (⌘J)",onClick:()=>k(!1),children:"✕"})]}),s.jsx("div",{className:"host-overlay-iframe",children:s.jsx(Zs,{projectId:e,wsPath:"/host/ws",kind:"host"})})]}),x&&s.jsxs("div",{className:`chat-panel${E==="left"?" dock-left":""}`,id:"chat-panel",style:{width:`${K}px`},children:[s.jsx("div",{className:"chat-panel-handle",ref:A}),s.jsxs("div",{className:"chat-panel-bar",children:[s.jsxs("span",{children:[s.jsx("i",{className:"screen-dot"}),"ask claude · host"]}),s.jsxs("span",{className:"chat-panel-actions",children:[s.jsx("button",{type:"button",title:"Dock left/right",onClick:H,children:"⇄"}),s.jsx("button",{type:"button",title:"Close (⌘K)",onClick:()=>N(!1),children:"✕"})]})]}),s.jsx("div",{className:"chat-panel-iframe",children:s.jsx(an,{wsPath:`/p/${e}/chat/ws?tools=Read,Grep,Glob`})})]}),X&&s.jsx(nn,{projectId:e,onDone:J=>{I(!1),J&&V(!0)}})]})}function Fg({repoId:e,onMsg:t}){const r=e?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState(0),[o,u]=C.useState(""),[d,m]=C.useState(!1),[f,g]=C.useState(""),[w,S]=C.useState(!1),[v,p]=C.useState(""),c=C.useRef(null);C.useEffect(()=>()=>{var E;return(E=c.current)==null?void 0:E.close()},[]);const a=C.useCallback(()=>{ee(`/api/prompts${r}`).then(E=>i(E.prompts||[])).catch(E=>t({text:E.message,err:!0}))},[r,t]);C.useEffect(()=>{a()},[a]);const l=n[h];if(C.useEffect(()=>{l&&(u(l.effective),m(!1),p(""),g(""))},[l==null?void 0:l.key,l==null?void 0:l.effective]),n.length===0||!l)return null;const _=E=>{y(L=>(L+E+n.length)%n.length)},j=async()=>{await fetch(`/api/prompts/${encodeURIComponent(l.key)}${r}`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({template:o})}).then(E=>E.json()).then(E=>{i(L=>L.map(T=>T.key===E.key?E:T)),t({text:"✓ prompt saved",err:!1})}).catch(E=>t({text:E.message,err:!0}))},b=async()=>{await fetch(`/api/prompts/${encodeURIComponent(l.key)}${r}`,{method:"DELETE",credentials:"same-origin"}).then(E=>E.json()).then(E=>{i(L=>L.map(T=>T.key===E.key?E:T)),t({text:"↺ reset to default",err:!1})}).catch(E=>t({text:E.message,err:!0}))},k=l.key==="worker.boot_guidance",x=()=>{var T;if(!k&&!f.trim())return;(T=c.current)==null||T.close(),S(!0),p("");const E=e?`/api/prompts/draft?repoId=${encodeURIComponent(e)}`:"/api/prompts/draft",L=new WebSocket(hs(E));c.current=L,L.onopen=()=>L.send(JSON.stringify({description:f,key:l.key})),L.onmessage=P=>{let B;try{B=JSON.parse(P.data)}catch{return}B.type==="text"?p(U=>U+B.text):B.type==="tool_use"?p(U=>U+`› ${B.tool} +`):B.type==="error"?p(U=>U+` +⚠ ${B.text||""}`):B.type==="draft"&&B.result&&(u(B.result),m(!0))},L.onclose=()=>{S(!1),c.current=null},L.onerror=()=>p(P=>P+` +⚠ draft connection failed`)},N=n.filter(E=>E.overridden).length;return s.jsxs("section",{className:"prompts-section",children:[s.jsxs("div",{className:"prompts-head",children:[s.jsxs("div",{className:"prompts-title",children:[s.jsx("span",{className:"prompts-icon","aria-hidden":!0,children:"✎"}),s.jsxs("div",{children:[s.jsx("h3",{className:"auto-mgr-h",style:{margin:0},children:"Prompts"}),s.jsxs("p",{className:"prompts-sub",children:["The editable instructions Corral gives Claude — ",n.length," built-in",N>0?`, ${N} modified here`:"","."]})]})]}),s.jsxs("div",{className:"prompts-picker",children:[s.jsx("select",{className:"cfg-select prompts-select",value:h,onChange:E=>y(Number(E.target.value)),"aria-label":"Choose a prompt to edit",children:n.map((E,L)=>s.jsxs("option",{value:L,children:[E.name,E.overridden?" • modified":""]},E.key))}),s.jsxs("div",{className:"prompts-pager",children:[s.jsx("button",{type:"button",className:"carousel-arrow",onClick:()=>_(-1),"aria-label":"Previous prompt",children:"‹"}),s.jsxs("span",{className:"prompts-count",children:[h+1," / ",n.length]}),s.jsx("button",{type:"button",className:"carousel-arrow",onClick:()=>_(1),"aria-label":"Next prompt",children:"›"})]})]})]}),s.jsxs("div",{className:"prompt-card",children:[s.jsxs("div",{className:"prompt-card-head",children:[l.name,s.jsx("span",{className:"auto-scope",children:e?"repo":"global"}),l.overridden&&s.jsx("span",{className:"modified-pill",children:"modified"}),!l.overridden&&l.source!=="default"&&s.jsxs("span",{className:"inherited-pill",children:["from ",l.source]})]}),s.jsxs("p",{className:"prompt-usedwhen",children:["↳ ",l.usedWhen]}),l.slots.length>0&&s.jsxs("div",{className:"prompt-slots",children:[s.jsx("span",{className:"prompt-slots-label",children:"Available:"}),l.slots.map(E=>s.jsx("code",{className:"prompt-slot-chip",children:`{{${E}}}`},E))]}),s.jsx("textarea",{className:"prompt-textarea",rows:8,value:o,onChange:E=>{u(E.target.value),m(!0)}}),s.jsxs("div",{className:"prompt-actions-row",children:[s.jsx("button",{type:"button",className:"auto-btn",disabled:!d,onClick:j,children:"Save"}),s.jsx("button",{type:"button",className:"auto-btn",disabled:!l.overridden,onClick:b,children:"Reset to default"})]}),s.jsxs("details",{className:"prompt-ai",children:[s.jsxs("summary",{children:["✨ Build with AI"," ",s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude, not the sandbox; read-only",children:"host · not sandboxed · read-only"})]}),k&&s.jsxs("p",{className:"prompt-usedwhen",style:{marginTop:0},children:["↳ Recommends a caching recipe for this repo from what we learned booting it",e?"":" (select a repo to ground it in that repo's boot history)"," — reads its captured boot runs + the codebase. Notes below are optional."]}),s.jsx("textarea",{className:"prompt-textarea",rows:2,value:f,onChange:E=>g(E.target.value),placeholder:k?"Optional notes to steer the recommendation…":"Describe what this prompt should do…"}),s.jsx("button",{type:"button",className:"auto-btn",disabled:w||!k&&!f.trim(),onClick:x,children:w?"Drafting…":k?"Recommend from our boot history":"Draft with AI"}),v&&s.jsx("pre",{className:"split-menu-ai-log",children:v})]})]})]})}function Ug({repoId:e,onMsg:t}){const r=e?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState(null),[o,u]=C.useState(""),[d,m]=C.useState(""),[f,g]=C.useState(""),w=C.useCallback(()=>{ee(`/api/prompts/library${r}`).then(a=>i(a.prompts||[])).catch(a=>t==null?void 0:t({text:a.message,err:!0}))},[r,t]);C.useEffect(()=>w(),[w]);function S(){y("new"),u(""),m(""),g("")}function v(a){y(a.id),u(a.name),m(a.template),g(a.description||"")}async function p(){if(!o.trim()||!d.trim()){t==null||t({text:"A name and a template are required.",err:!0});return}try{h==="new"?(await oe("/api/prompts/library",{name:o.trim(),template:d,description:f.trim(),repo:e||void 0}),t==null||t({text:`Saved "${o.trim()}".`,err:!1})):typeof h=="number"&&(await zg(`/api/prompts/library/${h}`,{name:o.trim(),template:d,description:f.trim()}),t==null||t({text:`Updated "${o.trim()}".`,err:!1})),y(null),w()}catch(a){t==null||t({text:`Couldn't save: ${a.message}`,err:!0})}}async function c(a){if(confirm(`Delete the "${a.name}" prompt?`))try{await St(`/api/prompts/library/${a.id}`),w()}catch(l){t==null||t({text:`Couldn't delete: ${l.message}`,err:!0})}}return s.jsxs("section",{className:"promptlib",children:[s.jsxs("div",{className:"promptlib-head",children:[s.jsxs("h3",{className:"auto-mgr-h",style:{margin:0},children:["Saved prompts ",s.jsx("span",{className:"auto-hint",style:{fontWeight:400},children:"— pick these when you start a project or work an issue"})]}),h===null&&s.jsx("button",{type:"button",className:"auto-btn",onClick:S,children:"+ New prompt"})]}),h!==null?s.jsxs("div",{className:"promptlib-editor",children:[s.jsx("input",{className:"auto-input",placeholder:"Name (e.g. Thorough refactor)",value:o,onChange:a=>u(a.target.value)}),s.jsx("input",{className:"auto-input",placeholder:"Short description (optional)",value:f,onChange:a=>g(a.target.value)}),s.jsx("textarea",{className:"auto-input promptlib-template",placeholder:"The prompt text. Use {{repo}}, {{branch}}, {{number}}, {{title}} where the start flow fills them in.",value:d,onChange:a=>m(a.target.value),rows:6}),s.jsxs("div",{className:"promptlib-editor-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:p,children:"Save"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>y(null),children:"Cancel"})]})]}):n.length===0?s.jsx("p",{className:"auto-empty",children:"No saved prompts yet. Create one to reuse it at project or issue start."}):s.jsx("ul",{className:"promptlib-list",children:n.map(a=>s.jsxs("li",{className:"promptlib-item",children:[s.jsxs("div",{className:"promptlib-item-main",children:[s.jsx("span",{className:"promptlib-name",children:a.name}),a.scope==="repo"&&s.jsx("span",{className:"promptlib-scope",children:"this repo"}),a.description&&s.jsx("span",{className:"promptlib-desc",children:a.description}),s.jsx("div",{className:"promptlib-preview",children:a.template})]}),s.jsxs("div",{className:"promptlib-item-actions",children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>v(a),children:"edit"}),s.jsx("button",{type:"button",className:"promptlib-x",title:"Delete",onClick:()=>c(a),children:"×"})]})]},a.id))})]})}function zg(e,t){return fetch(e,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`)})}const Wg=["CORRAL_EVENT","CORRAL_REPO_ID","CORRAL_PR_NUMBER","CORRAL_PR_URL","CORRAL_PR_TITLE","CORRAL_OWNER_NAME","CORRAL_HEAD_SHA"];function Id({script:e,onChange:t}){const r=C.useRef(null),n=C.useRef(null),i=C.useRef(e),[h,y]=C.useState(!1);C.useEffect(()=>{let L=null,T=!1;return Pi().then(P=>{T||!r.current||(L=P.createEditor({parent:r.current,doc:i.current,language:"bash",onChange:B=>{i.current=B,t(B)}}),n.current=L,y(!0))}).catch(()=>y(!1)),()=>{T=!0,L==null||L.destroy(),n.current=null}},[]);const[o,u]=C.useState(null);C.useEffect(()=>{ee("/api/scripts/env").then(u).catch(()=>u(null))},[]);const[d,m]=C.useState(!1),[f,g]=C.useState(null),[w,S]=C.useState(!1),[v,p]=C.useState(""),[c,a]=C.useState(!1),[l,_]=C.useState(""),j=C.useRef(null),b=L=>{var T,P;i.current=L,t(L),(P=(T=n.current)==null?void 0:T.setDoc)==null||P.call(T,L)},k=L=>{if(n.current){b((i.current||"")+L);return}b((i.current||"")+L)},x=async()=>{m(!0),g(null);try{const L=await fetch("/api/actions:test",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"bash",spec:JSON.stringify({script:i.current}),context:{event:"test",vars:{pr_number:"0",pr_url:"https://example/pr/0",pr_title:"Test PR",owner_name:"owner/repo"}}})});g(await L.json())}catch(L){g({status:"error",error:L.message})}finally{m(!1)}},N=()=>{var T;if(!v.trim())return;(T=j.current)==null||T.close(),a(!0),_("");const L=new WebSocket(hs("/api/scripts/draft"));j.current=L,L.onopen=()=>L.send(JSON.stringify({description:v})),L.onmessage=P=>{let B;try{B=JSON.parse(P.data)}catch{return}B.type==="text"?_(U=>U+B.text):B.type==="tool_use"?_(U=>U+`› ${B.tool} +`):B.type==="error"?_(U=>U+` +⚠ ${B.text||""}`):B.type==="draft"&&B.result&&b(B.result)},L.onclose=()=>{a(!1),j.current=null},L.onerror=()=>_(P=>P+` ⚠ draft connection failed`)},E=(o==null?void 0:o.clis)||[];return s.jsxs("div",{className:"bash-editor",children:[s.jsxs("div",{className:"host-callout",children:[s.jsx("div",{className:"host-callout-head",children:"⚠ Runs on your host machine — not the sandbox"}),s.jsx("p",{className:"host-callout-body",children:(o==null?void 0:o.note)||"This script runs on the machine hosting the dashboard, in your login shell, with any CLIs you're already signed in to. There is no sandbox."}),E.length>0&&s.jsxs("div",{className:"host-callout-clis",children:[s.jsx("span",{className:"host-callout-clis-label",children:"Available here:"}),E.map(L=>{const T=L.status==="authed"?`${L.label||L.name} — signed in`:L.status==="unauthed"?`${L.label||L.name} — installed, not signed in`:L.label||L.name;return s.jsxs("span",{className:`cli-pill ${L.status}`,title:T,children:[L.status==="authed"&&s.jsx("span",{className:"cli-mark",children:"✓"}),L.status==="unauthed"&&s.jsx("span",{className:"cli-mark",children:"●"}),L.name,L.status==="unauthed"&&s.jsx("span",{className:"cli-note",children:"not signed in"})]},L.name)})]})]}),s.jsxs("div",{className:"bash-editor-head",children:[s.jsx("span",{className:"bash-editor-label",children:"Script"}),s.jsx("span",{className:"bash-editor-hint",children:"bash · runs on the host"})]}),s.jsx("div",{ref:r,className:"bash-editor-cm"}),!h&&s.jsx("textarea",{className:"bash-editor-ta",rows:10,spellCheck:!1,defaultValue:e,onChange:L=>b(L.target.value),placeholder:`#!/usr/bin/env bash set -euo pipefail @@ -91,7 +91,7 @@ echo "PR $CORRAL_PR_NUMBER approved"`}),s.jsxs("div",{className:"bash-vars",chil set -euo pipefail echo "PR $CORRAL_PR_NUMBER" -`;function Bd({repoId:e}){const t=!!e,r=t?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState({}),[o,u]=C.useState([]),[d,m]=C.useState(null),f=C.useCallback(()=>{ee(`/api/actions${r}`).then(l=>i(l.actions||[])).catch(l=>m({text:l.message,err:!0}))},[r]),g=C.useCallback(()=>{ee("/api/triggers").then(l=>u(l.triggers||[])).catch(()=>{})},[]),w=C.useCallback(()=>{ee("/api/triggers").then(l=>{const _=(l.triggers||[]).map(j=>j.event);Promise.all(_.map(j=>ee(`/api/hooks?event=${encodeURIComponent(j)}${t?`&repo=${encodeURIComponent(e)}`:""}`).then(b=>[j,b.hooks||[]]).catch(()=>[j,[]]))).then(j=>y(Object.fromEntries(j)))})},[t,e]);C.useEffect(()=>{f(),g(),w()},[f,g,w]);const S=l=>n.find(_=>_.id===l),v=async(l,_,j,b)=>{try{const k=await oe("/api/actions",{name:j,kind:_,spec:b,scope:t?"repo":"global",repoId:t?e:void 0});await oe("/api/hooks",{event:l,scope:t?"repo":"global",repoId:t?e:void 0,targetKind:"action",targetId:k.id,enabled:!0}),m({text:"✓ step added",err:!1}),f(),w()}catch(k){m({text:k.message,err:!0})}},p=async(l,_)=>{try{await oe("/api/hooks",{event:l,scope:t?"repo":"global",repoId:t?e:void 0,targetKind:"action",targetId:_,enabled:!0}),m({text:"✓ step added",err:!1}),w()}catch(j){m({text:j.message,err:!0})}},c=n.filter(l=>l.kind==="bash"),a=async(l,_,j)=>{await fetch(`/api/hooks/${l}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),(!t||j==="repo")&&await fetch(`/api/actions/${_}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),f(),w()};return s.jsxs("div",{className:"auto-manager",children:[d&&s.jsx("div",{className:`auto-msg${d.err?" err":""}`,children:d.text}),s.jsx(Fg,{repoId:e,onMsg:m}),s.jsx(Ug,{repoId:e,onMsg:m}),s.jsxs("h3",{className:"auto-mgr-h",children:["Automations",t?" (this repo)":""]}),s.jsx("p",{className:"auto-hint",style:{opacity:.85},children:"Each card is something Corral already does. Add your own steps to run alongside it — a Slack ping when you approve, a script when a project starts, and so on."}),o.map(l=>s.jsx(Vg,{trigger:l,steps:(h[l.event]||[]).filter(_=>_.targetKind==="action"),actionById:S,savedScripts:c,scoped:t,onAdd:(_,j,b)=>v(l.event,_,j,b),onAddExisting:_=>p(l.event,_),onRemove:a},l.event)),s.jsx(Gg,{actions:n,scoped:t,onChanged:()=>{f(),w()}})]})}function Vg({trigger:e,steps:t,actionById:r,savedScripts:n,scoped:i,onAdd:h,onAddExisting:y,onRemove:o}){const[u,d]=C.useState(!1),[m,f]=C.useState(Sr[0].kind),[g,w]=C.useState(""),[S,v]=C.useState(JSON.stringify(Sr[0].starter,null,2)),[p,c]=C.useState(Kg),[a,l]=C.useState("new"),_=b=>{f(b);const k=Sr.find(x=>x.kind===b);v(JSON.stringify((k==null?void 0:k.starter)??{},null,2))},j=()=>{var k;if(m==="bash"&&a!=="new"){y(a),d(!1),l("new");return}const b=m==="bash"?JSON.stringify({script:p}):S;h(m,g.trim()||((k=Sr.find(x=>x.kind===m))==null?void 0:k.label)||m,b),d(!1),w("")};return s.jsxs("div",{className:"trigger-card",children:[s.jsxs("div",{className:"trigger-card-head",children:[s.jsx("span",{className:"trigger-title",children:e.title}),s.jsx("span",{className:"trigger-desc",children:e.description})]}),s.jsxs("ol",{className:"trigger-steps",children:[e.builtin?s.jsxs("li",{className:"trigger-step builtin",children:[s.jsx("span",{className:"trigger-step-ico",children:e.builtinIcon}),e.builtin,s.jsx("span",{className:"builtin-pill",children:"built-in"})]}):s.jsxs("li",{className:"trigger-step builtin muted-step",children:[s.jsx("span",{className:"trigger-step-ico",children:"•"}),e.title.replace(/^When /,"")]}),t.map(b=>{const k=r(b.targetId);return s.jsxs("li",{className:"trigger-step",children:[s.jsx("span",{className:"trigger-step-ico",children:qg(k==null?void 0:k.kind)}),(k==null?void 0:k.name)||`#${b.targetId}`,(!i||b.scope==="repo")&&s.jsx("button",{type:"button",className:"auto-del",onClick:()=>o(b.id,b.targetId,(k==null?void 0:k.scope)||"global"),children:"remove"})]},b.id)})]}),u?s.jsxs("div",{className:"trigger-add",children:[s.jsxs("div",{className:"auto-row",children:[s.jsx("select",{className:"auto-input",value:m,onChange:b=>_(b.target.value),children:Sr.map(b=>s.jsx("option",{value:b.kind,children:b.label},b.kind))}),!(m==="bash"&&a!=="new")&&s.jsx("input",{className:"auto-input",placeholder:"name (optional)",value:g,onChange:b=>w(b.target.value)})]}),m==="bash"&&n.length>0&&s.jsx("div",{className:"auto-row",children:s.jsxs("select",{className:"auto-input",value:a,onChange:b=>l(b.target.value==="new"?"new":Number(b.target.value)),children:[s.jsx("option",{value:"new",children:"✎ Write a new script"}),s.jsx("optgroup",{label:"Saved scripts",children:n.map(b=>s.jsxs("option",{value:b.id,children:[b.name," (",b.scope,")"]},b.id))})]})}),m==="bash"?a==="new"?s.jsx(Id,{script:p,onChange:c}):s.jsx("p",{className:"auto-hint",children:"Uses the saved script — edit it under the Scripts tab."}):s.jsx("textarea",{className:"auto-spec",rows:5,value:S,onChange:b=>v(b.target.value),spellCheck:!1}),(m==="slack"||m==="webhook")&&s.jsxs("p",{className:"auto-hint",children:["Reference secrets as ",s.jsx("code",{children:"{{secret.NAME}}"}),"; the target host must be on the firewall allowlist."]}),s.jsxs("div",{className:"auto-row",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:j,children:"Add step"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:()=>d(!1),children:"Cancel"})]})]}):s.jsx("button",{type:"button",className:"trigger-add-btn",onClick:()=>d(!0),children:"+ Add a step…"})]})}function qg(e){switch(e){case"slack":return"💬";case"webhook":return"🔗";case"bash":return"⚙";case"capability":return"▤";case"claude_prompt":return"✨";default:return"•"}}function Gg({actions:e,scoped:t,onChanged:r}){const n=async i=>{await fetch(`/api/actions/${i}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),r()};return s.jsxs("details",{className:"auto-advanced",children:[s.jsxs("summary",{children:["Advanced · all actions",t?" (this repo + global)":""]}),e.length===0?s.jsx("p",{className:"auto-empty",children:"No actions yet."}):s.jsxs("table",{className:"auto-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Kind"}),s.jsx("th",{children:"Scope"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:e.map(i=>s.jsxs("tr",{children:[s.jsx("td",{children:i.name}),s.jsx("td",{children:s.jsx("code",{children:i.kind})}),s.jsx("td",{children:i.scope}),s.jsx("td",{children:(!t||i.scope==="repo")&&s.jsx("button",{type:"button",className:"auto-del",onClick:()=>n(i.id),children:"delete"})})]},i.id))})]})]})}function Jg({repoId:e}){const[t,r]=C.useState([]),[n,i]=C.useState([]),[h,y]=C.useState(new Set),[o,u]=C.useState(null),[d,m]=C.useState(""),[f,g]=C.useState(""),[w,S]=C.useState(null),[v,p]=C.useState(""),[c,a]=C.useState(!1),l=C.useCallback(()=>{ee(`/api/skills?repo=${encodeURIComponent(e)}`).then(T=>r(T.skills||[])).catch(T=>S({text:T.message,err:!0})),ee("/api/skills?scope=global").then(T=>i(T.skills||[])).catch(()=>{}),ee(`/api/repos/${encodeURIComponent(e)}/skills/effective`).then(T=>y(new Set((T.skills||[]).map(O=>O.name)))).catch(()=>{}),ee(`/api/repos/${encodeURIComponent(e)}/agent-context`).then(T=>{p(T.content||""),a(!1)}).catch(()=>{})},[e]);C.useEffect(()=>l(),[l]);function _(){u("new"),m(""),g(`--- +`;function Bd({repoId:e}){const t=!!e,r=t?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState({}),[o,u]=C.useState([]),[d,m]=C.useState(null),f=C.useCallback(()=>{ee(`/api/actions${r}`).then(l=>i(l.actions||[])).catch(l=>m({text:l.message,err:!0}))},[r]),g=C.useCallback(()=>{ee("/api/triggers").then(l=>u(l.triggers||[])).catch(()=>{})},[]),w=C.useCallback(()=>{ee("/api/triggers").then(l=>{const _=(l.triggers||[]).map(j=>j.event);Promise.all(_.map(j=>ee(`/api/hooks?event=${encodeURIComponent(j)}${t?`&repo=${encodeURIComponent(e)}`:""}`).then(b=>[j,b.hooks||[]]).catch(()=>[j,[]]))).then(j=>y(Object.fromEntries(j)))})},[t,e]);C.useEffect(()=>{f(),g(),w()},[f,g,w]);const S=l=>n.find(_=>_.id===l),v=async(l,_,j,b)=>{try{const k=await oe("/api/actions",{name:j,kind:_,spec:b,scope:t?"repo":"global",repoId:t?e:void 0});await oe("/api/hooks",{event:l,scope:t?"repo":"global",repoId:t?e:void 0,targetKind:"action",targetId:k.id,enabled:!0}),m({text:"✓ step added",err:!1}),f(),w()}catch(k){m({text:k.message,err:!0})}},p=async(l,_)=>{try{await oe("/api/hooks",{event:l,scope:t?"repo":"global",repoId:t?e:void 0,targetKind:"action",targetId:_,enabled:!0}),m({text:"✓ step added",err:!1}),w()}catch(j){m({text:j.message,err:!0})}},c=n.filter(l=>l.kind==="bash"),a=async(l,_,j)=>{await fetch(`/api/hooks/${l}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),(!t||j==="repo")&&await fetch(`/api/actions/${_}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),f(),w()};return s.jsxs("div",{className:"auto-manager",children:[d&&s.jsx("div",{className:`auto-msg${d.err?" err":""}`,children:d.text}),s.jsx(Fg,{repoId:e,onMsg:m}),s.jsx(Ug,{repoId:e,onMsg:m}),s.jsxs("h3",{className:"auto-mgr-h",children:["Automations",t?" (this repo)":""]}),s.jsx("p",{className:"auto-hint",style:{opacity:.85},children:"Each card is something Corral already does. Add your own steps to run alongside it — a Slack ping when you approve, a script when a project starts, and so on."}),o.map(l=>s.jsx(Vg,{trigger:l,steps:(h[l.event]||[]).filter(_=>_.targetKind==="action"),actionById:S,savedScripts:c,scoped:t,onAdd:(_,j,b)=>v(l.event,_,j,b),onAddExisting:_=>p(l.event,_),onRemove:a},l.event)),s.jsx(Gg,{actions:n,scoped:t,onChanged:()=>{f(),w()}})]})}function Vg({trigger:e,steps:t,actionById:r,savedScripts:n,scoped:i,onAdd:h,onAddExisting:y,onRemove:o}){const[u,d]=C.useState(!1),[m,f]=C.useState(Sr[0].kind),[g,w]=C.useState(""),[S,v]=C.useState(JSON.stringify(Sr[0].starter,null,2)),[p,c]=C.useState(Kg),[a,l]=C.useState("new"),_=b=>{f(b);const k=Sr.find(x=>x.kind===b);v(JSON.stringify((k==null?void 0:k.starter)??{},null,2))},j=()=>{var k;if(m==="bash"&&a!=="new"){y(a),d(!1),l("new");return}const b=m==="bash"?JSON.stringify({script:p}):S;h(m,g.trim()||((k=Sr.find(x=>x.kind===m))==null?void 0:k.label)||m,b),d(!1),w("")};return s.jsxs("div",{className:"trigger-card",children:[s.jsxs("div",{className:"trigger-card-head",children:[s.jsx("span",{className:"trigger-title",children:e.title}),s.jsx("span",{className:"trigger-desc",children:e.description})]}),s.jsxs("ol",{className:"trigger-steps",children:[e.builtin?s.jsxs("li",{className:"trigger-step builtin",children:[s.jsx("span",{className:"trigger-step-ico",children:e.builtinIcon}),e.builtin,s.jsx("span",{className:"builtin-pill",children:"built-in"})]}):s.jsxs("li",{className:"trigger-step builtin muted-step",children:[s.jsx("span",{className:"trigger-step-ico",children:"•"}),e.title.replace(/^When /,"")]}),t.map(b=>{const k=r(b.targetId);return s.jsxs("li",{className:"trigger-step",children:[s.jsx("span",{className:"trigger-step-ico",children:qg(k==null?void 0:k.kind)}),(k==null?void 0:k.name)||`#${b.targetId}`,(!i||b.scope==="repo")&&s.jsx("button",{type:"button",className:"auto-del",onClick:()=>o(b.id,b.targetId,(k==null?void 0:k.scope)||"global"),children:"remove"})]},b.id)})]}),u?s.jsxs("div",{className:"trigger-add",children:[s.jsxs("div",{className:"auto-row",children:[s.jsx("select",{className:"auto-input",value:m,onChange:b=>_(b.target.value),children:Sr.map(b=>s.jsx("option",{value:b.kind,children:b.label},b.kind))}),!(m==="bash"&&a!=="new")&&s.jsx("input",{className:"auto-input",placeholder:"name (optional)",value:g,onChange:b=>w(b.target.value)})]}),m==="bash"&&n.length>0&&s.jsx("div",{className:"auto-row",children:s.jsxs("select",{className:"auto-input",value:a,onChange:b=>l(b.target.value==="new"?"new":Number(b.target.value)),children:[s.jsx("option",{value:"new",children:"✎ Write a new script"}),s.jsx("optgroup",{label:"Saved scripts",children:n.map(b=>s.jsxs("option",{value:b.id,children:[b.name," (",b.scope,")"]},b.id))})]})}),m==="bash"?a==="new"?s.jsx(Id,{script:p,onChange:c}):s.jsx("p",{className:"auto-hint",children:"Uses the saved script — edit it under the Scripts tab."}):s.jsx("textarea",{className:"auto-spec",rows:5,value:S,onChange:b=>v(b.target.value),spellCheck:!1}),(m==="slack"||m==="webhook")&&s.jsxs("p",{className:"auto-hint",children:["Reference secrets as ",s.jsx("code",{children:"{{secret.NAME}}"}),"; the target host must be on the firewall allowlist."]}),s.jsxs("div",{className:"auto-row",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:j,children:"Add step"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:()=>d(!1),children:"Cancel"})]})]}):s.jsx("button",{type:"button",className:"trigger-add-btn",onClick:()=>d(!0),children:"+ Add a step…"})]})}function qg(e){switch(e){case"slack":return"💬";case"webhook":return"🔗";case"bash":return"⚙";case"capability":return"▤";case"claude_prompt":return"✨";default:return"•"}}function Gg({actions:e,scoped:t,onChanged:r}){const n=async i=>{await fetch(`/api/actions/${i}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),r()};return s.jsxs("details",{className:"auto-advanced",children:[s.jsxs("summary",{children:["Advanced · all actions",t?" (this repo + global)":""]}),e.length===0?s.jsx("p",{className:"auto-empty",children:"No actions yet."}):s.jsxs("table",{className:"auto-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Kind"}),s.jsx("th",{children:"Scope"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:e.map(i=>s.jsxs("tr",{children:[s.jsx("td",{children:i.name}),s.jsx("td",{children:s.jsx("code",{children:i.kind})}),s.jsx("td",{children:i.scope}),s.jsx("td",{children:(!t||i.scope==="repo")&&s.jsx("button",{type:"button",className:"auto-del",onClick:()=>n(i.id),children:"delete"})})]},i.id))})]})]})}function Jg({repoId:e}){const[t,r]=C.useState([]),[n,i]=C.useState([]),[h,y]=C.useState(new Set),[o,u]=C.useState(null),[d,m]=C.useState(""),[f,g]=C.useState(""),[w,S]=C.useState(null),[v,p]=C.useState(""),[c,a]=C.useState(!1),l=C.useCallback(()=>{ee(`/api/skills?repo=${encodeURIComponent(e)}`).then(T=>r(T.skills||[])).catch(T=>S({text:T.message,err:!0})),ee("/api/skills?scope=global").then(T=>i(T.skills||[])).catch(()=>{}),ee(`/api/repos/${encodeURIComponent(e)}/skills/effective`).then(T=>y(new Set((T.skills||[]).map(P=>P.name)))).catch(()=>{}),ee(`/api/repos/${encodeURIComponent(e)}/agent-context`).then(T=>{p(T.content||""),a(!1)}).catch(()=>{})},[e]);C.useEffect(()=>l(),[l]);function _(){u("new"),m(""),g(`--- name: my-skill description: >- One line on what this does. Use this when - Keep the body a short runbook: the exact commands, the failure to watch for, the fix. Only what the model wouldn't already know. -`)}function j(T){u(T.id),m(T.name),g(T.content)}async function b(){if(!d.trim()||!f.trim()){S({text:"A name and SKILL.md content are required.",err:!0});return}try{o==="new"?await oe("/api/skills",{repo:e,name:d.trim(),content:f}):typeof o=="number"&&await Un(`/api/skills/${o}`,{name:d.trim(),content:f}),u(null),S({text:`Saved "${d.trim()}".`,err:!1}),l()}catch(T){S({text:`Couldn't save: ${T.message}`,err:!0})}}async function k(T){if(confirm(`Delete the "${T.name}" skill?`))try{await St(`/api/skills/${T.id}`),l()}catch(O){S({text:`Couldn't delete: ${O.message}`,err:!0})}}async function x(T){if(confirm(`Promote "${T.name}" to a global skill, reusable across all repos?`))try{await oe(`/api/skills/${T.id}/promote`,{autoAll:!1}),S({text:`Promoted "${T.name}" to global.`,err:!1}),l()}catch(O){S({text:`Couldn't promote: ${O.message}`,err:!0})}}async function N(T,O){try{O==="inherit"?await St(`/api/repos/${encodeURIComponent(e)}/skills/${encodeURIComponent(T.name)}/enabled`):await Un(`/api/repos/${encodeURIComponent(e)}/skills/${encodeURIComponent(T.name)}/enabled`,{enabled:O==="on"}),l()}catch(B){S({text:`Couldn't update: ${B.message}`,err:!0})}}async function E(){try{await Un(`/api/repos/${encodeURIComponent(e)}/agent-context`,{content:v}),a(!1),S({text:"Context saved.",err:!1})}catch(T){S({text:`Couldn't save context: ${T.message}`,err:!0})}}async function L(){if(!(v.trim()&&!confirm("Regenerate this repo's AGENTS.md with AI? The worker's result will replace the current context.")))try{await oe(`/api/repos/${encodeURIComponent(e)}/generate-agents-md`,{}),S({text:"Generating AGENTS.md — watch the Work tab; it'll appear here when done.",err:!1})}catch(T){S({text:`Couldn't start generation: ${T.message}`,err:!0})}}return s.jsxs("div",{className:"reposkills",children:[s.jsx("hr",{className:"repo-settings-sep"}),s.jsx("h3",{className:"repo-settings-h",children:"Skills & context"}),s.jsxs("p",{className:"tab-note",children:["Skills and an ",s.jsx("code",{children:"AGENTS.md"})," that Corral drops into a sandbox started from this repo — so Claude lands with the right capabilities and knowledge for this codebase."]}),w&&s.jsx("div",{className:`auto-msg${w.err?" err":""}`,children:w.text}),s.jsxs("div",{className:"reposkills-head",children:[s.jsx("h4",{className:"reposkills-h4",children:"This repo's skills"}),o===null&&s.jsx("button",{type:"button",className:"auto-btn",onClick:_,children:"+ New skill"})]}),o!==null?s.jsxs("div",{className:"reposkills-editor",children:[s.jsx("input",{className:"auto-input",placeholder:"skill name (letters, digits, - or _)",value:d,onChange:T=>m(T.target.value)}),s.jsx("textarea",{className:"auto-input reposkills-md",placeholder:"SKILL.md — YAML frontmatter (name, description) then the instructions.",value:f,onChange:T=>g(T.target.value),rows:12}),s.jsxs("p",{className:"auto-hint",children:["The ",s.jsx("code",{children:"description"})," is the one line the model matches to decide whether to load this skill. Say what it does ",s.jsx("b",{children:"and"})," name the situation — “Use this when…”. If it overlaps another skill, say which owns which case."]}),s.jsxs("div",{className:"reposkills-editor-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:b,children:"Save skill"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>u(null),children:"Cancel"})]})]}):t.length===0?s.jsx("p",{className:"auto-empty",children:"No skills yet. Add one to give this repo's sandbox extra capabilities."}):s.jsx("ul",{className:"reposkills-list",children:t.map(T=>s.jsxs("li",{className:"reposkills-item",children:[s.jsx("span",{className:"reposkills-name",children:T.name}),s.jsxs("div",{className:"reposkills-item-actions",children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>j(T),children:"edit"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>x(T),title:"Reuse across all repos",children:"promote to global"}),s.jsx("button",{type:"button",className:"reposkills-x",title:"Delete",onClick:()=>k(T),children:"×"})]})]},T.id))}),n.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"reposkills-h4",style:{marginTop:"1.1rem"},children:"Global skills"}),s.jsxs("p",{className:"tab-note",style:{marginTop:0},children:["Shared skills from Automations. ",s.jsx("b",{children:"Inherit"})," follows the skill's default; override it on or off just for this repo."]}),s.jsx("ul",{className:"reposkills-list",children:n.map(T=>{const O=h.has(T.name),B=t.some(F=>F.name===T.name);return s.jsxs("li",{className:"reposkills-item",children:[s.jsxs("span",{className:"reposkills-name",children:[T.name,s.jsx("span",{className:`reposkills-badge${O?" on":""}`,children:B?"overridden by repo skill":O?"injected":"not injected"})]}),s.jsxs("select",{className:"auto-input reposkills-tri","aria-label":`${T.name} for this repo`,value:"",onChange:F=>{const z=F.target.value;z&&N(T,z)},children:[s.jsx("option",{value:"",disabled:!0,children:"set…"}),s.jsxs("option",{value:"inherit",children:["Inherit (default: ",T.autoAll?"on":"off",")"]}),s.jsx("option",{value:"on",children:"On for this repo"}),s.jsx("option",{value:"off",children:"Off for this repo"})]})]},T.id)})})]}),s.jsx(cl,{repoId:e}),s.jsxs("div",{className:"reposkills-head",style:{marginTop:"1.1rem"},children:[s.jsx("h4",{className:"reposkills-h4",children:"AGENTS.md context"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:L,title:"Explore the repo and draft it with AI",children:"Regenerate with AI"})]}),s.jsxs("p",{className:"tab-note",style:{marginTop:0},children:["Added to the sandbox's ",s.jsx("code",{children:"CLAUDE.md"})," (below the repo's own, if any). Use it for standing instructions — conventions, gotchas, where things live. Corral drafts this for you when you add the repo; Regenerate re-runs it."]}),s.jsx("textarea",{className:"auto-input reposkills-md",placeholder:"# Notes for Claude working in this repo…",value:v,onChange:T=>{p(T.target.value),a(!0)},rows:8}),s.jsx("div",{className:"reposkills-editor-actions",children:s.jsx("button",{type:"button",className:"auto-btn",disabled:!c,onClick:E,children:"Save context"})})]})}function Yg(e){const t=[],r=[];for(const n of e.split(` +`)}function j(T){u(T.id),m(T.name),g(T.content)}async function b(){if(!d.trim()||!f.trim()){S({text:"A name and SKILL.md content are required.",err:!0});return}try{o==="new"?await oe("/api/skills",{repo:e,name:d.trim(),content:f}):typeof o=="number"&&await Un(`/api/skills/${o}`,{name:d.trim(),content:f}),u(null),S({text:`Saved "${d.trim()}".`,err:!1}),l()}catch(T){S({text:`Couldn't save: ${T.message}`,err:!0})}}async function k(T){if(confirm(`Delete the "${T.name}" skill?`))try{await St(`/api/skills/${T.id}`),l()}catch(P){S({text:`Couldn't delete: ${P.message}`,err:!0})}}async function x(T){if(confirm(`Promote "${T.name}" to a global skill, reusable across all repos?`))try{await oe(`/api/skills/${T.id}/promote`,{autoAll:!1}),S({text:`Promoted "${T.name}" to global.`,err:!1}),l()}catch(P){S({text:`Couldn't promote: ${P.message}`,err:!0})}}async function N(T,P){try{P==="inherit"?await St(`/api/repos/${encodeURIComponent(e)}/skills/${encodeURIComponent(T.name)}/enabled`):await Un(`/api/repos/${encodeURIComponent(e)}/skills/${encodeURIComponent(T.name)}/enabled`,{enabled:P==="on"}),l()}catch(B){S({text:`Couldn't update: ${B.message}`,err:!0})}}async function E(){try{await Un(`/api/repos/${encodeURIComponent(e)}/agent-context`,{content:v}),a(!1),S({text:"Context saved.",err:!1})}catch(T){S({text:`Couldn't save context: ${T.message}`,err:!0})}}async function L(){if(!(v.trim()&&!confirm("Regenerate this repo's AGENTS.md with AI? The worker's result will replace the current context.")))try{await oe(`/api/repos/${encodeURIComponent(e)}/generate-agents-md`,{}),S({text:"Generating AGENTS.md — watch the Work tab; it'll appear here when done.",err:!1})}catch(T){S({text:`Couldn't start generation: ${T.message}`,err:!0})}}return s.jsxs("div",{className:"reposkills",children:[s.jsx("hr",{className:"repo-settings-sep"}),s.jsx("h3",{className:"repo-settings-h",children:"Skills & context"}),s.jsxs("p",{className:"tab-note",children:["Skills and an ",s.jsx("code",{children:"AGENTS.md"})," that Corral drops into a sandbox started from this repo — so Claude lands with the right capabilities and knowledge for this codebase."]}),w&&s.jsx("div",{className:`auto-msg${w.err?" err":""}`,children:w.text}),s.jsxs("div",{className:"reposkills-head",children:[s.jsx("h4",{className:"reposkills-h4",children:"This repo's skills"}),o===null&&s.jsx("button",{type:"button",className:"auto-btn",onClick:_,children:"+ New skill"})]}),o!==null?s.jsxs("div",{className:"reposkills-editor",children:[s.jsx("input",{className:"auto-input",placeholder:"skill name (letters, digits, - or _)",value:d,onChange:T=>m(T.target.value)}),s.jsx("textarea",{className:"auto-input reposkills-md",placeholder:"SKILL.md — YAML frontmatter (name, description) then the instructions.",value:f,onChange:T=>g(T.target.value),rows:12}),s.jsxs("p",{className:"auto-hint",children:["The ",s.jsx("code",{children:"description"})," is the one line the model matches to decide whether to load this skill. Say what it does ",s.jsx("b",{children:"and"})," name the situation — “Use this when…”. If it overlaps another skill, say which owns which case."]}),s.jsxs("div",{className:"reposkills-editor-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:b,children:"Save skill"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>u(null),children:"Cancel"})]})]}):t.length===0?s.jsx("p",{className:"auto-empty",children:"No skills yet. Add one to give this repo's sandbox extra capabilities."}):s.jsx("ul",{className:"reposkills-list",children:t.map(T=>s.jsxs("li",{className:"reposkills-item",children:[s.jsx("span",{className:"reposkills-name",children:T.name}),s.jsxs("div",{className:"reposkills-item-actions",children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>j(T),children:"edit"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>x(T),title:"Reuse across all repos",children:"promote to global"}),s.jsx("button",{type:"button",className:"reposkills-x",title:"Delete",onClick:()=>k(T),children:"×"})]})]},T.id))}),n.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"reposkills-h4",style:{marginTop:"1.1rem"},children:"Global skills"}),s.jsxs("p",{className:"tab-note",style:{marginTop:0},children:["Shared skills from Automations. ",s.jsx("b",{children:"Inherit"})," follows the skill's default; override it on or off just for this repo."]}),s.jsx("ul",{className:"reposkills-list",children:n.map(T=>{const P=h.has(T.name),B=t.some(U=>U.name===T.name);return s.jsxs("li",{className:"reposkills-item",children:[s.jsxs("span",{className:"reposkills-name",children:[T.name,s.jsx("span",{className:`reposkills-badge${P?" on":""}`,children:B?"overridden by repo skill":P?"injected":"not injected"})]}),s.jsxs("select",{className:"auto-input reposkills-tri","aria-label":`${T.name} for this repo`,value:"",onChange:U=>{const K=U.target.value;K&&N(T,K)},children:[s.jsx("option",{value:"",disabled:!0,children:"set…"}),s.jsxs("option",{value:"inherit",children:["Inherit (default: ",T.autoAll?"on":"off",")"]}),s.jsx("option",{value:"on",children:"On for this repo"}),s.jsx("option",{value:"off",children:"Off for this repo"})]})]},T.id)})})]}),s.jsx(cl,{repoId:e}),s.jsxs("div",{className:"reposkills-head",style:{marginTop:"1.1rem"},children:[s.jsx("h4",{className:"reposkills-h4",children:"AGENTS.md context"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:L,title:"Explore the repo and draft it with AI",children:"Regenerate with AI"})]}),s.jsxs("p",{className:"tab-note",style:{marginTop:0},children:["Added to the sandbox's ",s.jsx("code",{children:"CLAUDE.md"})," (below the repo's own, if any). Use it for standing instructions — conventions, gotchas, where things live. Corral drafts this for you when you add the repo; Regenerate re-runs it."]}),s.jsx("textarea",{className:"auto-input reposkills-md",placeholder:"# Notes for Claude working in this repo…",value:v,onChange:T=>{p(T.target.value),a(!0)},rows:8}),s.jsx("div",{className:"reposkills-editor-actions",children:s.jsx("button",{type:"button",className:"auto-btn",disabled:!c,onClick:E,children:"Save context"})})]})}function Yg(e){const t=[],r=[];for(const n of e.split(` `))if(!(n.startsWith("@@")||n.startsWith("+++")||n.startsWith("---")||n.startsWith("diff ")||n.startsWith("index ")||n.startsWith("new file")||n.startsWith("deleted file")||n.startsWith("similarity ")||n.startsWith("rename ")))if(n.startsWith("+"))r.push(n.slice(1));else if(n.startsWith("-"))t.push(n.slice(1));else{const i=n.startsWith(" ")?n.slice(1):n;t.push(i),r.push(i)}return{original:t.join(` `),modified:r.join(` `)}}const Xg=[{key:"prs",label:"PR Review"},{key:"issues",label:"Issues"},{key:"projects",label:"Projects"},{key:"forensics",label:"Forensics"},{key:"settings",label:"Settings"}];function Qg({id:e}){ds("console");const[t,r]=C.useState("prs"),[n,i]=C.useState(null),h=C.useCallback(()=>{ee("/repos").then(y=>i((y.repos||[]).find(o=>o.id===e)||null)).catch(()=>i(null))},[e]);return C.useEffect(()=>h(),[h]),s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All repos"}),s.jsx("span",{className:"brand-name",style:n!=null&&n.color?{color:n.color}:void 0,children:n?n.name:e}),(n==null?void 0:n.url)&&s.jsx("a",{className:"brand-sub repo-url",href:n.url,target:"_blank",rel:"noreferrer",children:n.url.replace(/^https?:\/\//,"")}),s.jsx(Zg,{repoId:e})]})}),s.jsxs("div",{className:"repo-hub tab-area",children:[s.jsx("div",{className:"tabs",children:Xg.map(y=>s.jsx("button",{className:`tab-btn${t===y.key?" active":""}`,onClick:()=>r(y.key),children:y.label},y.key))}),s.jsx("div",{className:"tab-panel",style:{display:t==="prs"?"block":"none"},children:s.jsx(tv,{repoId:e})}),s.jsx("div",{className:"tab-panel",style:{display:t==="issues"?"block":"none"},children:s.jsx(pv,{repoUrl:n==null?void 0:n.url})}),s.jsx("div",{className:"tab-panel",style:{display:t==="projects"?"block":"none"},children:s.jsx(mv,{repoId:e})}),s.jsx("div",{className:"tab-panel",style:{display:t==="forensics"?"block":"none"},children:s.jsx(fv,{repoId:e})}),s.jsx("div",{className:"tab-panel",style:{display:t==="settings"?"block":"none"},children:s.jsx(dv,{repoId:e,repo:n,onSaved:h})})]})]})}function Zg({repoId:e}){const[t,r]=C.useState(null);return C.useEffect(()=>{ee(`/repos/${encodeURIComponent(e)}/analysis-status`).then(r).catch(()=>{})},[e]),t?t.analyzed?t.upToDate?null:s.jsx("span",{className:"repo-chip warn",children:"⚠ analysis out of date"}):s.jsx("span",{className:"repo-chip warn",children:"⚠ not analyzed"}):null}function ev({decision:e,draft:t}){if(t)return s.jsx("span",{className:"review-badge draft",children:"draft"});switch(e){case"APPROVED":return s.jsx("span",{className:"review-badge approved",children:"✓ approved"});case"CHANGES_REQUESTED":return s.jsx("span",{className:"review-badge changes",children:"✗ changes"});case"REVIEW_REQUIRED":return s.jsx("span",{className:"review-badge required",children:"○ review"});default:return s.jsx("span",{className:"review-badge none",children:"—"})}}function tv({repoId:e}){const{navigate:t}=ur(),[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState([]),[u,d]=C.useState(null),[m,f]=C.useState(""),g=C.useCallback(()=>ee(`/repos/${encodeURIComponent(e)}/prs`).then(x=>o(x.prs||[])).catch(()=>{}),[e]),w=C.useCallback(()=>{ee(`/repos/${encodeURIComponent(e)}/prs/open`).then(x=>{x.available?(n(x.prs||[]),h(null)):(n([]),h(x.reason||"unavailable"))}).catch(x=>h(x.message))},[e]);C.useEffect(()=>{w(),g()},[w,g]);const S=new Map(y.map(x=>[x.number,x])),[v,p]=C.useState(""),[c,a]=C.useState("updated"),[l,_]=C.useState(!1),j=Date.now(),b=(r||[]).filter(x=>!l||!x.isDraft).filter(x=>{const N=v.trim().toLowerCase();return N?String(x.number).includes(N)||x.title.toLowerCase().includes(N)||x.author.toLowerCase().includes(N)||x.labels.some(E=>E.toLowerCase().includes(N)):!0}).sort((x,N)=>{if(c==="number")return N.number-x.number;const E=c==="updated"?"updatedAt":"createdAt";return(N[E]||"").localeCompare(x[E]||"")}),k=()=>{const x=parseInt(m,10);if(!Number.isFinite(x)||x<=0){d("enter a positive PR number");return}t(`/repos/${encodeURIComponent(e)}/prs/${x}`)};return s.jsxs(s.Fragment,{children:[s.jsx(ul,{repoId:e}),u&&s.jsxs("p",{className:"tab-note err",children:["Failed: ",u]}),r===null?s.jsx("p",{className:"tab-note",children:"Loading open PRs…"}):i?s.jsxs("p",{className:"tab-note",children:["Couldn't list open PRs (",i,"). Open a PR by number below."]}):r.length===0?s.jsx("p",{className:"tab-note",children:"No open pull requests on this repo."}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"pr-toolbar",children:[s.jsx("input",{className:"pr-search",type:"search",placeholder:"🔎 filter by #, title, author, label…",value:v,onChange:x=>p(x.target.value)}),s.jsxs("select",{value:c,onChange:x=>a(x.target.value),children:[s.jsx("option",{value:"updated",children:"Recently updated"}),s.jsx("option",{value:"created",children:"Recently created"}),s.jsx("option",{value:"number",children:"PR number"})]}),s.jsxs("label",{className:"pr-toolbar-check",children:[s.jsx("input",{type:"checkbox",checked:l,onChange:x=>_(x.target.checked)}),"hide drafts"]}),s.jsxs("span",{className:"pr-toolbar-count",children:[b.length," of ",r.length]})]}),b.length===0?s.jsxs("p",{className:"tab-note",children:["No PRs match “",v,"”."]}):s.jsx("ul",{className:"pr-list rich",children:b.map(x=>{const N=S.get(x.number);return s.jsx("li",{className:"pr-card",children:s.jsxs(be,{className:"pr-card-link",to:`/repos/${encodeURIComponent(e)}/prs/${x.number}`,children:[s.jsxs("div",{className:"pr-card-top",children:[s.jsx(ev,{decision:x.reviewDecision,draft:x.isDraft}),s.jsxs("span",{className:"pr-card-title",children:[s.jsxs("span",{className:"pr-num",children:["#",x.number]})," ",(N==null?void 0:N.shortSummary)||x.title||"(untitled)"]}),N&&s.jsx("span",{className:"pr-analyzed",title:"Viewed",children:"✓"})]}),s.jsxs("div",{className:"pr-card-meta",children:[x.author&&s.jsxs("span",{className:"pr-meta-author",children:["@",x.author]}),s.jsxs("span",{className:"pr-diffstat",children:[s.jsxs("span",{className:"add",children:["+",x.additions.toLocaleString()]})," ",s.jsxs("span",{className:"del",children:["−",x.deletions.toLocaleString()]})]}),s.jsxs("span",{className:"pr-meta-time",children:["updated ",on(x.updatedAt,j)]}),x.labels.slice(0,4).map(E=>s.jsx("span",{className:"pr-label",children:E},E))]})]})},x.number)})})]}),s.jsxs("div",{className:"pr-manual",children:[s.jsx("span",{className:"pr-manual-h",children:"Open a specific PR (e.g. closed/old):"}),s.jsx("input",{className:"pr-num-input",type:"number",min:"1",placeholder:"PR #",value:m,onChange:x=>f(x.target.value),onKeyDown:x=>x.key==="Enter"&&k()}),s.jsx("button",{type:"button",className:"btn",onClick:k,children:"Open"})]})]})}const sv="This block modifies the file. Claude analysis is unavailable.";function rv({prId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(null),[o,u]=C.useState(0),[d,m]=C.useState(!1),[f,g]=C.useState(!1),w=C.useCallback(()=>{ee(`/prs/${e}/blocks`).then(a=>{r(a.blocks||[]),i(a.status||null),u(0)}).catch(a=>y(a.message))},[e]);C.useEffect(()=>w(),[w]);const S=()=>{m(!0),y(null),oe(`/prs/${e}/enrich`).then(a=>{r(a.blocks||[]),a.status&&i(a.status)}).catch(a=>y(a.message)).finally(()=>m(!1))},v=()=>{g(!0),y(null),oe(`/prs/${e}/rerank`).then(a=>{r(a.blocks||[]),a.status&&i(a.status)}).catch(a=>y(a.message)).finally(()=>g(!1))};if(h)return s.jsxs("p",{className:"tab-note err",children:["Failed to load blocks: ",h]});if(t===null)return s.jsx("p",{className:"tab-note",children:"Loading blocks…"});if(t.length===0)return s.jsx("p",{className:"tab-note",children:"No blocks extracted for this PR."});const p=t.some(a=>a.explanation&&a.explanation!==sv),c=t[Math.min(o,t.length-1)];return s.jsxs("div",{className:"block-carousel",children:[(n==null?void 0:n.stale)&&s.jsxs("div",{className:"rerank-bar",children:[s.jsx("span",{children:"⚠ Block hotness was ranked before the repo's last analysis — the ordering may be out of date."}),s.jsx("button",{type:"button",className:"btn",disabled:f,onClick:v,children:f?"Re-ranking…":"Re-rank blocks"})]}),n&&!n.repoAnalyzed&&s.jsx("div",{className:"rerank-bar",children:s.jsx("span",{children:`⚠ This repo isn't analyzed yet — blocks aren't hotness-ranked. Run "Analyze repo" (Forensics tab) to rank by churn & callgraph.`})}),s.jsxs("div",{className:"enrich-bar",children:[p?s.jsx("span",{className:"enrich-note",children:"✓ AI analysis added — blocks re-ranked by AI risk"}):s.jsx("span",{className:"enrich-note",children:"Blocks ranked by heuristics (churn × callgraph). Add AI analysis to re-rank by an informed risk score (weighs the heuristics against how well-guarded the actual change is):"}),s.jsx("button",{type:"button",className:"btn",disabled:d,onClick:S,children:d?"Analyzing…":p?"Re-run AI":"+ Add AI analysis"})]}),s.jsxs("div",{className:"block-nav",children:[s.jsx("button",{type:"button",disabled:o<=0,onClick:()=>u(o-1),children:"◀"}),s.jsxs("span",{className:"block-pos",children:["Block ",o+1," of ",t.length]}),s.jsx("button",{type:"button",disabled:o>=t.length-1,onClick:()=>u(o+1),children:"▶"}),s.jsx("span",{className:"block-dots",children:t.map((a,l)=>s.jsx("span",{className:`dot${l===o?" on":""}`},l))})]}),s.jsxs("div",{className:"block-card",children:[s.jsxs("div",{className:"block-meta",children:[s.jsxs("span",{className:"block-prio",children:["🔥 Priority ",c.priority]}),s.jsxs("span",{className:"block-loc",children:[c.filePath,":",c.lineStart,"–",c.lineEnd]}),c.isTest&&s.jsx("span",{className:"block-badge",children:"test"}),c.diffHunk&&s.jsx(av,{hunk:c.diffHunk}),c.hotnessScore!=null&&(p?s.jsxs("span",{className:"block-hot",title:"AI risk score (0-100): likelihood this change causes an issue",children:["risk ",Math.round(c.hotnessScore),"/100"]}):s.jsxs("span",{className:"block-hot",title:"heuristic hotness (churn × callgraph)",children:["hotness ",c.hotnessScore.toFixed(1)]}))]}),c.title&&s.jsx("h3",{className:"block-title",children:c.title}),c.diffHunk&&s.jsx(nv,{prId:e,hunk:c.diffHunk,filePath:c.filePath,lineStart:c.lineStart}),c.explanation&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"block-h",children:"What this does"}),s.jsx("p",{children:c.explanation})]}),c.codebaseContext&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"block-h",children:"Codebase context"}),s.jsx("p",{children:c.codebaseContext})]})]})]})}function nv({prId:e,hunk:t,filePath:r,lineStart:n}){const i=C.useRef(null),h=C.useRef(null),y=C.useRef(null),[o,u]=C.useState(!1),[d,m]=C.useState(null),[f,g]=C.useState(null);C.useEffect(()=>{let v=null,p=!1,c=null;const{original:a,modified:l}=Yg(t);return Pi().then(_=>{var b;if(p||!h.current)return;h.current.innerHTML="",v=_.createDiff({parent:h.current,original:a,modified:l,filename:r}),y.current=v.view||null;const j=(b=v.view)==null?void 0:b.dom.querySelector(".cm-scroller");if(j){const k=()=>m(null);j.addEventListener("scroll",k,{passive:!0}),c=()=>j.removeEventListener("scroll",k)}}).catch(()=>!p&&u(!0)),()=>{p=!0,c==null||c(),v==null||v.destroy(),y.current=null}},[t,r]);const w=v=>{const p=y.current,c=i.current;if(!p||!c)return;const a=c.getBoundingClientRect(),l=p.posAtCoords({x:a.left+12,y:v.clientY});if(l==null)return;const _=p.state.doc.lineAt(l).number,j=p.coordsAtPos(l);if(!j)return;const b=j.top-a.top;m(k=>(k==null?void 0:k.cmLine)===_&&Math.abs(k.top-b)<1?k:{cmLine:_,top:b})};if(o)return s.jsx("pre",{className:"diff-pre",children:t});const S=v=>n+(v-1);return s.jsxs("div",{className:"block-diff-wrap",children:[s.jsxs("div",{className:"block-diff-host diff-view",ref:i,onMouseMove:w,onMouseLeave:()=>m(null),children:[s.jsx("div",{className:"diff-body",ref:h}),d&&f==null&&s.jsx("button",{type:"button",className:"line-comment-add",style:{top:`${d.top}px`},title:`Comment on line ${S(d.cmLine)}`,onClick:()=>g(d.cmLine),children:"+"})]}),f!=null&&s.jsx(iv,{prId:e,path:r,line:S(f),onClose:()=>g(null)})]})}function iv({prId:e,path:t,line:r,onClose:n}){const[i,h]=C.useState(""),[y,o]=C.useState(!1),[u,d]=C.useState(null),m=()=>{i.trim()&&(o(!0),d(null),oe(`/prs/${e}/line-comment`,{path:t,line:r,side:"RIGHT",body:i}).then(()=>{d("✓ posted"),setTimeout(n,700)}).catch(f=>d(f.message)).finally(()=>o(!1)))};return s.jsxs("div",{className:"line-comment-box",children:[s.jsxs("div",{className:"line-comment-head",children:["Comment on ",t,":",r,s.jsx("button",{type:"button",className:"line-comment-x",onClick:n,children:"✕"})]}),s.jsx("textarea",{className:"line-comment-body",placeholder:"Leave a review comment on this line…",value:i,autoFocus:!0,onChange:f=>h(f.target.value)}),s.jsxs("div",{className:"line-comment-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:y||!i.trim(),onClick:m,children:y?"Posting…":"Comment"}),u&&s.jsx("span",{className:`line-comment-msg${u.startsWith("✓")?"":" err"}`,children:u})]})]})}const da=new Map;function ov(e){let t=da.get(e);return t||(t=ee(`/prs/${e}/file-stats`).then(r=>r.files||[]),da.set(e,t)),t}function Hc(e){da.delete(e)}function av({hunk:e}){let t=0,r=0;for(const n of e.split(` -`))n.startsWith("+")&&!n.startsWith("+++")?t++:n.startsWith("-")&&!n.startsWith("---")&&r++;return t===0&&r===0?null:s.jsxs("span",{className:"block-diffstat",children:[s.jsxs("span",{className:"add",children:["+",t]})," ",s.jsxs("span",{className:"del",children:["−",r]})]})}function Fc({add:e,del:t}){return e===0&&t===0?null:s.jsxs("span",{className:"ff-chip diffstat",title:"lines added / removed in this PR",children:[s.jsxs("span",{className:"add",children:["+",e.toLocaleString()]})," ",s.jsxs("span",{className:"del",children:["−",t.toLocaleString()]})]})}function lv({stat:e}){if(!(e.totalCommits>0||e.daysOld!=null)){const i=e.newFile?"✨ new file":e.repoAnalyzed?"no history":"not analyzed",h=e.newFile?"added by this PR — no prior history on the base branch":e.repoAnalyzed?"no commit history for this file on the analyzed branch":"run 'Analyze repo' to compute file forensics";return s.jsxs("div",{className:"file-forensics",children:[s.jsx(Fc,{add:e.additions,del:e.deletions}),s.jsx("span",{className:"ff-chip cool",title:h,children:i}),e.refCount>0&&s.jsxs("span",{className:"ff-chip",children:["🔗 ",e.refCount," refs"]})]})}const r=e.authorCount===1,n=e.daysSinceEdit!=null&&e.daysSinceEdit>180;return s.jsxs("div",{className:"file-forensics",children:[s.jsx(Fc,{add:e.additions,del:e.deletions}),s.jsxs("span",{className:"ff-chip",title:"fix commits / total commits",children:["🔧 ",e.fixCommits,"/",e.totalCommits," fixes (",e.fixPct,"%)"]}),s.jsxs("span",{className:`ff-chip${r?" warn":""}`,title:"distinct commit authors",children:["👤 ",e.authorCount," author",e.authorCount===1?"":"s",r?" (sole)":""]}),e.refCount>0&&s.jsxs("span",{className:"ff-chip",title:"other files that call into this file (callgraph)",children:["🔗 ",e.refCount," refs"]}),e.velocityPerWeek>0&&s.jsxs("span",{className:"ff-chip",title:"commits per week over the file's life",children:["⚡ ",e.velocityPerWeek,"/wk"]}),e.daysOld!=null&&s.jsxs("span",{className:"ff-chip",title:"age since first commit",children:["📅 ",e.daysOld,"d old"]}),e.daysSinceEdit!=null&&s.jsxs("span",{className:`ff-chip${n?" cool":""}`,title:"days since last edit",children:["🕐 edited ",e.daysSinceEdit,"d ago",n?" (stale)":""]})]})}function ul({repoId:e,onAnalyzed:t}){var f;const[r,n]=C.useState(null),[i,h]=C.useState(!1),[y,o]=C.useState(null),u=C.useCallback(()=>{ee(`/repos/${encodeURIComponent(e)}/analysis-status`).then(n).catch(()=>{})},[e]);C.useEffect(()=>u(),[u]);const d=()=>{h(!0),o(null),oe(`/repos/${encodeURIComponent(e)}/analyze`).then(()=>{u(),t==null||t()}).catch(g=>o(g.message)).finally(()=>h(!1))};if(!r||r.analyzed&&r.upToDate)return null;if(!r.analyzed)return s.jsxs("div",{className:"analysis-banner",children:[s.jsx("span",{children:"This repo hasn't been analyzed. Run forensics + the callgraph to power hotness ranking and file stats."}),s.jsx("button",{type:"button",className:"btn primary",disabled:i,onClick:d,children:i?"Analyzing…":"Analyze repo"}),y&&s.jsx("span",{className:"tab-note err",children:y})]});const m=((f=r.newCommits)==null?void 0:f.length)||0;return s.jsxs("div",{className:"analysis-banner warn",children:[s.jsxs("div",{className:"analysis-banner-head",children:[s.jsxs("span",{children:["⚠ ",m>0?`${m}${m>=25?"+":""} new commit${m===1?"":"s"}`:"New commits"," ","since analysis (at ",r.analyzedSha,"). Ranking & file stats may be out of date."]}),s.jsx("button",{type:"button",className:"btn",disabled:i,onClick:d,children:i?"Analyzing…":"Re-analyze"})]}),r.newCommits&&r.newCommits.length>0&&s.jsx("ul",{className:"analysis-commits",children:r.newCommits.map(g=>s.jsxs("li",{children:[s.jsx("span",{className:"ac-sha",children:g.sha})," ",g.subject]},g.sha))}),y&&s.jsx("span",{className:"tab-note err",children:y})]})}const Uc=5;function cv({prId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(!1);C.useEffect(()=>{let m=!0;return ov(e).then(f=>m&&r(f)).catch(()=>m&&r([])),()=>{m=!1}},[e]);const h=(t==null?void 0:t.length)??0,y=t&&!n?t.slice(0,Uc):t,o=h-((y==null?void 0:y.length)??0),u=(t||[]).reduce((m,f)=>m+f.additions,0),d=(t||[]).reduce((m,f)=>m+f.deletions,0);return s.jsxs("div",{className:"pr-files",children:[s.jsxs("h3",{className:"pr-files-h",children:["Files changed",t?` (${h})`:"",t&&(u>0||d>0)&&s.jsxs("span",{className:"pr-files-total",children:[s.jsxs("span",{className:"add",children:["+",u.toLocaleString()]})," ",s.jsxs("span",{className:"del",children:["−",d.toLocaleString()]})]})]}),t===null?s.jsx("div",{className:"pr-files-list",children:[0,1,2].map(m=>s.jsxs("div",{className:"pr-file-row skeleton",children:[s.jsx("span",{className:"sk sk-name"}),s.jsx("span",{className:"sk sk-chip"}),s.jsx("span",{className:"sk sk-chip"}),s.jsx("span",{className:"sk sk-chip"})]},m))}):t.length===0?s.jsx("p",{className:"tab-note",children:"No file forensics for this PR."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pr-files-list",children:y.map(m=>s.jsxs("div",{className:"pr-file-row",children:[s.jsx("span",{className:"pr-file-name",title:m.filePath,children:m.filePath}),s.jsx(lv,{stat:m})]},m.filePath))}),h>Uc&&s.jsx("button",{type:"button",className:"pr-files-more",onClick:()=>i(m=>!m),children:n?"Show less":`View ${o} more file${o===1?"":"s"}`})]})]})}function uv({prId:e}){var u;const[t,r]=C.useState(null),[n,i]=C.useState(!1),[h,y]=C.useState(null);C.useEffect(()=>{ee(`/prs/${e}/risk`).then(d=>r(d.risk)).catch(()=>{})},[e]);const o=()=>{i(!0),y(null),oe(`/prs/${e}/analyze`).then(d=>r(d.risk)).catch(d=>y(d.message)).finally(()=>i(!1))};return s.jsxs("div",{className:"risk-card",children:[s.jsxs("div",{className:"risk-head",children:[s.jsx("span",{className:"risk-title",children:"Risk"}),t&&s.jsx("span",{className:`risk-pill ${t.overallRisk}`,children:t.overallRisk}),s.jsx("button",{type:"button",className:"btn",disabled:n,onClick:o,children:n?"Assessing…":t?"Re-assess":"Assess risk"})]}),h&&s.jsxs("p",{className:"tab-note err",children:["Failed: ",h]}),t&&s.jsxs("div",{className:"risk-body",children:[s.jsx("p",{className:"risk-summary",children:t.riskSummary}),t.meat&&s.jsxs("p",{children:[s.jsx("strong",{children:"Change:"})," ",t.meat]}),t.bugImpact&&s.jsxs("p",{children:[s.jsx("strong",{children:"If a bug slips in:"})," ",t.bugImpact]}),t.fixHistory&&s.jsxs("p",{children:[s.jsx("strong",{children:"Fix history:"})," ",t.fixHistory]}),((u=t.fileHealth)==null?void 0:u.length)>0&&s.jsx("ul",{className:"risk-files",children:t.fileHealth.map((d,m)=>s.jsxs("li",{children:[s.jsx("span",{className:`risk-dot ${d.risk}`})," ",d.file," — ",d.insight]},m))})]})]})}const hv=["#e8833a","#a05cff","#37b7c3","#e05c8a","#5ce68a","#e6c34a","#5c8aff","#e6605c","#8ad35c","#c37ad3","#4ac3a0","#d38a5c","#7a9de6","#d3c15c","#5cd3c1"];function dv({repoId:e,repo:t,onSaved:r}){const[n,i]=C.useState((t==null?void 0:t.color)||"#a05cff"),[h,y]=C.useState(!1),[o,u]=C.useState(null);C.useEffect(()=>{t!=null&&t.color&&i(t.color)},[t==null?void 0:t.color]);const d=()=>{y(!0),u(null),oe(`/repos/${encodeURIComponent(e)}/color`,{color:n}).then(()=>{u("saved ✓"),r()}).catch(m=>u(m.message)).finally(()=>y(!1))};return s.jsxs("div",{className:"repo-settings",children:[s.jsx("h3",{className:"repo-settings-h",children:"Label color"}),s.jsx("p",{className:"tab-note",children:"The color used for this repo's label on the Repos and PRs pages."}),s.jsx("div",{className:"color-swatches",children:hv.map(m=>s.jsx("button",{type:"button",className:`color-swatch${n.toLowerCase()===m?" on":""}`,style:{background:m},title:m,onClick:()=>i(m)},m))}),s.jsxs("div",{className:"color-custom",children:[s.jsx("input",{type:"color",value:n.length===7?n:"#a05cff",onChange:m=>i(m.target.value)}),s.jsx("input",{className:"color-hex",type:"text",value:n,spellCheck:!1,onChange:m=>i(m.target.value)}),s.jsx("span",{className:"repo-color-chip",style:{borderColor:n,color:n},children:(t==null?void 0:t.name)||"preview"})]}),s.jsxs("div",{className:"color-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:h,onClick:d,children:h?"Saving…":"Save color"}),o&&s.jsx("span",{className:"tab-note",children:o})]}),s.jsx(Jg,{repoId:e}),s.jsx("hr",{className:"repo-settings-sep"}),s.jsx("h3",{className:"repo-settings-h",children:"Automations"}),s.jsxs("p",{className:"tab-note",children:["Actions and event hooks scoped to this repo — they apply on top of the"," ",s.jsx(be,{to:"/automations",children:"global automations"}),". Built-in behavior always runs first; hooks are additive and best-effort."]}),s.jsx(Bd,{repoId:e})]})}function fv({repoId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(null),[o,u]=C.useState(!1),d=C.useCallback(()=>{ee(`/repos/${encodeURIComponent(e)}/forensics`).then(g=>r(g.files||[])).catch(g=>y(g.message))},[e]);C.useEffect(()=>d(),[d]);const m=C.useCallback(()=>{u(!0),y(null),oe(`/repos/${encodeURIComponent(e)}/analyze`).then(g=>{r(g.files||[]),i({nodes:g.cgNodes||0,edges:g.cgEdges||0,ok:!!g.callgraphOk})}).catch(g=>y(g.message)).finally(()=>u(!1))},[e]),f=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:m,children:o?"Analyzing…":t&&t.length?"Re-analyze":"Analyze repo"}),n&&(n.ok?s.jsxs("span",{className:"cg-stat",children:["Callgraph: ",n.nodes.toLocaleString()," nodes · ",n.edges.toLocaleString()," edges"]}):s.jsx("span",{className:"cg-stat",children:"Callgraph unavailable (churn-only hotness)"}))]});return h?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"tab-actions",children:f}),s.jsxs("p",{className:"tab-note err",children:["Failed: ",h]})]}):t===null?s.jsx("p",{className:"tab-note",children:"Loading…"}):t.length===0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"tab-actions",children:f}),s.jsx("p",{className:"tab-note",children:"Not analyzed yet. Forensics ranks files by churn (commits per day) and fix-commit count to surface the repo's hottest, most bug-prone files."})]}):s.jsxs(s.Fragment,{children:[s.jsx(ul,{repoId:e,onAnalyzed:d}),s.jsx("div",{className:"tab-actions",children:f}),s.jsxs("table",{className:"forensics-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"File"}),s.jsx("th",{children:"Churn"}),s.jsx("th",{children:"Fix / total commits"})]})}),s.jsx("tbody",{children:t.map(g=>s.jsxs("tr",{children:[s.jsx("td",{children:g.filePath}),s.jsx("td",{children:g.churnScore!=null?g.churnScore.toFixed(2):"—"}),s.jsxs("td",{children:[g.fixCommits," / ",g.totalCommits]})]},g.id))})]})]})}function pv({repoUrl:e}){const t=Rd(e),[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState(""),u=Date.now();if(C.useEffect(()=>{if(!t){h("not a GitHub remote"),n([]);return}ee(`/gh/issues?repo=${encodeURIComponent(t)}`).then(f=>{n(f.issues||[]),h(f.available?null:f.reason||"unavailable")}).catch(f=>h(f.message))},[t]),r===null)return s.jsx("p",{className:"tab-note",children:"Loading issues…"});if(i&&r.length===0)return s.jsxs("p",{className:"tab-note",children:["Couldn't list issues (",i,")."]});if(r.length===0)return s.jsx("p",{className:"tab-note",children:"No open issues."});const d=y.trim().toLowerCase(),m=d?r.filter(f=>{var g;return String(f.number).includes(d)||f.title.toLowerCase().includes(d)||(((g=f.author)==null?void 0:g.login)||"").toLowerCase().includes(d)}):r;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"pr-toolbar",children:[s.jsx("input",{className:"pr-search",type:"search",placeholder:"🔎 filter issues by #, title, author…",value:y,onChange:f=>o(f.target.value)}),s.jsxs("span",{className:"pr-toolbar-count",children:[m.length," of ",r.length]})]}),s.jsx("ul",{className:"pr-list",children:m.map(f=>{var g;return s.jsxs("li",{className:"pr-row",children:[s.jsx("div",{className:"pr-head-row",children:s.jsxs("a",{className:"pr-head",href:f.url,target:"_blank",rel:"noreferrer",title:"Open on GitHub",children:[s.jsxs("span",{className:"pr-num",children:["#",f.number]})," ",f.title]})}),s.jsxs("div",{className:"pr-byline",children:[((g=f.author)==null?void 0:g.login)&&s.jsxs("span",{children:["@",f.author.login]}),f.createdAt&&s.jsxs("span",{children:[" · opened ",on(f.createdAt,u)]})]})]},f.number)})})]})}function mv({repoId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null);return C.useEffect(()=>{ee(`/repos/${encodeURIComponent(e)}/projects`).then(h=>r(h.projects||[])).catch(h=>i(h.message))},[e]),n?s.jsxs("p",{className:"tab-note err",children:["Failed to load projects: ",n]}):t===null?s.jsx("p",{className:"tab-note",children:"Loading…"}):t.length===0?s.jsx("p",{className:"tab-note",children:"No Corral sandbox sessions on this repo yet. Projects whose git remote matches this repo appear here — start one from the Repos list."}):s.jsx("ul",{className:"pr-list",children:t.map(h=>s.jsxs("li",{children:[s.jsx(be,{to:`/p/${encodeURIComponent(h.id)}`,children:h.name}),s.jsx("span",{className:"proj-ws",children:h.workspace})]},h.id))})}function gv({prId:e}){const[t,r]=C.useState([]),[n,i]=C.useState([]),[h,y]=C.useState(null),o=C.useCallback(()=>{ee(`/prs/${e}/links`).then(m=>r(m.links||[])).catch(m=>y(m.message)),ee(`/prs/${e}/links/suggest`).then(m=>i(m.suggestions||[])).catch(()=>{})},[e]);C.useEffect(()=>o(),[o]);const u=(m,f)=>{oe(`/prs/${e}/links`,{linkedPrId:m,relationship:f}).then(()=>o()).catch(g=>y(g.message))},d=m=>{fetch(`/prs/${e}/links/${m}`,{method:"DELETE",credentials:"same-origin"}).then(()=>o()).catch(()=>{})};return s.jsxs("div",{className:"linked-prs",children:[s.jsx("h4",{className:"block-h",children:"Linked PRs"}),h&&s.jsx("p",{className:"tab-note err",children:h}),t.length===0&&s.jsx("p",{className:"tab-note",children:"No linked PRs."}),s.jsx("ul",{className:"link-list",children:t.map(m=>s.jsxs("li",{children:[s.jsx("span",{className:"link-rel",children:m.relationship}),s.jsxs("span",{className:"link-tgt",children:["#",m.linkedNumber," ",m.linkedTitle||m.linkedSummary||""]}),s.jsx("button",{type:"button",className:"link-x",title:"Remove link",onClick:()=>d(m.id),children:"✕"})]},m.id))}),n.length>0&&s.jsxs("div",{className:"link-suggest",children:[s.jsx("span",{className:"link-suggest-h",children:"Suggested (shared files):"}),n.map(m=>s.jsxs("span",{className:"link-suggest-item",children:["#",m.number," (",m.overlap,")",s.jsx("button",{type:"button",className:"btn tiny",onClick:()=>u(m.prId,"related"),children:"+ link"})]},m.prId))]})]})}function vv({prId:e,repoId:t,pr:r,repoName:n}){const[i,h]=C.useState(null),[y,o]=C.useState(""),[u,d]=C.useState(!1),[m,f]=C.useState(null),g=S=>{d(!0),f(null),oe(`/prs/${e}/${S}`,{body:y}).then(()=>{f({text:zc(S)+" ✓",err:!1}),h(null),o("")}).catch(v=>f({text:v.message,err:!0})).finally(()=>d(!1))},w=S=>{f(null),h(v=>v===S?null:S)};return s.jsxs("div",{className:"pr-actions",children:[s.jsxs("div",{className:"pr-actions-row",children:[s.jsx("button",{type:"button",className:`btn${i==="approve"?" primary":""}`,onClick:()=>w("approve"),children:"✓ Approve"}),s.jsx("button",{type:"button",className:`btn${i==="comment"?" primary":""}`,onClick:()=>w("comment"),children:"💬 Comment"}),s.jsx("button",{type:"button",className:`btn${i==="request-changes"?" primary":""}`,onClick:()=>w("request-changes"),children:"✗ Request changes"}),s.jsx(_v,{prId:e,repoId:t,pr:r,repoName:n}),m&&s.jsx("span",{className:`pr-actions-msg${m.err?" err":""}`,children:m.text})]}),i?s.jsxs("div",{className:"pr-action-panel col",children:[s.jsx("textarea",{className:"pr-action-body",placeholder:i==="request-changes"?"Describe the changes you're requesting (required)…":i==="approve"?"Optional approval note…":"Comment…",value:y,onChange:S=>o(S.target.value)}),s.jsxs("div",{className:"pr-action-panel",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:u,onClick:()=>g(i),children:u?"Submitting…":`Confirm ${zc(i).toLowerCase()}`}),s.jsx("button",{type:"button",className:"btn",onClick:()=>h(null),children:"Cancel"})]})]}):null]})}function zc(e){switch(e){case"approve":return"Approved";case"comment":return"Commented";case"request-changes":return"Requested changes"}}function Wc(e){return e==="host"?"Merge with host":e==="sandbox"?"Merge with sandbox":"Merge"}const Kc=["squash","merge","rebase"],Vc={squash:"Squash and merge",merge:"Create a merge commit",rebase:"Rebase and merge"};function _v({prId:e,repoId:t,pr:r,repoName:n}){const[i,h]=C.useState("host"),[y,o]=C.useState(null),[u,d]=C.useState(!1),[m,f]=C.useState(!1),[g,w]=C.useState(null),[S,v]=C.useState(null),[p,c]=C.useState(!1),[a,l]=C.useState("");C.useEffect(()=>{ee("/global/config").then(E=>{const L=E.merge_mode;(L==="host"||L==="sandbox"||L==="plain")&&h(L)}).catch(()=>{}),ee(`/repos/${encodeURIComponent(t)}/merge-strategy`).then(E=>{o(E),l(E.effective||"")}).catch(()=>{})},[t]);const _=y&&y.allowed.length?y.allowed:Kc,j=!!y&&!y.preferred&&!y.global_default,b=async E=>{try{await oe(`/repos/${encodeURIComponent(t)}/merge-strategy`,{strategy:E}),o(L=>L&&{...L,preferred:E,effective:E})}catch{}},k=()=>{if(w(null),j){c(!0);return}x(a||(y==null?void 0:y.effective)||"squash")},x=async E=>{c(!1),d(!1),f(!0),w(null);try{if(i==="plain")await oe(`/prs/${e}/merge`,{method:E}),w({text:"Merged ✓",err:!1});else if(i==="host")await oe(`/prs/${e}/merge-host/start`,{}),window.dispatchEvent(new CustomEvent("corral:open-work")),w({text:"Merging on host — see the Work tab (⌘K)",err:!1});else{const L=await ee(`/prs/${e}/merge-prompt`),O=(await oe("/projects/create",{mode:"clone",name:`${n||"pr"}-merge-${r.number}`,repos:[{repoId:t,branch:L.branch||r.headRef||void 0}],source:{kind:"pr",repo_id:t,number:r.number,url:r.githubUrl,title:r.title}})).id;v(O),await oe(`/p/${O}/start`).catch(()=>{}),await je(`/p/${O}/populate-prompt`,{prompt:L.prompt,submit:!0}).catch(()=>{}),await oe(`/prs/${e}/merge-watch`,{projectId:O}).catch(()=>{}),w({text:"Merge sandbox launched",err:!1})}}catch(L){w({text:L.message,err:!0})}finally{f(!1)}},N=i==="host";return s.jsxs("span",{className:"merge-control",children:[s.jsxs("span",{className:"split-btn",children:[s.jsx("button",{type:"button",className:`btn primary split-main${N?" warn":""}`,disabled:m,title:i==="host"?"Rebase & merge on the host (fast — NOT sandboxed)":i==="sandbox"?"Rebase & merge in a one-shot sandbox, then tear it down":"Merge the PR on GitHub (no rebase)",onClick:k,children:m?"Working…":`⑃ ${Wc(i)}`}),s.jsx("button",{type:"button",className:"btn primary split-caret",disabled:m,"aria-label":"Merge options",title:"Choose merge mode & strategy",onClick:()=>d(E=>!E),children:"▾"}),u&&s.jsxs("div",{className:"split-menu",role:"menu",children:[s.jsx("div",{className:"split-menu-head",children:"Mode"}),["host","sandbox","plain"].map(E=>s.jsxs("button",{type:"button",className:`split-menu-item${i===E?" active":""}`,onClick:()=>h(E),children:[Wc(E),E==="host"&&s.jsx("span",{className:"split-menu-scope",children:"not sandboxed"}),E==="plain"&&s.jsx("span",{className:"split-menu-scope",children:"no rebase"})]},E)),s.jsx("div",{className:"split-menu-sep"}),s.jsxs("div",{className:"split-menu-head",children:["Strategy",y&&y.preferred?" · repo default":y&&y.global_default?" · global default":""]}),Kc.map(E=>{const L=_.includes(E),T=(a||(y==null?void 0:y.effective))===E;return s.jsxs("button",{type:"button",className:`split-menu-item${T?" active":""}`,disabled:!L,title:L?"":"Disabled for this repo on GitHub",onClick:()=>{l(E),b(E)},children:[Vc[E],!L&&s.jsx("span",{className:"split-menu-scope",children:"off on GitHub"})]},E)})]})]}),g&&s.jsx("span",{className:`pr-actions-msg${g.err?" err":""}`,children:g.text}),S&&s.jsx("a",{className:"pr-actions-link",href:`/p/${S}/`,title:"Open the merge sandbox",children:"open sandbox ↗"}),p&&s.jsx("div",{className:"merge-ask-backdrop",onClick:()=>c(!1),children:s.jsxs("div",{className:"merge-ask",onClick:E=>E.stopPropagation(),children:[s.jsxs("div",{className:"merge-ask-head",children:["How should ",n||"this repo"," be merged?"]}),s.jsx("p",{className:"muted",children:"Pick the merge method for this repository. It'll be remembered as this repo's default (you can change it later in the ▾ menu). Only methods GitHub allows for the repo are shown."}),s.jsx("div",{className:"merge-ask-options",children:_.map(E=>s.jsx("button",{type:"button",className:"btn",onClick:()=>x(E),children:Vc[E]},E))}),s.jsx("button",{type:"button",className:"merge-ask-cancel",onClick:()=>c(!1),children:"Cancel"})]})})]})}function yv(e,t){return{repo:t||"",branch:e.headRef||"",pr_number:String(e.number),pr_title:e.title||"",pr_url:e.githubUrl||""}}function xv(e,t){return e.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(r,n)=>t[n]??"")}function Sv(e){return`Verify PR #${e.number} ("${e.title||""}") works. You're on its branch. Explore the change, run the relevant tests or the app, and report whether it behaves correctly and any issues you find. The PR is ${e.githubUrl||""}.`}function wv({repoId:e,pr:t,repoName:r}){const[n,i]=C.useState("idle"),[h,y]=C.useState(null),[o,u]=C.useState(null),[d,m]=C.useState(!1),[f,g]=C.useState("default"),[w,S]=C.useState([]),[v,p]=C.useState(null),[c,a]=C.useState(!1),[l,_]=C.useState(""),[j,b]=C.useState(""),[k,x]=C.useState(!1),[N,E]=C.useState(""),L=C.useRef(null);C.useEffect(()=>()=>{var K;return(K=L.current)==null?void 0:K.close()},[]);const T=()=>{var $;if(!j.trim())return;($=L.current)==null||$.close(),x(!0),E("");const K=new WebSocket(hs(`/api/prompts/draft?repoId=${encodeURIComponent(e)}`));L.current=K,K.onopen=()=>K.send(JSON.stringify({description:j})),K.onmessage=R=>{let D;try{D=JSON.parse(R.data)}catch{return}D.type==="text"?E(M=>M+D.text):D.type==="tool_use"?E(M=>M+`› ${D.tool} -`):D.type==="error"?E(M=>M+` -⚠ ${D.text||""}`):D.type==="draft"&&D.result&&_(D.result)},K.onclose=()=>{x(!1),L.current=null},K.onerror=()=>E(R=>R+` -⚠ draft connection failed`)};C.useEffect(()=>{!d||w.length||v!==null||(ee(`/api/prompts?repo=${encodeURIComponent(e)}`).then(K=>{const $=(K.prompts||[]).find(R=>R.key==="pr.verify");$&&(g($.source),p($.effective))}).catch(()=>{}),ee(`/api/prompts/project-start?repo=${encodeURIComponent(e)}`).then(K=>S(K.presets||[])).catch(()=>{}))},[d,e,w.length,v]);const O=()=>c&&l.trim()?l:v?xv(v,yv(t,r)):Sv(t),B=async()=>{m(!1),i("launching"),u(null);try{const K={kind:"pr",repo_id:e,number:t.number,url:t.githubUrl,title:t.title},R=(await oe("/projects/create",{mode:"clone",name:`${r||"pr"}-verify-${t.number}`,repos:[{repoId:e,branch:t.headRef||void 0}],source:K})).id;y(R),await oe(`/p/${R}/start`).catch(()=>{}),await je(`/p/${R}/populate-prompt`,{prompt:O(),submit:!0}).catch(()=>{}),i("done")}catch(K){u(K.message),i("err")}};if(n==="done"&&h)return s.jsx("a",{className:"dock-toggle",href:`/p/${h}/`,title:"Open the verify project",children:"✓ verifying → open project"});const F=n==="launching"?"Launching…":n==="err"?`⚠ ${o}`:"▶ Verify in sandbox",z=c?"custom prompt":v?`${f} prompt`:"default verify prompt";return s.jsxs("div",{className:"split-btn",children:[s.jsx("button",{type:"button",className:"dock-toggle split-main",disabled:n==="launching",title:"Create a sandbox project on this PR's branch and auto-start Claude to verify it (runs in the background)",onClick:B,children:F}),s.jsx("button",{type:"button",className:"dock-toggle split-caret",disabled:n==="launching",title:"Choose which prompt to launch with","aria-label":"Choose prompt",onClick:()=>m(K=>!K),children:"▾"}),d&&s.jsxs("div",{className:"split-menu",role:"menu",children:[s.jsxs("div",{className:"split-menu-head",children:["Launch prompt · ",z]}),s.jsx("button",{type:"button",className:`split-menu-item${!v&&!c?" active":""}`,onClick:()=>{p(null),a(!1)},children:"Built-in verify prompt"}),w.map(K=>s.jsxs("button",{type:"button",className:`split-menu-item${v===K.template&&!c?" active":""}`,onClick:()=>{p(K.template),a(!1)},children:[K.name," ",s.jsx("span",{className:"split-menu-scope",children:K.scope})]},K.id)),s.jsx("div",{className:"split-menu-sep"}),s.jsx("button",{type:"button",className:`split-menu-item${c?" active":""}`,onClick:()=>{a(!0),l||_(O())},children:"✎ Customize prompt…"}),c&&s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"split-menu-textarea",rows:6,value:l,onChange:K=>_(K.target.value),placeholder:"Prompt to send when the sandbox starts…"}),s.jsxs("div",{className:"split-menu-ai",children:[s.jsxs("div",{className:"split-menu-ai-head",children:["✨ Build with AI",s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude, not the sandbox; read-only tools",children:"host · not sandboxed · read-only"})]}),s.jsx("textarea",{className:"split-menu-textarea",rows:2,value:j,onChange:K=>b(K.target.value),placeholder:"Describe what this prompt should do — e.g. 'review the diff, run the test suite, and summarize risks'"}),s.jsx("button",{type:"button",className:"dock-toggle",style:{marginLeft:0},disabled:k||!j.trim(),onClick:T,children:k?"Drafting…":"Draft with AI"}),N&&s.jsx("pre",{className:"split-menu-ai-log",children:N})]})]})]})]})}function fo({text:e}){const[t,r]=C.useState(!1),n=e.length>600;return s.jsxs("div",{className:`pr-desc-body-wrap${n&&!t?" clamped":""}`,children:[s.jsx("div",{className:"pr-desc-body markdown",dangerouslySetInnerHTML:{__html:jr(e)}}),n&&s.jsx("button",{type:"button",className:"pr-desc-more",onClick:()=>r(i=>!i),children:t?"Show less":"Show more"})]})}function bv({prId:e,body:t}){const[r,n]=C.useState([]),[i,h]=C.useState(0);C.useEffect(()=>{let u=!0;return ee(`/prs/${e}/issues`).then(d=>u&&n(d.issues||[])).catch(()=>u&&n([])),()=>{u=!1}},[e]);const y=(t||"").trim();if(!y&&r.length===0)return null;if(r.length===0)return s.jsxs("div",{className:"pr-desc",children:[s.jsx("div",{className:"pr-desc-head",children:"Description"}),y?s.jsx(fo,{text:y}):s.jsx("p",{className:"pr-desc-empty",children:"No description."})]});const o=i>0?r[i-1]:null;return s.jsxs("div",{className:"pr-desc",children:[s.jsxs("div",{className:"pr-desc-tabs",role:"tablist",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":i===0,className:`pr-desc-tab${i===0?" active":""}`,onClick:()=>h(0),children:"Description"}),r.map((u,d)=>s.jsxs("button",{type:"button",role:"tab","aria-selected":i===d+1,className:`pr-desc-tab${i===d+1?" active":""}`,onClick:()=>h(d+1),title:u.title||`Issue #${u.number}`,children:["Issue #",u.number]},u.number))]}),o?s.jsxs("div",{className:"pr-desc-issue",children:[s.jsxs("div",{className:"pr-desc-issue-head",children:[s.jsxs("span",{className:"pr-desc-issue-title",children:["#",o.number," ",o.title||""]}),o.state&&s.jsx("span",{className:"pr-state",children:o.state}),o.url&&s.jsx("a",{className:"pr-desc-issue-link",href:o.url,target:"_blank",rel:"noreferrer",children:"view on GitHub ↗"}),o.source==="branch"&&s.jsx("span",{className:"pr-desc-issue-src",title:"Linked via the PR's branch name, not an official 'Closes #N' reference",children:"from branch name"})]}),(o.body||"").trim()?s.jsx(fo,{text:(o.body||"").trim()}):s.jsx("p",{className:"pr-desc-empty",children:"No issue description."})]}):y?s.jsx(fo,{text:y}):s.jsx("p",{className:"pr-desc-empty",children:"No description."})]})}function Cv({prId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState(!1),[o,u]=C.useState(null),d=()=>{ee(`/prs/${e}/notes`).then(g=>r(g.notes||[])).catch(g=>u(g.message))};C.useEffect(d,[e]);const m=()=>{n.trim()&&(y(!0),u(null),oe(`/prs/${e}/notes`,{body:n}).then(()=>{i(""),d()}).catch(g=>u(g.message)).finally(()=>y(!1)))},f=g=>{St(`/prs/${e}/notes/${g}`).then(d).catch(w=>u(w.message))};return s.jsxs("div",{className:"pr-notes-panel",children:[s.jsxs("div",{className:"pr-notes-head",children:["🗒 Notes ",s.jsx("span",{className:"pr-notes-sub",children:"private · local only, never posted to GitHub"})]}),s.jsxs("div",{className:"pr-notes-add",children:[s.jsx("textarea",{className:"pr-notes-input",rows:2,placeholder:"Add a private note about this PR…",value:n,onChange:g=>i(g.target.value),onKeyDown:g=>{(g.metaKey||g.ctrlKey)&&g.key==="Enter"&&m()}}),s.jsx("button",{type:"button",className:"btn primary",disabled:h||!n.trim(),onClick:m,children:h?"Saving…":"Add note"})]}),o&&s.jsx("p",{className:"tab-note err",children:o}),t===null?s.jsx("p",{className:"tab-note",children:"Loading notes…"}):t.length===0?s.jsx("p",{className:"pr-notes-empty",children:"No notes yet."}):s.jsx("ul",{className:"pr-notes-list",children:t.map(g=>s.jsxs("li",{className:"pr-note",children:[s.jsx("div",{className:"pr-note-body",children:g.body}),s.jsxs("div",{className:"pr-note-meta",children:[g.author?`${g.author} · `:"",g.createdAt,s.jsx("button",{type:"button",className:"pr-note-del",title:"Delete note",onClick:()=>f(g.id),children:"✕"})]})]},g.id))})]})}function kv({repoId:e,number:t}){ds("console");const[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState(null),[u,d]=C.useState(0),[m,f]=C.useState(!1),[g,w]=C.useState(!1),[S,v]=C.useState(!1),[p,c]=C.useState(!1),[a,l]=C.useState(!1),_=()=>{l(!0),o(null),oe(`/repos/${encodeURIComponent(e)}/prs/fetch`,{number:t}).then(j=>{h(j.pr),Hc(j.pr.id),d(b=>b+1)}).catch(j=>o(j.message)).finally(()=>l(!1))};return C.useEffect(()=>{ee("/repos").then(j=>n((j.repos||[]).find(b=>b.id===e)||null)).catch(()=>{})},[e]),C.useEffect(()=>{let j=!0;return ee(`/repos/${encodeURIComponent(e)}/prs`).then(b=>{const k=(b.prs||[]).find(x=>x.number===t);if(k){j&&h(k);return}return oe(`/repos/${encodeURIComponent(e)}/prs/fetch`,{number:t}).then(x=>j&&h(x.pr))}).catch(b=>j&&o(b.message)),()=>{j=!1}},[e,t]),s.jsxs(s.Fragment,{children:[s.jsxs("header",{className:"console-header",children:[s.jsxs("div",{className:"brand",children:[s.jsxs(be,{to:`/repos/${encodeURIComponent(e)}`,className:"back",children:["← ",r?r.name:"repo"]}),s.jsxs("span",{className:"brand-name",children:["#",t," ",(i==null?void 0:i.shortSummary)||(i==null?void 0:i.title)||""]}),(i==null?void 0:i.state)&&s.jsx("span",{className:"pr-state",children:i.state}),(i==null?void 0:i.githubUrl)&&s.jsx("a",{className:"brand-sub",href:i.githubUrl,target:"_blank",rel:"noreferrer",children:"view on GitHub ↗"})]}),i&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"dock-toggle",disabled:a,title:"Re-pull this PR from GitHub (description, diff) and re-extract blocks",onClick:_,children:a?"Refreshing…":"↻ Refresh from GitHub"}),s.jsx("button",{type:"button",className:`dock-toggle${S?" on":""}`,title:"Link this PR to related PRs",onClick:()=>v(j=>!j),children:"🔗 Linked PRs"}),s.jsx("button",{type:"button",className:`dock-toggle${p?" on":""}`,title:"Private notes on this PR — local only, never posted to GitHub",onClick:()=>c(j=>!j),children:"🗒 Notes"}),s.jsx(wv,{repoId:e,pr:i,repoName:r==null?void 0:r.name}),s.jsx("button",{type:"button",className:"dock-toggle",title:"Start a sandbox project on this PR's branch (opens the create dialog)",onClick:()=>w(!0),children:"⧉ Start project"}),s.jsx("button",{type:"button",className:`dock-toggle${m?" on":""}`,title:"Ask Claude about this PR — a host claude chat",onClick:()=>f(j=>!j),children:"💬 Ask Claude"})]})]}),s.jsx(cl,{repoId:e}),s.jsxs("div",{className:"pr-review-page",children:[s.jsxs("div",{className:"pr-experimental-note",children:["⚠ ",s.jsx("strong",{children:"Experimental — a gauge, not a substitute for review."})," This analysis is an aid to help you orient quickly; it can miss things and be wrong. Don’t rely on it in place of reading the diff and your own judgment."]}),i&&S&&s.jsx("div",{className:"pr-links-panel",children:s.jsx(gv,{prId:i.id})}),i&&p&&s.jsx(Cv,{prId:i.id}),i&&s.jsx(vv,{prId:i.id,repoId:e,pr:i,repoName:r==null?void 0:r.name}),y?s.jsxs("p",{className:"tab-note err",children:["Failed to load PR #",t,": ",y]}):i?s.jsxs(s.Fragment,{children:[s.jsx(ul,{repoId:e,onAnalyzed:()=>{Hc(i.id),d(j=>j+1)}}),s.jsx(bv,{prId:i.id,body:i.body}),s.jsxs("div",{className:"pr-top",children:[s.jsx("div",{className:"pr-top-left",children:s.jsx(uv,{prId:i.id},`risk-${u}`)}),s.jsx("div",{className:"pr-top-right",children:s.jsx(cv,{prId:i.id},`ff-${u}`)})]}),s.jsx(rv,{prId:i.id},`bc-${u}`)]}):s.jsxs("p",{className:"tab-note",children:["Loading PR #",t,"…"]})]}),i&&m&&s.jsxs("div",{className:"chat-panel",id:"chat-panel",children:[s.jsxs("div",{className:"chat-panel-bar",children:[s.jsxs("span",{children:[s.jsx("i",{className:"screen-dot"}),"ask claude · PR #",t]}),s.jsx("span",{className:"chat-panel-actions",children:s.jsx("button",{type:"button",title:"Close",onClick:()=>f(!1),children:"✕"})})]}),s.jsx("div",{className:"chat-panel-iframe",children:s.jsx(an,{wsPath:`/prs/${i.id}/chat/ws`})})]}),i&&g&&s.jsx(ll,{presetRepoId:e,presetBranch:i.headRef,presetName:`${(r==null?void 0:r.name)||"pr"}-pr-${t}`,onClose:()=>w(!1)})]})}function fs(e){return e.replace(/^.*\//,"")}const qc=Array.from({length:25},(e,t)=>t);function Gc(e){return e===0||e===24?"12am":e===12?"12pm":e<12?`${e}am`:`${e-12}pm`}function jv(){ds("console");const e=wd(),[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(""),[o,u]=C.useState(""),[d,m]=C.useState([]),[f,g]=C.useState({}),[w,S]=C.useState({host:"",kind:"header",name:"",value:""}),[v,p]=C.useState({}),[c,a]=C.useState(""),[l,_]=C.useState([]),[j,b]=C.useState(!1),[k,x]=C.useState(!1),[N,E]=C.useState(""),[L,T]=C.useState(""),[O,B]=C.useState(""),[F,z]=C.useState(""),[K,$]=C.useState(""),[R,D]=C.useState(!1),[M,P]=C.useState(!0),[U,Y]=C.useState(!0),[H,J]=C.useState(""),[I,A]=C.useState("host"),[q,W]=C.useState(!0),[X,Q]=C.useState(""),[re,ie]=C.useState(null),he=G=>G.split(` -`).map(te=>te.trim()).filter(Boolean),Ce=C.useCallback(G=>{ee("/global/config").then(te=>{r(te),y((te.monitor_hosts||[]).join(` +`))n.startsWith("+")&&!n.startsWith("+++")?t++:n.startsWith("-")&&!n.startsWith("---")&&r++;return t===0&&r===0?null:s.jsxs("span",{className:"block-diffstat",children:[s.jsxs("span",{className:"add",children:["+",t]})," ",s.jsxs("span",{className:"del",children:["−",r]})]})}function Fc({add:e,del:t}){return e===0&&t===0?null:s.jsxs("span",{className:"ff-chip diffstat",title:"lines added / removed in this PR",children:[s.jsxs("span",{className:"add",children:["+",e.toLocaleString()]})," ",s.jsxs("span",{className:"del",children:["−",t.toLocaleString()]})]})}function lv({stat:e}){if(!(e.totalCommits>0||e.daysOld!=null)){const i=e.newFile?"✨ new file":e.repoAnalyzed?"no history":"not analyzed",h=e.newFile?"added by this PR — no prior history on the base branch":e.repoAnalyzed?"no commit history for this file on the analyzed branch":"run 'Analyze repo' to compute file forensics";return s.jsxs("div",{className:"file-forensics",children:[s.jsx(Fc,{add:e.additions,del:e.deletions}),s.jsx("span",{className:"ff-chip cool",title:h,children:i}),e.refCount>0&&s.jsxs("span",{className:"ff-chip",children:["🔗 ",e.refCount," refs"]})]})}const r=e.authorCount===1,n=e.daysSinceEdit!=null&&e.daysSinceEdit>180;return s.jsxs("div",{className:"file-forensics",children:[s.jsx(Fc,{add:e.additions,del:e.deletions}),s.jsxs("span",{className:"ff-chip",title:"fix commits / total commits",children:["🔧 ",e.fixCommits,"/",e.totalCommits," fixes (",e.fixPct,"%)"]}),s.jsxs("span",{className:`ff-chip${r?" warn":""}`,title:"distinct commit authors",children:["👤 ",e.authorCount," author",e.authorCount===1?"":"s",r?" (sole)":""]}),e.refCount>0&&s.jsxs("span",{className:"ff-chip",title:"other files that call into this file (callgraph)",children:["🔗 ",e.refCount," refs"]}),e.velocityPerWeek>0&&s.jsxs("span",{className:"ff-chip",title:"commits per week over the file's life",children:["⚡ ",e.velocityPerWeek,"/wk"]}),e.daysOld!=null&&s.jsxs("span",{className:"ff-chip",title:"age since first commit",children:["📅 ",e.daysOld,"d old"]}),e.daysSinceEdit!=null&&s.jsxs("span",{className:`ff-chip${n?" cool":""}`,title:"days since last edit",children:["🕐 edited ",e.daysSinceEdit,"d ago",n?" (stale)":""]})]})}function ul({repoId:e,onAnalyzed:t}){var f;const[r,n]=C.useState(null),[i,h]=C.useState(!1),[y,o]=C.useState(null),u=C.useCallback(()=>{ee(`/repos/${encodeURIComponent(e)}/analysis-status`).then(n).catch(()=>{})},[e]);C.useEffect(()=>u(),[u]);const d=()=>{h(!0),o(null),oe(`/repos/${encodeURIComponent(e)}/analyze`).then(()=>{u(),t==null||t()}).catch(g=>o(g.message)).finally(()=>h(!1))};if(!r||r.analyzed&&r.upToDate)return null;if(!r.analyzed)return s.jsxs("div",{className:"analysis-banner",children:[s.jsx("span",{children:"This repo hasn't been analyzed. Run forensics + the callgraph to power hotness ranking and file stats."}),s.jsx("button",{type:"button",className:"btn primary",disabled:i,onClick:d,children:i?"Analyzing…":"Analyze repo"}),y&&s.jsx("span",{className:"tab-note err",children:y})]});const m=((f=r.newCommits)==null?void 0:f.length)||0;return s.jsxs("div",{className:"analysis-banner warn",children:[s.jsxs("div",{className:"analysis-banner-head",children:[s.jsxs("span",{children:["⚠ ",m>0?`${m}${m>=25?"+":""} new commit${m===1?"":"s"}`:"New commits"," ","since analysis (at ",r.analyzedSha,"). Ranking & file stats may be out of date."]}),s.jsx("button",{type:"button",className:"btn",disabled:i,onClick:d,children:i?"Analyzing…":"Re-analyze"})]}),r.newCommits&&r.newCommits.length>0&&s.jsx("ul",{className:"analysis-commits",children:r.newCommits.map(g=>s.jsxs("li",{children:[s.jsx("span",{className:"ac-sha",children:g.sha})," ",g.subject]},g.sha))}),y&&s.jsx("span",{className:"tab-note err",children:y})]})}const Uc=5;function cv({prId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(!1);C.useEffect(()=>{let m=!0;return ov(e).then(f=>m&&r(f)).catch(()=>m&&r([])),()=>{m=!1}},[e]);const h=(t==null?void 0:t.length)??0,y=t&&!n?t.slice(0,Uc):t,o=h-((y==null?void 0:y.length)??0),u=(t||[]).reduce((m,f)=>m+f.additions,0),d=(t||[]).reduce((m,f)=>m+f.deletions,0);return s.jsxs("div",{className:"pr-files",children:[s.jsxs("h3",{className:"pr-files-h",children:["Files changed",t?` (${h})`:"",t&&(u>0||d>0)&&s.jsxs("span",{className:"pr-files-total",children:[s.jsxs("span",{className:"add",children:["+",u.toLocaleString()]})," ",s.jsxs("span",{className:"del",children:["−",d.toLocaleString()]})]})]}),t===null?s.jsx("div",{className:"pr-files-list",children:[0,1,2].map(m=>s.jsxs("div",{className:"pr-file-row skeleton",children:[s.jsx("span",{className:"sk sk-name"}),s.jsx("span",{className:"sk sk-chip"}),s.jsx("span",{className:"sk sk-chip"}),s.jsx("span",{className:"sk sk-chip"})]},m))}):t.length===0?s.jsx("p",{className:"tab-note",children:"No file forensics for this PR."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pr-files-list",children:y.map(m=>s.jsxs("div",{className:"pr-file-row",children:[s.jsx("span",{className:"pr-file-name",title:m.filePath,children:m.filePath}),s.jsx(lv,{stat:m})]},m.filePath))}),h>Uc&&s.jsx("button",{type:"button",className:"pr-files-more",onClick:()=>i(m=>!m),children:n?"Show less":`View ${o} more file${o===1?"":"s"}`})]})]})}function uv({prId:e}){var u;const[t,r]=C.useState(null),[n,i]=C.useState(!1),[h,y]=C.useState(null);C.useEffect(()=>{ee(`/prs/${e}/risk`).then(d=>r(d.risk)).catch(()=>{})},[e]);const o=()=>{i(!0),y(null),oe(`/prs/${e}/analyze`).then(d=>r(d.risk)).catch(d=>y(d.message)).finally(()=>i(!1))};return s.jsxs("div",{className:"risk-card",children:[s.jsxs("div",{className:"risk-head",children:[s.jsx("span",{className:"risk-title",children:"Risk"}),t&&s.jsx("span",{className:`risk-pill ${t.overallRisk}`,children:t.overallRisk}),s.jsx("button",{type:"button",className:"btn",disabled:n,onClick:o,children:n?"Assessing…":t?"Re-assess":"Assess risk"})]}),h&&s.jsxs("p",{className:"tab-note err",children:["Failed: ",h]}),t&&s.jsxs("div",{className:"risk-body",children:[s.jsx("p",{className:"risk-summary",children:t.riskSummary}),t.meat&&s.jsxs("p",{children:[s.jsx("strong",{children:"Change:"})," ",t.meat]}),t.bugImpact&&s.jsxs("p",{children:[s.jsx("strong",{children:"If a bug slips in:"})," ",t.bugImpact]}),t.fixHistory&&s.jsxs("p",{children:[s.jsx("strong",{children:"Fix history:"})," ",t.fixHistory]}),((u=t.fileHealth)==null?void 0:u.length)>0&&s.jsx("ul",{className:"risk-files",children:t.fileHealth.map((d,m)=>s.jsxs("li",{children:[s.jsx("span",{className:`risk-dot ${d.risk}`})," ",d.file," — ",d.insight]},m))})]})]})}const hv=["#e8833a","#a05cff","#37b7c3","#e05c8a","#5ce68a","#e6c34a","#5c8aff","#e6605c","#8ad35c","#c37ad3","#4ac3a0","#d38a5c","#7a9de6","#d3c15c","#5cd3c1"];function dv({repoId:e,repo:t,onSaved:r}){const[n,i]=C.useState((t==null?void 0:t.color)||"#a05cff"),[h,y]=C.useState(!1),[o,u]=C.useState(null);C.useEffect(()=>{t!=null&&t.color&&i(t.color)},[t==null?void 0:t.color]);const d=()=>{y(!0),u(null),oe(`/repos/${encodeURIComponent(e)}/color`,{color:n}).then(()=>{u("saved ✓"),r()}).catch(m=>u(m.message)).finally(()=>y(!1))};return s.jsxs("div",{className:"repo-settings",children:[s.jsx("h3",{className:"repo-settings-h",children:"Label color"}),s.jsx("p",{className:"tab-note",children:"The color used for this repo's label on the Repos and PRs pages."}),s.jsx("div",{className:"color-swatches",children:hv.map(m=>s.jsx("button",{type:"button",className:`color-swatch${n.toLowerCase()===m?" on":""}`,style:{background:m},title:m,onClick:()=>i(m)},m))}),s.jsxs("div",{className:"color-custom",children:[s.jsx("input",{type:"color",value:n.length===7?n:"#a05cff",onChange:m=>i(m.target.value)}),s.jsx("input",{className:"color-hex",type:"text",value:n,spellCheck:!1,onChange:m=>i(m.target.value)}),s.jsx("span",{className:"repo-color-chip",style:{borderColor:n,color:n},children:(t==null?void 0:t.name)||"preview"})]}),s.jsxs("div",{className:"color-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:h,onClick:d,children:h?"Saving…":"Save color"}),o&&s.jsx("span",{className:"tab-note",children:o})]}),s.jsx(Jg,{repoId:e}),s.jsx("hr",{className:"repo-settings-sep"}),s.jsx("h3",{className:"repo-settings-h",children:"Automations"}),s.jsxs("p",{className:"tab-note",children:["Actions and event hooks scoped to this repo — they apply on top of the"," ",s.jsx(be,{to:"/automations",children:"global automations"}),". Built-in behavior always runs first; hooks are additive and best-effort."]}),s.jsx(Bd,{repoId:e})]})}function fv({repoId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(null),[o,u]=C.useState(!1),d=C.useCallback(()=>{ee(`/repos/${encodeURIComponent(e)}/forensics`).then(g=>r(g.files||[])).catch(g=>y(g.message))},[e]);C.useEffect(()=>d(),[d]);const m=C.useCallback(()=>{u(!0),y(null),oe(`/repos/${encodeURIComponent(e)}/analyze`).then(g=>{r(g.files||[]),i({nodes:g.cgNodes||0,edges:g.cgEdges||0,ok:!!g.callgraphOk})}).catch(g=>y(g.message)).finally(()=>u(!1))},[e]),f=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:m,children:o?"Analyzing…":t&&t.length?"Re-analyze":"Analyze repo"}),n&&(n.ok?s.jsxs("span",{className:"cg-stat",children:["Callgraph: ",n.nodes.toLocaleString()," nodes · ",n.edges.toLocaleString()," edges"]}):s.jsx("span",{className:"cg-stat",children:"Callgraph unavailable (churn-only hotness)"}))]});return h?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"tab-actions",children:f}),s.jsxs("p",{className:"tab-note err",children:["Failed: ",h]})]}):t===null?s.jsx("p",{className:"tab-note",children:"Loading…"}):t.length===0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"tab-actions",children:f}),s.jsx("p",{className:"tab-note",children:"Not analyzed yet. Forensics ranks files by churn (commits per day) and fix-commit count to surface the repo's hottest, most bug-prone files."})]}):s.jsxs(s.Fragment,{children:[s.jsx(ul,{repoId:e,onAnalyzed:d}),s.jsx("div",{className:"tab-actions",children:f}),s.jsxs("table",{className:"forensics-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"File"}),s.jsx("th",{children:"Churn"}),s.jsx("th",{children:"Fix / total commits"})]})}),s.jsx("tbody",{children:t.map(g=>s.jsxs("tr",{children:[s.jsx("td",{children:g.filePath}),s.jsx("td",{children:g.churnScore!=null?g.churnScore.toFixed(2):"—"}),s.jsxs("td",{children:[g.fixCommits," / ",g.totalCommits]})]},g.id))})]})]})}function pv({repoUrl:e}){const t=Rd(e),[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState(""),u=Date.now();if(C.useEffect(()=>{if(!t){h("not a GitHub remote"),n([]);return}ee(`/gh/issues?repo=${encodeURIComponent(t)}`).then(f=>{n(f.issues||[]),h(f.available?null:f.reason||"unavailable")}).catch(f=>h(f.message))},[t]),r===null)return s.jsx("p",{className:"tab-note",children:"Loading issues…"});if(i&&r.length===0)return s.jsxs("p",{className:"tab-note",children:["Couldn't list issues (",i,")."]});if(r.length===0)return s.jsx("p",{className:"tab-note",children:"No open issues."});const d=y.trim().toLowerCase(),m=d?r.filter(f=>{var g;return String(f.number).includes(d)||f.title.toLowerCase().includes(d)||(((g=f.author)==null?void 0:g.login)||"").toLowerCase().includes(d)}):r;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"pr-toolbar",children:[s.jsx("input",{className:"pr-search",type:"search",placeholder:"🔎 filter issues by #, title, author…",value:y,onChange:f=>o(f.target.value)}),s.jsxs("span",{className:"pr-toolbar-count",children:[m.length," of ",r.length]})]}),s.jsx("ul",{className:"pr-list",children:m.map(f=>{var g;return s.jsxs("li",{className:"pr-row",children:[s.jsx("div",{className:"pr-head-row",children:s.jsxs("a",{className:"pr-head",href:f.url,target:"_blank",rel:"noreferrer",title:"Open on GitHub",children:[s.jsxs("span",{className:"pr-num",children:["#",f.number]})," ",f.title]})}),s.jsxs("div",{className:"pr-byline",children:[((g=f.author)==null?void 0:g.login)&&s.jsxs("span",{children:["@",f.author.login]}),f.createdAt&&s.jsxs("span",{children:[" · opened ",on(f.createdAt,u)]})]})]},f.number)})})]})}function mv({repoId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(null);return C.useEffect(()=>{ee(`/repos/${encodeURIComponent(e)}/projects`).then(h=>r(h.projects||[])).catch(h=>i(h.message))},[e]),n?s.jsxs("p",{className:"tab-note err",children:["Failed to load projects: ",n]}):t===null?s.jsx("p",{className:"tab-note",children:"Loading…"}):t.length===0?s.jsx("p",{className:"tab-note",children:"No Corral sandbox sessions on this repo yet. Projects whose git remote matches this repo appear here — start one from the Repos list."}):s.jsx("ul",{className:"pr-list",children:t.map(h=>s.jsxs("li",{children:[s.jsx(be,{to:`/p/${encodeURIComponent(h.id)}`,children:h.name}),s.jsx("span",{className:"proj-ws",children:h.workspace})]},h.id))})}function gv({prId:e}){const[t,r]=C.useState([]),[n,i]=C.useState([]),[h,y]=C.useState(null),o=C.useCallback(()=>{ee(`/prs/${e}/links`).then(m=>r(m.links||[])).catch(m=>y(m.message)),ee(`/prs/${e}/links/suggest`).then(m=>i(m.suggestions||[])).catch(()=>{})},[e]);C.useEffect(()=>o(),[o]);const u=(m,f)=>{oe(`/prs/${e}/links`,{linkedPrId:m,relationship:f}).then(()=>o()).catch(g=>y(g.message))},d=m=>{fetch(`/prs/${e}/links/${m}`,{method:"DELETE",credentials:"same-origin"}).then(()=>o()).catch(()=>{})};return s.jsxs("div",{className:"linked-prs",children:[s.jsx("h4",{className:"block-h",children:"Linked PRs"}),h&&s.jsx("p",{className:"tab-note err",children:h}),t.length===0&&s.jsx("p",{className:"tab-note",children:"No linked PRs."}),s.jsx("ul",{className:"link-list",children:t.map(m=>s.jsxs("li",{children:[s.jsx("span",{className:"link-rel",children:m.relationship}),s.jsxs("span",{className:"link-tgt",children:["#",m.linkedNumber," ",m.linkedTitle||m.linkedSummary||""]}),s.jsx("button",{type:"button",className:"link-x",title:"Remove link",onClick:()=>d(m.id),children:"✕"})]},m.id))}),n.length>0&&s.jsxs("div",{className:"link-suggest",children:[s.jsx("span",{className:"link-suggest-h",children:"Suggested (shared files):"}),n.map(m=>s.jsxs("span",{className:"link-suggest-item",children:["#",m.number," (",m.overlap,")",s.jsx("button",{type:"button",className:"btn tiny",onClick:()=>u(m.prId,"related"),children:"+ link"})]},m.prId))]})]})}function vv({prId:e,repoId:t,pr:r,repoName:n}){const[i,h]=C.useState(null),[y,o]=C.useState(""),[u,d]=C.useState(!1),[m,f]=C.useState(null),g=S=>{d(!0),f(null),oe(`/prs/${e}/${S}`,{body:y}).then(()=>{f({text:zc(S)+" ✓",err:!1}),h(null),o("")}).catch(v=>f({text:v.message,err:!0})).finally(()=>d(!1))},w=S=>{f(null),h(v=>v===S?null:S)};return s.jsxs("div",{className:"pr-actions",children:[s.jsxs("div",{className:"pr-actions-row",children:[s.jsx("button",{type:"button",className:`btn${i==="approve"?" primary":""}`,onClick:()=>w("approve"),children:"✓ Approve"}),s.jsx("button",{type:"button",className:`btn${i==="comment"?" primary":""}`,onClick:()=>w("comment"),children:"💬 Comment"}),s.jsx("button",{type:"button",className:`btn${i==="request-changes"?" primary":""}`,onClick:()=>w("request-changes"),children:"✗ Request changes"}),s.jsx(_v,{prId:e,repoId:t,pr:r,repoName:n}),m&&s.jsx("span",{className:`pr-actions-msg${m.err?" err":""}`,children:m.text})]}),i?s.jsxs("div",{className:"pr-action-panel col",children:[s.jsx("textarea",{className:"pr-action-body",placeholder:i==="request-changes"?"Describe the changes you're requesting (required)…":i==="approve"?"Optional approval note…":"Comment…",value:y,onChange:S=>o(S.target.value)}),s.jsxs("div",{className:"pr-action-panel",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:u,onClick:()=>g(i),children:u?"Submitting…":`Confirm ${zc(i).toLowerCase()}`}),s.jsx("button",{type:"button",className:"btn",onClick:()=>h(null),children:"Cancel"})]})]}):null]})}function zc(e){switch(e){case"approve":return"Approved";case"comment":return"Commented";case"request-changes":return"Requested changes"}}function Wc(e){return e==="host"?"Merge with host":e==="sandbox"?"Merge with sandbox":"Merge"}const Kc=["squash","merge","rebase"],Vc={squash:"Squash and merge",merge:"Create a merge commit",rebase:"Rebase and merge"};function _v({prId:e,repoId:t,pr:r,repoName:n}){const[i,h]=C.useState("host"),[y,o]=C.useState(null),[u,d]=C.useState(!1),[m,f]=C.useState(!1),[g,w]=C.useState(null),[S,v]=C.useState(null),[p,c]=C.useState(!1),[a,l]=C.useState("");C.useEffect(()=>{ee("/global/config").then(E=>{const L=E.merge_mode;(L==="host"||L==="sandbox"||L==="plain")&&h(L)}).catch(()=>{}),ee(`/repos/${encodeURIComponent(t)}/merge-strategy`).then(E=>{o(E),l(E.effective||"")}).catch(()=>{})},[t]);const _=y&&y.allowed.length?y.allowed:Kc,j=!!y&&!y.preferred&&!y.global_default,b=async E=>{try{await oe(`/repos/${encodeURIComponent(t)}/merge-strategy`,{strategy:E}),o(L=>L&&{...L,preferred:E,effective:E})}catch{}},k=()=>{if(w(null),j){c(!0);return}x(a||(y==null?void 0:y.effective)||"squash")},x=async E=>{c(!1),d(!1),f(!0),w(null);try{if(i==="plain")await oe(`/prs/${e}/merge`,{method:E}),w({text:"Merged ✓",err:!1});else if(i==="host")await oe(`/prs/${e}/merge-host/start`,{}),window.dispatchEvent(new CustomEvent("corral:open-work")),w({text:"Merging on host — see the Work tab (⌘K)",err:!1});else{const L=await ee(`/prs/${e}/merge-prompt`),P=(await oe("/projects/create",{mode:"clone",name:`${n||"pr"}-merge-${r.number}`,repos:[{repoId:t,branch:L.branch||r.headRef||void 0}],source:{kind:"pr",repo_id:t,number:r.number,url:r.githubUrl,title:r.title}})).id;v(P),await oe(`/p/${P}/start`).catch(()=>{}),await je(`/p/${P}/populate-prompt`,{prompt:L.prompt,submit:!0}).catch(()=>{}),await oe(`/prs/${e}/merge-watch`,{projectId:P}).catch(()=>{}),w({text:"Merge sandbox launched",err:!1})}}catch(L){w({text:L.message,err:!0})}finally{f(!1)}},N=i==="host";return s.jsxs("span",{className:"merge-control",children:[s.jsxs("span",{className:"split-btn",children:[s.jsx("button",{type:"button",className:`btn primary split-main${N?" warn":""}`,disabled:m,title:i==="host"?"Rebase & merge on the host (fast — NOT sandboxed)":i==="sandbox"?"Rebase & merge in a one-shot sandbox, then tear it down":"Merge the PR on GitHub (no rebase)",onClick:k,children:m?"Working…":`⑃ ${Wc(i)}`}),s.jsx("button",{type:"button",className:"btn primary split-caret",disabled:m,"aria-label":"Merge options",title:"Choose merge mode & strategy",onClick:()=>d(E=>!E),children:"▾"}),u&&s.jsxs("div",{className:"split-menu",role:"menu",children:[s.jsx("div",{className:"split-menu-head",children:"Mode"}),["host","sandbox","plain"].map(E=>s.jsxs("button",{type:"button",className:`split-menu-item${i===E?" active":""}`,onClick:()=>h(E),children:[Wc(E),E==="host"&&s.jsx("span",{className:"split-menu-scope",children:"not sandboxed"}),E==="plain"&&s.jsx("span",{className:"split-menu-scope",children:"no rebase"})]},E)),s.jsx("div",{className:"split-menu-sep"}),s.jsxs("div",{className:"split-menu-head",children:["Strategy",y&&y.preferred?" · repo default":y&&y.global_default?" · global default":""]}),Kc.map(E=>{const L=_.includes(E),T=(a||(y==null?void 0:y.effective))===E;return s.jsxs("button",{type:"button",className:`split-menu-item${T?" active":""}`,disabled:!L,title:L?"":"Disabled for this repo on GitHub",onClick:()=>{l(E),b(E)},children:[Vc[E],!L&&s.jsx("span",{className:"split-menu-scope",children:"off on GitHub"})]},E)})]})]}),g&&s.jsx("span",{className:`pr-actions-msg${g.err?" err":""}`,children:g.text}),S&&s.jsx("a",{className:"pr-actions-link",href:`/p/${S}/`,title:"Open the merge sandbox",children:"open sandbox ↗"}),p&&s.jsx("div",{className:"merge-ask-backdrop",onClick:()=>c(!1),children:s.jsxs("div",{className:"merge-ask",onClick:E=>E.stopPropagation(),children:[s.jsxs("div",{className:"merge-ask-head",children:["How should ",n||"this repo"," be merged?"]}),s.jsx("p",{className:"muted",children:"Pick the merge method for this repository. It'll be remembered as this repo's default (you can change it later in the ▾ menu). Only methods GitHub allows for the repo are shown."}),s.jsx("div",{className:"merge-ask-options",children:_.map(E=>s.jsx("button",{type:"button",className:"btn",onClick:()=>x(E),children:Vc[E]},E))}),s.jsx("button",{type:"button",className:"merge-ask-cancel",onClick:()=>c(!1),children:"Cancel"})]})})]})}function yv(e,t){return{repo:t||"",branch:e.headRef||"",pr_number:String(e.number),pr_title:e.title||"",pr_url:e.githubUrl||""}}function xv(e,t){return e.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(r,n)=>t[n]??"")}function Sv(e){return`Verify PR #${e.number} ("${e.title||""}") works. You're on its branch. Explore the change, run the relevant tests or the app, and report whether it behaves correctly and any issues you find. The PR is ${e.githubUrl||""}.`}function wv({repoId:e,pr:t,repoName:r}){const[n,i]=C.useState("idle"),[h,y]=C.useState(null),[o,u]=C.useState(null),[d,m]=C.useState(!1),[f,g]=C.useState("default"),[w,S]=C.useState([]),[v,p]=C.useState(null),[c,a]=C.useState(!1),[l,_]=C.useState(""),[j,b]=C.useState(""),[k,x]=C.useState(!1),[N,E]=C.useState(""),L=C.useRef(null);C.useEffect(()=>()=>{var q;return(q=L.current)==null?void 0:q.close()},[]);const T=()=>{var $;if(!j.trim())return;($=L.current)==null||$.close(),x(!0),E("");const q=new WebSocket(hs(`/api/prompts/draft?repoId=${encodeURIComponent(e)}`));L.current=q,q.onopen=()=>q.send(JSON.stringify({description:j})),q.onmessage=R=>{let A;try{A=JSON.parse(R.data)}catch{return}A.type==="text"?E(M=>M+A.text):A.type==="tool_use"?E(M=>M+`› ${A.tool} +`):A.type==="error"?E(M=>M+` +⚠ ${A.text||""}`):A.type==="draft"&&A.result&&_(A.result)},q.onclose=()=>{x(!1),L.current=null},q.onerror=()=>E(R=>R+` +⚠ draft connection failed`)};C.useEffect(()=>{!d||w.length||v!==null||(ee(`/api/prompts?repo=${encodeURIComponent(e)}`).then(q=>{const $=(q.prompts||[]).find(R=>R.key==="pr.verify");$&&(g($.source),p($.effective))}).catch(()=>{}),ee(`/api/prompts/project-start?repo=${encodeURIComponent(e)}`).then(q=>S(q.presets||[])).catch(()=>{}))},[d,e,w.length,v]);const P=()=>c&&l.trim()?l:v?xv(v,yv(t,r)):Sv(t),B=async()=>{m(!1),i("launching"),u(null);try{const q={kind:"pr",repo_id:e,number:t.number,url:t.githubUrl,title:t.title},R=(await oe("/projects/create",{mode:"clone",name:`${r||"pr"}-verify-${t.number}`,repos:[{repoId:e,branch:t.headRef||void 0}],source:q})).id;y(R),await oe(`/p/${R}/start`).catch(()=>{}),await je(`/p/${R}/populate-prompt`,{prompt:P(),submit:!0}).catch(()=>{}),i("done")}catch(q){u(q.message),i("err")}};if(n==="done"&&h)return s.jsx("a",{className:"dock-toggle",href:`/p/${h}/`,title:"Open the verify project",children:"✓ verifying → open project"});const U=n==="launching"?"Launching…":n==="err"?`⚠ ${o}`:"▶ Verify in sandbox",K=c?"custom prompt":v?`${f} prompt`:"default verify prompt";return s.jsxs("div",{className:"split-btn",children:[s.jsx("button",{type:"button",className:"dock-toggle split-main",disabled:n==="launching",title:"Create a sandbox project on this PR's branch and auto-start Claude to verify it (runs in the background)",onClick:B,children:U}),s.jsx("button",{type:"button",className:"dock-toggle split-caret",disabled:n==="launching",title:"Choose which prompt to launch with","aria-label":"Choose prompt",onClick:()=>m(q=>!q),children:"▾"}),d&&s.jsxs("div",{className:"split-menu",role:"menu",children:[s.jsxs("div",{className:"split-menu-head",children:["Launch prompt · ",K]}),s.jsx("button",{type:"button",className:`split-menu-item${!v&&!c?" active":""}`,onClick:()=>{p(null),a(!1)},children:"Built-in verify prompt"}),w.map(q=>s.jsxs("button",{type:"button",className:`split-menu-item${v===q.template&&!c?" active":""}`,onClick:()=>{p(q.template),a(!1)},children:[q.name," ",s.jsx("span",{className:"split-menu-scope",children:q.scope})]},q.id)),s.jsx("div",{className:"split-menu-sep"}),s.jsx("button",{type:"button",className:`split-menu-item${c?" active":""}`,onClick:()=>{a(!0),l||_(P())},children:"✎ Customize prompt…"}),c&&s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"split-menu-textarea",rows:6,value:l,onChange:q=>_(q.target.value),placeholder:"Prompt to send when the sandbox starts…"}),s.jsxs("div",{className:"split-menu-ai",children:[s.jsxs("div",{className:"split-menu-ai-head",children:["✨ Build with AI",s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude, not the sandbox; read-only tools",children:"host · not sandboxed · read-only"})]}),s.jsx("textarea",{className:"split-menu-textarea",rows:2,value:j,onChange:q=>b(q.target.value),placeholder:"Describe what this prompt should do — e.g. 'review the diff, run the test suite, and summarize risks'"}),s.jsx("button",{type:"button",className:"dock-toggle",style:{marginLeft:0},disabled:k||!j.trim(),onClick:T,children:k?"Drafting…":"Draft with AI"}),N&&s.jsx("pre",{className:"split-menu-ai-log",children:N})]})]})]})]})}function fo({text:e}){const[t,r]=C.useState(!1),n=e.length>600;return s.jsxs("div",{className:`pr-desc-body-wrap${n&&!t?" clamped":""}`,children:[s.jsx("div",{className:"pr-desc-body markdown",dangerouslySetInnerHTML:{__html:jr(e)}}),n&&s.jsx("button",{type:"button",className:"pr-desc-more",onClick:()=>r(i=>!i),children:t?"Show less":"Show more"})]})}function bv({prId:e,body:t}){const[r,n]=C.useState([]),[i,h]=C.useState(0);C.useEffect(()=>{let u=!0;return ee(`/prs/${e}/issues`).then(d=>u&&n(d.issues||[])).catch(()=>u&&n([])),()=>{u=!1}},[e]);const y=(t||"").trim();if(!y&&r.length===0)return null;if(r.length===0)return s.jsxs("div",{className:"pr-desc",children:[s.jsx("div",{className:"pr-desc-head",children:"Description"}),y?s.jsx(fo,{text:y}):s.jsx("p",{className:"pr-desc-empty",children:"No description."})]});const o=i>0?r[i-1]:null;return s.jsxs("div",{className:"pr-desc",children:[s.jsxs("div",{className:"pr-desc-tabs",role:"tablist",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":i===0,className:`pr-desc-tab${i===0?" active":""}`,onClick:()=>h(0),children:"Description"}),r.map((u,d)=>s.jsxs("button",{type:"button",role:"tab","aria-selected":i===d+1,className:`pr-desc-tab${i===d+1?" active":""}`,onClick:()=>h(d+1),title:u.title||`Issue #${u.number}`,children:["Issue #",u.number]},u.number))]}),o?s.jsxs("div",{className:"pr-desc-issue",children:[s.jsxs("div",{className:"pr-desc-issue-head",children:[s.jsxs("span",{className:"pr-desc-issue-title",children:["#",o.number," ",o.title||""]}),o.state&&s.jsx("span",{className:"pr-state",children:o.state}),o.url&&s.jsx("a",{className:"pr-desc-issue-link",href:o.url,target:"_blank",rel:"noreferrer",children:"view on GitHub ↗"}),o.source==="branch"&&s.jsx("span",{className:"pr-desc-issue-src",title:"Linked via the PR's branch name, not an official 'Closes #N' reference",children:"from branch name"})]}),(o.body||"").trim()?s.jsx(fo,{text:(o.body||"").trim()}):s.jsx("p",{className:"pr-desc-empty",children:"No issue description."})]}):y?s.jsx(fo,{text:y}):s.jsx("p",{className:"pr-desc-empty",children:"No description."})]})}function Cv({prId:e}){const[t,r]=C.useState(null),[n,i]=C.useState(""),[h,y]=C.useState(!1),[o,u]=C.useState(null),d=()=>{ee(`/prs/${e}/notes`).then(g=>r(g.notes||[])).catch(g=>u(g.message))};C.useEffect(d,[e]);const m=()=>{n.trim()&&(y(!0),u(null),oe(`/prs/${e}/notes`,{body:n}).then(()=>{i(""),d()}).catch(g=>u(g.message)).finally(()=>y(!1)))},f=g=>{St(`/prs/${e}/notes/${g}`).then(d).catch(w=>u(w.message))};return s.jsxs("div",{className:"pr-notes-panel",children:[s.jsxs("div",{className:"pr-notes-head",children:["🗒 Notes ",s.jsx("span",{className:"pr-notes-sub",children:"private · local only, never posted to GitHub"})]}),s.jsxs("div",{className:"pr-notes-add",children:[s.jsx("textarea",{className:"pr-notes-input",rows:2,placeholder:"Add a private note about this PR…",value:n,onChange:g=>i(g.target.value),onKeyDown:g=>{(g.metaKey||g.ctrlKey)&&g.key==="Enter"&&m()}}),s.jsx("button",{type:"button",className:"btn primary",disabled:h||!n.trim(),onClick:m,children:h?"Saving…":"Add note"})]}),o&&s.jsx("p",{className:"tab-note err",children:o}),t===null?s.jsx("p",{className:"tab-note",children:"Loading notes…"}):t.length===0?s.jsx("p",{className:"pr-notes-empty",children:"No notes yet."}):s.jsx("ul",{className:"pr-notes-list",children:t.map(g=>s.jsxs("li",{className:"pr-note",children:[s.jsx("div",{className:"pr-note-body",children:g.body}),s.jsxs("div",{className:"pr-note-meta",children:[g.author?`${g.author} · `:"",g.createdAt,s.jsx("button",{type:"button",className:"pr-note-del",title:"Delete note",onClick:()=>f(g.id),children:"✕"})]})]},g.id))})]})}function kv({repoId:e,number:t}){ds("console");const[r,n]=C.useState(null),[i,h]=C.useState(null),[y,o]=C.useState(null),[u,d]=C.useState(0),[m,f]=C.useState(!1),[g,w]=C.useState(!1),[S,v]=C.useState(!1),[p,c]=C.useState(!1),[a,l]=C.useState(!1),_=()=>{l(!0),o(null),oe(`/repos/${encodeURIComponent(e)}/prs/fetch`,{number:t}).then(j=>{h(j.pr),Hc(j.pr.id),d(b=>b+1)}).catch(j=>o(j.message)).finally(()=>l(!1))};return C.useEffect(()=>{ee("/repos").then(j=>n((j.repos||[]).find(b=>b.id===e)||null)).catch(()=>{})},[e]),C.useEffect(()=>{let j=!0;return ee(`/repos/${encodeURIComponent(e)}/prs`).then(b=>{const k=(b.prs||[]).find(x=>x.number===t);if(k){j&&h(k);return}return oe(`/repos/${encodeURIComponent(e)}/prs/fetch`,{number:t}).then(x=>j&&h(x.pr))}).catch(b=>j&&o(b.message)),()=>{j=!1}},[e,t]),s.jsxs(s.Fragment,{children:[s.jsxs("header",{className:"console-header",children:[s.jsxs("div",{className:"brand",children:[s.jsxs(be,{to:`/repos/${encodeURIComponent(e)}`,className:"back",children:["← ",r?r.name:"repo"]}),s.jsxs("span",{className:"brand-name",children:["#",t," ",(i==null?void 0:i.shortSummary)||(i==null?void 0:i.title)||""]}),(i==null?void 0:i.state)&&s.jsx("span",{className:"pr-state",children:i.state}),(i==null?void 0:i.githubUrl)&&s.jsx("a",{className:"brand-sub",href:i.githubUrl,target:"_blank",rel:"noreferrer",children:"view on GitHub ↗"})]}),i&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"dock-toggle",disabled:a,title:"Re-pull this PR from GitHub (description, diff) and re-extract blocks",onClick:_,children:a?"Refreshing…":"↻ Refresh from GitHub"}),s.jsx("button",{type:"button",className:`dock-toggle${S?" on":""}`,title:"Link this PR to related PRs",onClick:()=>v(j=>!j),children:"🔗 Linked PRs"}),s.jsx("button",{type:"button",className:`dock-toggle${p?" on":""}`,title:"Private notes on this PR — local only, never posted to GitHub",onClick:()=>c(j=>!j),children:"🗒 Notes"}),s.jsx(wv,{repoId:e,pr:i,repoName:r==null?void 0:r.name}),s.jsx("button",{type:"button",className:"dock-toggle",title:"Start a sandbox project on this PR's branch (opens the create dialog)",onClick:()=>w(!0),children:"⧉ Start project"}),s.jsx("button",{type:"button",className:`dock-toggle${m?" on":""}`,title:"Ask Claude about this PR — a host claude chat",onClick:()=>f(j=>!j),children:"💬 Ask Claude"})]})]}),s.jsx(cl,{repoId:e}),s.jsxs("div",{className:"pr-review-page",children:[s.jsxs("div",{className:"pr-experimental-note",children:["⚠ ",s.jsx("strong",{children:"Experimental — a gauge, not a substitute for review."})," This analysis is an aid to help you orient quickly; it can miss things and be wrong. Don’t rely on it in place of reading the diff and your own judgment."]}),i&&S&&s.jsx("div",{className:"pr-links-panel",children:s.jsx(gv,{prId:i.id})}),i&&p&&s.jsx(Cv,{prId:i.id}),i&&s.jsx(vv,{prId:i.id,repoId:e,pr:i,repoName:r==null?void 0:r.name}),y?s.jsxs("p",{className:"tab-note err",children:["Failed to load PR #",t,": ",y]}):i?s.jsxs(s.Fragment,{children:[s.jsx(ul,{repoId:e,onAnalyzed:()=>{Hc(i.id),d(j=>j+1)}}),s.jsx(bv,{prId:i.id,body:i.body}),s.jsxs("div",{className:"pr-top",children:[s.jsx("div",{className:"pr-top-left",children:s.jsx(uv,{prId:i.id},`risk-${u}`)}),s.jsx("div",{className:"pr-top-right",children:s.jsx(cv,{prId:i.id},`ff-${u}`)})]}),s.jsx(rv,{prId:i.id},`bc-${u}`)]}):s.jsxs("p",{className:"tab-note",children:["Loading PR #",t,"…"]})]}),i&&m&&s.jsxs("div",{className:"chat-panel",id:"chat-panel",children:[s.jsxs("div",{className:"chat-panel-bar",children:[s.jsxs("span",{children:[s.jsx("i",{className:"screen-dot"}),"ask claude · PR #",t]}),s.jsx("span",{className:"chat-panel-actions",children:s.jsx("button",{type:"button",title:"Close",onClick:()=>f(!1),children:"✕"})})]}),s.jsx("div",{className:"chat-panel-iframe",children:s.jsx(an,{wsPath:`/prs/${i.id}/chat/ws`})})]}),i&&g&&s.jsx(ll,{presetRepoId:e,presetBranch:i.headRef,presetName:`${(r==null?void 0:r.name)||"pr"}-pr-${t}`,onClose:()=>w(!1)})]})}function fs(e){return e.replace(/^.*\//,"")}const qc=Array.from({length:25},(e,t)=>t);function Gc(e){return e===0||e===24?"12am":e===12?"12pm":e<12?`${e}am`:`${e-12}pm`}function jv(){ds("console");const e=wd(),[t,r]=C.useState(null),[n,i]=C.useState(null),[h,y]=C.useState(""),[o,u]=C.useState(""),[d,m]=C.useState([]),[f,g]=C.useState({}),[w,S]=C.useState({host:"",kind:"header",name:"",value:""}),[v,p]=C.useState({}),[c,a]=C.useState(""),[l,_]=C.useState([]),[j,b]=C.useState(!1),[k,x]=C.useState(!1),[N,E]=C.useState(""),[L,T]=C.useState(""),[P,B]=C.useState(""),[U,K]=C.useState(""),[q,$]=C.useState(""),[R,A]=C.useState(!1),[M,O]=C.useState(!0),[W,F]=C.useState(!0),[z,X]=C.useState(""),[I,D]=C.useState("host"),[V,H]=C.useState(!0),[J,Q]=C.useState(""),[re,ie]=C.useState(null),he=Y=>Y.split(` +`).map(te=>te.trim()).filter(Boolean),Ce=C.useCallback(Y=>{ee("/global/config").then(te=>{r(te),y((te.monitor_hosts||[]).join(` `)),u((te.mitm_ports||[]).join(` -`)),m([]),g({});const Se={};(te.ssh_keys||[]).forEach(Te=>Se[fs(Te)]=!0),p(Se);const Ut=new Set((te.available_ssh_keys||[]).map(Te=>Te.name));_((te.ssh_keys||[]).filter(Te=>!Ut.has(fs(Te)))),E(te.update_repo||""),T(te.log_retention_days?String(te.log_retention_days):""),B(te.log_max_rows?String(te.log_max_rows):""),z(te.conv_retention_days?String(te.conv_retention_days):""),$(te.conv_max_rows?String(te.conv_max_rows):""),D(!!te.api_writes_enabled),P(te.dind_default!==!1),Y(te.dind_repo_cache_default!==!1),J(te.merge_strategy||""),A(te.merge_mode||"host"),W(te.merge_auto_teardown!==!1),Q(te.agent_context_stale_days?String(te.agent_context_stale_days):""),G&&i({text:G,err:!1})}).catch(te=>i({text:`failed to load: ${te.message}`,err:!0})),ee("/api/chat/capability").then(te=>ie(te.configured?te.capability:null)).catch(()=>{})},[]);C.useEffect(()=>Ce(),[Ce]);function ae(){const G=[];return((t==null?void 0:t.available_ssh_keys)||[]).forEach(te=>{v[te.name]&&G.push(te.name)}),l.forEach(te=>{v[fs(te)]!==!1&&G.push(te)}),G}async function dt(G){ie(G);try{const te=await fetch("/api/chat/capability",{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({capability:G})});if(!te.ok)throw new Error(`HTTP ${te.status}`);i({text:`✓ assistant set to ${G==="act"?"can act":"read-only"}`,err:!1})}catch(te){i({text:`couldn't update assistant: ${te.message}`,err:!0})}}async function wt(){const G={};d.length&&(G.set_creds=d.slice());const te=Object.keys(f).filter(Se=>f[Se]);te.length&&(G.unset_creds=te),G.monitor_hosts=he(h),G.mitm_ports=he(o),G.ssh_keys=ae(),G.update_repo=N.trim(),G.log_retention_days=L.trim()?Math.max(0,parseInt(L,10)||0):0,G.log_max_rows=O.trim()?Math.max(0,parseInt(O,10)||0):0,G.conv_retention_days=F.trim()?Math.max(0,parseInt(F,10)||0):0,G.conv_max_rows=K.trim()?Math.max(0,parseInt(K,10)||0):0,G.api_writes_enabled=R,G.dind_default=M,G.dind_repo_cache_default=U,G.merge_strategy=H,G.merge_mode=I,G.merge_auto_teardown=q,G.agent_context_stale_days=X.trim()&&parseInt(X,10)||0,x(!0);try{const Se=await oe("/global/apply",G);Ce((Se.results||[]).join(" • ")||"✓ saved")}catch(Se){i({text:`apply failed: ${Se.message}`,err:!0})}finally{x(!1)}}async function nt(){b(!1);try{await je("/global/populate",{}),b(!0),i({text:"complete the prompts in the terminal; credentials refresh here when done",err:!1})}catch(G){i({text:`could not start: ${G.message}`,err:!0})}}function ft(){const G=w.host.trim().toLowerCase(),te=w.name.trim();if(!G||!te||!w.value){i({text:"credential needs host, name, and value",err:!0});return}m(Se=>[...Se,{host:G,kind:w.kind,name:te,value:w.value}]),S({host:"",kind:"header",name:"",value:""}),i({text:"credential queued — click Apply",err:!1})}if(!t)return s.jsx("p",{className:"muted",style:{padding:"1rem"},children:"loading global settings…"});const Ie=(t.available_ssh_keys||[]).map(G=>({value:G.name,meta:[G.type,G.comment].filter(Boolean).join(" ")})),Le=l.map(G=>({value:G,meta:"custom path"}));return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"brand-back",title:"Back to all projects",children:"←"}),s.jsx("span",{className:"brand-name",children:"corral"}),s.jsx("span",{className:"brand-sub",children:"global settings"})]})}),s.jsxs("main",{className:"global-wrap",children:[s.jsxs("p",{className:"global-intro",children:["Settings that apply across every project. Credentials here are shared by all projects (a project can still override per host). Defaults are inherited by new projects when you run ",s.jsx("code",{children:"corral init"}),"."]}),s.jsxs("div",{id:"global-root",children:[s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Do Not Disturb ",s.jsx("span",{className:"muted",children:"— quiet hours for notifications (this browser)"})]}),s.jsxs("label",{className:"row",style:{marginBottom:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:e.config.enabled,onChange:G=>e.setEnabled(G.target.checked)}),s.jsxs("span",{children:["Enable Do Not Disturb — silence the chime and toasts outside your active hours.",e.config.enabled&&e.quiet&&s.jsx("span",{className:"dnd-now",children:" · quiet right now 🌙"})]})]}),s.jsxs("div",{className:"row dnd-hours",style:{opacity:e.config.enabled?1:.5},children:[s.jsx("span",{className:"cfg-label",children:"Notify me between"}),s.jsx("select",{className:"cfg-edit dnd-hour-select",disabled:!e.config.enabled,value:e.config.startHour,onChange:G=>e.setWindow(Number(G.target.value),e.config.endHour),children:qc.map(G=>s.jsx("option",{value:G,children:Gc(G)},G))}),s.jsx("span",{children:"and"}),s.jsx("select",{className:"cfg-edit dnd-hour-select",disabled:!e.config.enabled,value:e.config.endHour,onChange:G=>e.setWindow(e.config.startHour,Number(G.target.value)),children:qc.map(G=>s.jsx("option",{value:G,children:Gc(G)},G))}),s.jsx("span",{className:"muted cfg-note",children:"uses this browser's local time (default 9am–5pm)"})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Shared credentials ",s.jsx("span",{className:"muted",children:"— all projects, mtime-reloaded live"})]}),s.jsx("div",{className:"muted global-path",children:t.creds_path}),s.jsxs("table",{className:"cfg-creds",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Host"}),s.jsx("th",{children:"Injects"}),s.jsx("th",{children:"Value"}),s.jsx("th",{})]})}),s.jsxs("tbody",{children:[(t.credentials||[]).length===0&&s.jsx("tr",{children:s.jsx("td",{className:"muted",colSpan:4,children:"none set"})}),(t.credentials||[]).map(G=>s.jsxs("tr",{style:{opacity:f[G.host]?.4:1},children:[s.jsx("td",{children:G.host}),s.jsxs("td",{children:[G.kind,": ",G.name]}),s.jsx("td",{className:"cred-mask",children:G.masked}),s.jsx("td",{children:s.jsx("button",{className:"cfg-cred-rm",onClick:()=>{g(te=>({...te,[G.host]:!0})),i({text:"credential queued for removal — click Apply",err:!1})},children:"remove"})})]},G.host)),d.map((G,te)=>s.jsxs("tr",{children:[s.jsx("td",{children:G.host}),s.jsxs("td",{children:[G.kind,": ",G.name]}),s.jsx("td",{className:"s-2xx",children:"pending"}),s.jsx("td",{})]},`new-${te}`))]})]}),s.jsxs("div",{className:"cfg-cred-add",children:[s.jsx("input",{placeholder:"host (api.foo.com)",value:w.host,onChange:G=>S({...w,host:G.target.value})}),s.jsxs("select",{value:w.kind,onChange:G=>S({...w,kind:G.target.value}),children:[s.jsx("option",{value:"header",children:"header"}),s.jsx("option",{value:"url_param",children:"url_param"})]}),s.jsx("input",{placeholder:"name (X-API-Key)",value:w.name,onChange:G=>S({...w,name:G.target.value})}),s.jsx("input",{placeholder:"value (secret)",type:"password",value:w.value,onChange:G=>S({...w,value:G.target.value})}),s.jsx("button",{className:"cfg-btn",onClick:ft,children:"Add"})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:nt,children:"Populate from Claude…"}),s.jsxs("span",{className:"muted",children:["runs ",s.jsx("code",{children:"claude setup-token"})," in a terminal below"]})]}),j&&s.jsxs("div",{className:"populate-term",style:{display:"block",height:320},children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"claude setup-token · answer the prompts"]}),s.jsx(Zs,{fullPath:"/global/populate/ws"})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Defaults for new projects ",s.jsxs("span",{className:"muted",children:["— inherited at ",s.jsx("code",{children:"corral init"})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Default monitor-list"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("textarea",{className:"cfg-edit",rows:3,spellCheck:!1,value:h,onChange:G=>y(G.target.value)}),s.jsx("div",{className:"muted cfg-note",children:"empty = new projects monitor all allowed hosts"})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Default mitm-ports"}),s.jsx("div",{className:"cfg-value",children:s.jsx("textarea",{className:"cfg-edit",rows:2,spellCheck:!1,value:o,onChange:G=>u(G.target.value)})})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Default SSH keys ",s.jsx("span",{className:"muted",children:"— loaded by EVERY project's scoped agent"})]}),s.jsx("div",{className:"muted global-path",children:t.ssh_keys_path}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Keys"}),s.jsxs("div",{className:"cfg-value",children:[Ie.length+Le.length===0?s.jsx("div",{className:"muted cfg-note",children:"no keys found under ~/.ssh"}):s.jsx("div",{className:"cfg-ssh-list",children:[...Ie,...Le].map(G=>s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",className:"g-ssh-key",checked:!!v[fs(G.value)],onChange:te=>p(Se=>({...Se,[fs(G.value)]:te.target.checked}))})," ",s.jsx("span",{className:"cfg-ssh-name",children:fs(G.value)})," ",G.meta&&s.jsx("span",{className:"muted cfg-ssh-meta",children:G.meta})]},G.value))}),s.jsxs("div",{className:"cfg-ssh-extra-add",children:[s.jsx("input",{placeholder:"other key path (~/.ssh/... or /abs/path)",value:c,onChange:G=>a(G.target.value)}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>{const G=c.trim();G&&(_(te=>te.includes(G)?te:[...te,G]),p(te=>({...te,[fs(G)]:!0})),a(""))},children:"+ add path"})]})]})]}),s.jsx("div",{className:"muted cfg-note",children:"The container can USE these keys (sign/push) but never reads the key bytes — only the agent socket is mounted. Projects can add more in their Config tab."})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Update source ",s.jsxs("span",{className:"muted",children:["— where ",s.jsx("code",{children:"corral update"})," pulls releases from"]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Repo or URL"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit",spellCheck:!1,placeholder:t.update_repo_default,value:N,onChange:G=>E(G.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["A GitHub ",s.jsx("code",{children:"owner/name"}),", or a full release URL for another host (e.g."," ",s.jsx("code",{children:"https://git.example.com/owner/repo"}),") that uses the same"," ",s.jsx("code",{children:"/releases/latest"})," + ",s.jsx("code",{children:"/releases/download//…"})," layout. Leave blank for the default (",s.jsx("code",{children:t.update_repo_default}),")."]})]})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Log retention ",s.jsxs("span",{className:"muted",children:["— how long the ",s.jsx("a",{href:"/automations/logs",children:"activity log"})," is kept"]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Keep for (days)"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.log_retention_days_default),value:L,onChange:G=>T(G.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.log_retention_days_default," days). Older entries are pruned hourly."]})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Max entries"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.log_max_rows_default),value:O,onChange:G=>B(G.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.log_max_rows_default.toLocaleString()," rows). The newest are kept."]})]})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Conversation retention ",s.jsx("span",{className:"muted",children:"— how long captured Claude conversations are kept"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Keep for (days)"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.conv_retention_days_default),value:F,onChange:G=>z(G.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.conv_retention_days_default," days). Kept even after a project is deleted; pruned hourly. Stored separately from the activity log."]})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Max conversations"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.conv_max_rows_default),value:K,onChange:G=>$(G.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.conv_max_rows_default.toLocaleString()," conversations). The newest are kept."]})]})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["API access ",s.jsxs("span",{className:"muted",children:["— let the ",s.jsx("code",{children:"corral api"})," CLI and Claude make changes"]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:R,onChange:G=>D(G.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Allow API writes"})]}),s.jsx("div",{className:"muted cfg-note",children:"Reads (listing flows, logs, PRs) are always allowed. With this off, the CLI and Claude can look but not act; turn it on to let them start projects, create issues, and run flows. Off by default."})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["New sandboxes ",s.jsx("span",{className:"muted",children:"— defaults for projects you create"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:M,onChange:G=>P(G.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Default Docker-in-Docker"})]}),s.jsxs("div",{className:"muted cfg-note",children:["On (default): new sandboxes run ",s.jsx("b",{children:"privileged"})," so Docker works inside them (build images, run",s.jsx("code",{children:" docker compose"}),"). Off gives a tighter, unprivileged box — pick this if you don't need Docker and want stronger isolation. A single project can override this when it's created or in its Config tab."]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:U,onChange:G=>Y(G.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Reuse a repo's DinD cache across projects"})]}),s.jsxs("div",{className:"muted cfg-note",children:["On (default): a project created ",s.jsx("b",{children:"from a repo"})," auto-starts from that repo's DinD baseline (built images + volumes), so a second project from the same repo doesn't rebuild from scratch. The first such project ",s.jsx("b",{children:"auto-saves its build as the baseline when you stop it"})," (only if none exists — it never overwrites one). You can also save/update it manually in a project's Config tab. Off makes every project start with an empty inner Docker."]})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["PR merging ",s.jsx("span",{className:"muted",children:"— defaults for the Merge button on a PR"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("span",{className:"cfg-ssh-name",children:"Default merge mode"}),s.jsxs("select",{className:"cfg-select",value:I,onChange:G=>A(G.target.value),children:[s.jsx("option",{value:"host",children:"Merge with host — rebase & merge on the host (fast, not sandboxed)"}),s.jsx("option",{value:"sandbox",children:"Merge with sandbox — rebase & merge in a one-shot container"}),s.jsx("option",{value:"plain",children:"Merge — plain gh merge, no rebase"})]}),s.jsxs("div",{className:"muted cfg-note",children:['Which action the Merge button runs by default. The ▾ next to it always lets you pick a different mode per-merge. "Sandbox" and "host" run Claude with the editable ',s.jsx("code",{children:"pr.merge"}),' prompt (Automations → Prompts) to rebase onto the base branch, resolve conflicts, and merge; "host" skips the container for speed but ',s.jsx("b",{children:"is not sandboxed"}),"."]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("span",{className:"cfg-ssh-name",children:"Default merge strategy"}),s.jsxs("select",{className:"cfg-select",value:H,onChange:G=>J(G.target.value),children:[s.jsx("option",{value:"",children:"Ask per repo (remember the first choice)"}),s.jsx("option",{value:"squash",children:"Squash and merge"}),s.jsx("option",{value:"merge",children:"Create a merge commit"}),s.jsx("option",{value:"rebase",children:"Rebase and merge"})]}),s.jsx("div",{className:"muted cfg-note",children:'The method used when merging. A repo can set its own preference (which wins); leave this on "Ask per repo" to be prompted the first time you merge each repo and have that choice remembered for it. Only methods your GitHub repo actually allows are offered.'})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:q,onChange:G=>W(G.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Auto-remove the merge sandbox once merged"})]}),s.jsx("div",{className:"muted cfg-note",children:'On (default): after a "merge with sandbox" job lands the PR, its one-shot container is torn down automatically. Turn off if you want to inspect how conflicts were resolved before removing it.'})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["AGENTS.md context ",s.jsx("span",{className:"muted",children:"— when to nag that a repo's agent context is stale"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Flag stale after (days)"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",placeholder:String(t.agent_context_stale_days_default),value:X,onChange:G=>Q(G.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.agent_context_stale_days_default," days ≈ 3 months). A banner then nudges you to regenerate a repo's ",s.jsx("code",{children:"AGENTS.md"})," — on the repo and on any sandbox or PR review derived from it. Set a negative value to turn the check off."]})]})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["Assistant ",s.jsx("span",{className:"muted",children:"— what the app-wide Claude chat can do"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"radio",name:"assistant-cap",checked:re!=="act",onChange:()=>dt("readonly")})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Read-only — look, don't change"})]}),s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"radio",name:"assistant-cap",checked:re==="act",onChange:()=>dt("act")})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Can act — run corral api (create issues, start projects, run flows)"})]}),s.jsxs("div",{className:"muted cfg-note",children:['Governs the app-wide chat dock. "Can act" still needs API writes (above) enabled before it can actually change anything.',re===null&&" Not set yet — you'll be asked the first time you open the chat."]})]})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn",disabled:k,onClick:wt,children:k?"Applying…":"Apply"}),n&&s.jsx("span",{className:`cfg-msg ${n.err?"s-4xx":"s-2xx"}`,children:n.text})]})]})]})]})}function Nv(e){var t;try{return((t=JSON.parse(e.spec))==null?void 0:t.script)||""}catch{return""}}function Ev({repoId:e}){const t=!!e,r=t?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState(null),[o,u]=C.useState(null),[d,m]=C.useState(""),[f,g]=C.useState(""),[w,S]=C.useState(!1),v=C.useCallback(()=>{ee(`/api/actions${r}`).then(_=>i((_.actions||[]).filter(j=>j.kind==="bash"))).catch(_=>y({text:_.message,err:!0}))},[r]);C.useEffect(()=>{v()},[v]);const p=()=>{u(null),m(""),g(Lv),S(!0)},c=_=>{u(_.id),m(_.name),g(Nv(_)),S(!0)},a=async()=>{if(!d.trim()){y({text:"give the script a name",err:!0});return}const _=JSON.stringify({script:f});try{o!=null?await fetch(`/api/actions/${o}`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d,spec:_})}):await oe("/api/actions",{name:d,kind:"bash",spec:_,scope:t?"repo":"global",repoId:t?e:void 0}),y({text:"✓ script saved",err:!1}),S(!1),v()}catch(j){y({text:j.message,err:!0})}},l=async _=>{await fetch(`/api/actions/${_}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),v()};return s.jsxs("div",{className:"scripts-lib",children:[h&&s.jsx("div",{className:`auto-msg${h.err?" err":""}`,children:h.text}),s.jsx("p",{className:"auto-hint",style:{opacity:.85},children:'Reusable bash scripts. Save one here, then pick it from a "run a script" step or add it to a flow. Scripts run on your host machine (see the callout in the editor).'}),n.length===0?s.jsx("p",{className:"auto-empty",children:"No saved scripts yet."}):s.jsxs("table",{className:"auto-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Scope"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:n.map(_=>s.jsxs("tr",{children:[s.jsx("td",{children:_.name}),s.jsx("td",{children:_.scope}),s.jsx("td",{children:(!t||_.scope==="repo")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>c(_),children:"edit"}),s.jsx("button",{type:"button",className:"auto-del",onClick:()=>l(_.id),children:"delete"})]})})]},_.id))})]}),w?s.jsxs("div",{className:"auto-create",children:[s.jsx("h4",{className:"auto-mgr-h",children:o!=null?"Edit script":"New script"}),s.jsx("input",{className:"auto-input",style:{width:"100%",marginBottom:"0.4rem"},placeholder:"script name",value:d,onChange:_=>m(_.target.value)}),s.jsx(Id,{script:f,onChange:g}),o!=null&&s.jsx(Rv,{actionId:o,script:f}),s.jsxs("div",{className:"auto-row",style:{marginTop:"0.5rem"},children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:a,children:"Save script"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:()=>S(!1),children:"Cancel"})]}),o==null&&s.jsx("p",{className:"auto-hint",style:{opacity:.7,marginTop:"0.4rem"},children:"Save the script first, then re-open it to set secrets (API keys, etc.) it needs."})]}):s.jsx("button",{type:"button",className:"auto-btn",onClick:p,style:{marginTop:"0.5rem"},children:"+ New script"})]})}function Rv({actionId:e,script:t}){const[r,n]=C.useState([]),[i,h]=C.useState({}),[y,o]=C.useState(""),[u,d]=C.useState(null),m=C.useCallback(()=>{ee(`/api/actions/${e}/secrets`).then(S=>n(S.secrets||[])).catch(()=>{})},[e]);C.useEffect(()=>{m()},[e,t]);const f=async()=>{const S=Object.entries(i).filter(([,v])=>v!=="").map(([v,p])=>({name:v,value:p}));if(S.length===0){d("nothing to save");return}try{await fetch(`/api/actions/${e}/secrets`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({secrets:S})}),h({}),d("✓ secrets saved (stored in your Keychain, injected at run)"),m()}catch(v){d(v.message)}},g=async S=>{await fetch(`/api/actions/${e}/secrets`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({remove:[S]})}).catch(()=>{}),m()},w=()=>{const S=y.trim().toUpperCase().replace(/[^A-Z0-9_]/g,"_");S&&!r.some(v=>v.name===S)&&(n(v=>[...v,{name:S,set:!1}]),o(""))};return s.jsxs("div",{className:"script-secrets",style:{marginTop:"0.6rem",borderTop:"1px solid var(--con-line, #2a3a36)",paddingTop:"0.5rem"},children:[s.jsx("div",{className:"auto-mgr-h",style:{marginBottom:"0.25rem"},children:"Secrets"}),s.jsx("p",{className:"auto-hint",style:{opacity:.75,marginTop:0},children:"Env vars this script needs (detected from the body). Values are kept in your Keychain, injected into the script's environment when it runs, and stripped from host-Claude conversations."}),r.length===0?s.jsx("p",{className:"auto-empty",style:{opacity:.7},children:"No secrets detected. Add one if the script needs an API key."}):s.jsx("table",{className:"auto-table",children:s.jsx("tbody",{children:r.map(S=>s.jsxs("tr",{children:[s.jsx("td",{style:{fontFamily:"ui-monospace, monospace",whiteSpace:"nowrap"},children:S.name}),s.jsx("td",{style:{width:"100%"},children:s.jsx("input",{className:"auto-input",type:"password",style:{width:"100%"},placeholder:S.set?`set (${S.masked}) — leave blank to keep`:"enter value",value:i[S.name]??"",onChange:v=>h(p=>({...p,[S.name]:v.target.value}))})}),s.jsx("td",{children:S.set&&s.jsx("button",{type:"button",className:"auto-del",onClick:()=>g(S.name),children:"remove"})})]},S.name))})}),s.jsxs("div",{className:"auto-row",style:{marginTop:"0.4rem",gap:"0.4rem"},children:[s.jsx("input",{className:"auto-input",style:{maxWidth:"16rem"},placeholder:"+ add a secret var (e.g. FRESHDESK_API_KEY)",value:y,onChange:S=>o(S.target.value),onKeyDown:S=>S.key==="Enter"&&(S.preventDefault(),w())}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:w,children:"add"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:f,children:"Save secrets"})]}),u&&s.jsx("div",{className:"auto-msg",style:{marginTop:"0.3rem"},children:u})]})}const Lv=`#!/usr/bin/env bash +`)),m([]),g({});const Se={};(te.ssh_keys||[]).forEach(Te=>Se[fs(Te)]=!0),p(Se);const Ut=new Set((te.available_ssh_keys||[]).map(Te=>Te.name));_((te.ssh_keys||[]).filter(Te=>!Ut.has(fs(Te)))),E(te.update_repo||""),T(te.log_retention_days?String(te.log_retention_days):""),B(te.log_max_rows?String(te.log_max_rows):""),K(te.conv_retention_days?String(te.conv_retention_days):""),$(te.conv_max_rows?String(te.conv_max_rows):""),A(!!te.api_writes_enabled),O(te.dind_default!==!1),F(te.dind_repo_cache_default!==!1),X(te.merge_strategy||""),D(te.merge_mode||"host"),H(te.merge_auto_teardown!==!1),Q(te.agent_context_stale_days?String(te.agent_context_stale_days):""),Y&&i({text:Y,err:!1})}).catch(te=>i({text:`failed to load: ${te.message}`,err:!0})),ee("/api/chat/capability").then(te=>ie(te.configured?te.capability:null)).catch(()=>{})},[]);C.useEffect(()=>Ce(),[Ce]);function ae(){const Y=[];return((t==null?void 0:t.available_ssh_keys)||[]).forEach(te=>{v[te.name]&&Y.push(te.name)}),l.forEach(te=>{v[fs(te)]!==!1&&Y.push(te)}),Y}async function dt(Y){ie(Y);try{const te=await fetch("/api/chat/capability",{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({capability:Y})});if(!te.ok)throw new Error(`HTTP ${te.status}`);i({text:`✓ assistant set to ${Y==="act"?"can act":"read-only"}`,err:!1})}catch(te){i({text:`couldn't update assistant: ${te.message}`,err:!0})}}async function wt(){const Y={};d.length&&(Y.set_creds=d.slice());const te=Object.keys(f).filter(Se=>f[Se]);te.length&&(Y.unset_creds=te),Y.monitor_hosts=he(h),Y.mitm_ports=he(o),Y.ssh_keys=ae(),Y.update_repo=N.trim(),Y.log_retention_days=L.trim()?Math.max(0,parseInt(L,10)||0):0,Y.log_max_rows=P.trim()?Math.max(0,parseInt(P,10)||0):0,Y.conv_retention_days=U.trim()?Math.max(0,parseInt(U,10)||0):0,Y.conv_max_rows=q.trim()?Math.max(0,parseInt(q,10)||0):0,Y.api_writes_enabled=R,Y.dind_default=M,Y.dind_repo_cache_default=W,Y.merge_strategy=z,Y.merge_mode=I,Y.merge_auto_teardown=V,Y.agent_context_stale_days=J.trim()&&parseInt(J,10)||0,x(!0);try{const Se=await oe("/global/apply",Y);Ce((Se.results||[]).join(" • ")||"✓ saved")}catch(Se){i({text:`apply failed: ${Se.message}`,err:!0})}finally{x(!1)}}async function nt(){b(!1);try{await je("/global/populate",{}),b(!0),i({text:"complete the prompts in the terminal; credentials refresh here when done",err:!1})}catch(Y){i({text:`could not start: ${Y.message}`,err:!0})}}function ft(){const Y=w.host.trim().toLowerCase(),te=w.name.trim();if(!Y||!te||!w.value){i({text:"credential needs host, name, and value",err:!0});return}m(Se=>[...Se,{host:Y,kind:w.kind,name:te,value:w.value}]),S({host:"",kind:"header",name:"",value:""}),i({text:"credential queued — click Apply",err:!1})}if(!t)return s.jsx("p",{className:"muted",style:{padding:"1rem"},children:"loading global settings…"});const Ie=(t.available_ssh_keys||[]).map(Y=>({value:Y.name,meta:[Y.type,Y.comment].filter(Boolean).join(" ")})),Le=l.map(Y=>({value:Y,meta:"custom path"}));return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"brand-back",title:"Back to all projects",children:"←"}),s.jsx("span",{className:"brand-name",children:"corral"}),s.jsx("span",{className:"brand-sub",children:"global settings"})]})}),s.jsxs("main",{className:"global-wrap",children:[s.jsxs("p",{className:"global-intro",children:["Settings that apply across every project. Credentials here are shared by all projects (a project can still override per host). Defaults are inherited by new projects when you run ",s.jsx("code",{children:"corral init"}),"."]}),s.jsxs("div",{id:"global-root",children:[s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Do Not Disturb ",s.jsx("span",{className:"muted",children:"— quiet hours for notifications (this browser)"})]}),s.jsxs("label",{className:"row",style:{marginBottom:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:e.config.enabled,onChange:Y=>e.setEnabled(Y.target.checked)}),s.jsxs("span",{children:["Enable Do Not Disturb — silence the chime and toasts outside your active hours.",e.config.enabled&&e.quiet&&s.jsx("span",{className:"dnd-now",children:" · quiet right now 🌙"})]})]}),s.jsxs("div",{className:"row dnd-hours",style:{opacity:e.config.enabled?1:.5},children:[s.jsx("span",{className:"cfg-label",children:"Notify me between"}),s.jsx("select",{className:"cfg-edit dnd-hour-select",disabled:!e.config.enabled,value:e.config.startHour,onChange:Y=>e.setWindow(Number(Y.target.value),e.config.endHour),children:qc.map(Y=>s.jsx("option",{value:Y,children:Gc(Y)},Y))}),s.jsx("span",{children:"and"}),s.jsx("select",{className:"cfg-edit dnd-hour-select",disabled:!e.config.enabled,value:e.config.endHour,onChange:Y=>e.setWindow(e.config.startHour,Number(Y.target.value)),children:qc.map(Y=>s.jsx("option",{value:Y,children:Gc(Y)},Y))}),s.jsx("span",{className:"muted cfg-note",children:"uses this browser's local time (default 9am–5pm)"})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Shared credentials ",s.jsx("span",{className:"muted",children:"— all projects, mtime-reloaded live"})]}),s.jsx("div",{className:"muted global-path",children:t.creds_path}),s.jsxs("table",{className:"cfg-creds",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Host"}),s.jsx("th",{children:"Injects"}),s.jsx("th",{children:"Value"}),s.jsx("th",{})]})}),s.jsxs("tbody",{children:[(t.credentials||[]).length===0&&s.jsx("tr",{children:s.jsx("td",{className:"muted",colSpan:4,children:"none set"})}),(t.credentials||[]).map(Y=>s.jsxs("tr",{style:{opacity:f[Y.host]?.4:1},children:[s.jsx("td",{children:Y.host}),s.jsxs("td",{children:[Y.kind,": ",Y.name]}),s.jsx("td",{className:"cred-mask",children:Y.masked}),s.jsx("td",{children:s.jsx("button",{className:"cfg-cred-rm",onClick:()=>{g(te=>({...te,[Y.host]:!0})),i({text:"credential queued for removal — click Apply",err:!1})},children:"remove"})})]},Y.host)),d.map((Y,te)=>s.jsxs("tr",{children:[s.jsx("td",{children:Y.host}),s.jsxs("td",{children:[Y.kind,": ",Y.name]}),s.jsx("td",{className:"s-2xx",children:"pending"}),s.jsx("td",{})]},`new-${te}`))]})]}),s.jsxs("div",{className:"cfg-cred-add",children:[s.jsx("input",{placeholder:"host (api.foo.com)",value:w.host,onChange:Y=>S({...w,host:Y.target.value})}),s.jsxs("select",{value:w.kind,onChange:Y=>S({...w,kind:Y.target.value}),children:[s.jsx("option",{value:"header",children:"header"}),s.jsx("option",{value:"url_param",children:"url_param"})]}),s.jsx("input",{placeholder:"name (X-API-Key)",value:w.name,onChange:Y=>S({...w,name:Y.target.value})}),s.jsx("input",{placeholder:"value (secret)",type:"password",value:w.value,onChange:Y=>S({...w,value:Y.target.value})}),s.jsx("button",{className:"cfg-btn",onClick:ft,children:"Add"})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:nt,children:"Populate from Claude…"}),s.jsxs("span",{className:"muted",children:["runs ",s.jsx("code",{children:"claude setup-token"})," in a terminal below"]})]}),j&&s.jsxs("div",{className:"populate-term",style:{display:"block",height:320},children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"claude setup-token · answer the prompts"]}),s.jsx(Zs,{fullPath:"/global/populate/ws"})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Defaults for new projects ",s.jsxs("span",{className:"muted",children:["— inherited at ",s.jsx("code",{children:"corral init"})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Default monitor-list"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("textarea",{className:"cfg-edit",rows:3,spellCheck:!1,value:h,onChange:Y=>y(Y.target.value)}),s.jsx("div",{className:"muted cfg-note",children:"empty = new projects monitor all allowed hosts"})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Default mitm-ports"}),s.jsx("div",{className:"cfg-value",children:s.jsx("textarea",{className:"cfg-edit",rows:2,spellCheck:!1,value:o,onChange:Y=>u(Y.target.value)})})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Default SSH keys ",s.jsx("span",{className:"muted",children:"— loaded by EVERY project's scoped agent"})]}),s.jsx("div",{className:"muted global-path",children:t.ssh_keys_path}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Keys"}),s.jsxs("div",{className:"cfg-value",children:[Ie.length+Le.length===0?s.jsx("div",{className:"muted cfg-note",children:"no keys found under ~/.ssh"}):s.jsx("div",{className:"cfg-ssh-list",children:[...Ie,...Le].map(Y=>s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",className:"g-ssh-key",checked:!!v[fs(Y.value)],onChange:te=>p(Se=>({...Se,[fs(Y.value)]:te.target.checked}))})," ",s.jsx("span",{className:"cfg-ssh-name",children:fs(Y.value)})," ",Y.meta&&s.jsx("span",{className:"muted cfg-ssh-meta",children:Y.meta})]},Y.value))}),s.jsxs("div",{className:"cfg-ssh-extra-add",children:[s.jsx("input",{placeholder:"other key path (~/.ssh/... or /abs/path)",value:c,onChange:Y=>a(Y.target.value)}),s.jsx("button",{className:"cfg-btn cfg-btn-ghost",onClick:()=>{const Y=c.trim();Y&&(_(te=>te.includes(Y)?te:[...te,Y]),p(te=>({...te,[fs(Y)]:!0})),a(""))},children:"+ add path"})]})]})]}),s.jsx("div",{className:"muted cfg-note",children:"The container can USE these keys (sign/push) but never reads the key bytes — only the agent socket is mounted. Projects can add more in their Config tab."})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Update source ",s.jsxs("span",{className:"muted",children:["— where ",s.jsx("code",{children:"corral update"})," pulls releases from"]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Repo or URL"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit",spellCheck:!1,placeholder:t.update_repo_default,value:N,onChange:Y=>E(Y.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["A GitHub ",s.jsx("code",{children:"owner/name"}),", or a full release URL for another host (e.g."," ",s.jsx("code",{children:"https://git.example.com/owner/repo"}),") that uses the same"," ",s.jsx("code",{children:"/releases/latest"})," + ",s.jsx("code",{children:"/releases/download//…"})," layout. Leave blank for the default (",s.jsx("code",{children:t.update_repo_default}),")."]})]})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Log retention ",s.jsxs("span",{className:"muted",children:["— how long the ",s.jsx("a",{href:"/automations/logs",children:"activity log"})," is kept"]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Keep for (days)"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.log_retention_days_default),value:L,onChange:Y=>T(Y.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.log_retention_days_default," days). Older entries are pruned hourly."]})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Max entries"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.log_max_rows_default),value:P,onChange:Y=>B(Y.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.log_max_rows_default.toLocaleString()," rows). The newest are kept."]})]})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["Conversation retention ",s.jsx("span",{className:"muted",children:"— how long captured Claude conversations are kept"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Keep for (days)"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.conv_retention_days_default),value:U,onChange:Y=>K(Y.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.conv_retention_days_default," days). Kept even after a project is deleted; pruned hourly. Stored separately from the activity log."]})]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Max conversations"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",min:0,placeholder:String(t.conv_max_rows_default),value:q,onChange:Y=>$(Y.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.conv_max_rows_default.toLocaleString()," conversations). The newest are kept."]})]})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["API access ",s.jsxs("span",{className:"muted",children:["— let the ",s.jsx("code",{children:"corral api"})," CLI and Claude make changes"]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:R,onChange:Y=>A(Y.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Allow API writes"})]}),s.jsx("div",{className:"muted cfg-note",children:"Reads (listing flows, logs, PRs) are always allowed. With this off, the CLI and Claude can look but not act; turn it on to let them start projects, create issues, and run flows. Off by default."})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["New sandboxes ",s.jsx("span",{className:"muted",children:"— defaults for projects you create"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:M,onChange:Y=>O(Y.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Default Docker-in-Docker"})]}),s.jsxs("div",{className:"muted cfg-note",children:["On (default): new sandboxes run ",s.jsx("b",{children:"privileged"})," so Docker works inside them (build images, run",s.jsx("code",{children:" docker compose"}),"). Off gives a tighter, unprivileged box — pick this if you don't need Docker and want stronger isolation. A single project can override this when it's created or in its Config tab."]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:W,onChange:Y=>F(Y.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Reuse a repo's DinD cache across projects"})]}),s.jsxs("div",{className:"muted cfg-note",children:["On (default): a project created ",s.jsx("b",{children:"from a repo"})," auto-starts from that repo's DinD baseline (built images + volumes), so a second project from the same repo doesn't rebuild from scratch. The first such project ",s.jsx("b",{children:"auto-saves its build as the baseline when you stop it"})," (only if none exists — it never overwrites one). You can also save/update it manually in a project's Config tab. Off makes every project start with an empty inner Docker."]})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["PR merging ",s.jsx("span",{className:"muted",children:"— defaults for the Merge button on a PR"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("span",{className:"cfg-ssh-name",children:"Default merge mode"}),s.jsxs("select",{className:"cfg-select",value:I,onChange:Y=>D(Y.target.value),children:[s.jsx("option",{value:"host",children:"Merge with host — rebase & merge on the host (fast, not sandboxed)"}),s.jsx("option",{value:"sandbox",children:"Merge with sandbox — rebase & merge in a one-shot container"}),s.jsx("option",{value:"plain",children:"Merge — plain gh merge, no rebase"})]}),s.jsxs("div",{className:"muted cfg-note",children:['Which action the Merge button runs by default. The ▾ next to it always lets you pick a different mode per-merge. "Sandbox" and "host" run Claude with the editable ',s.jsx("code",{children:"pr.merge"}),' prompt (Automations → Prompts) to rebase onto the base branch, resolve conflicts, and merge; "host" skips the container for speed but ',s.jsx("b",{children:"is not sandboxed"}),"."]})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("span",{className:"cfg-ssh-name",children:"Default merge strategy"}),s.jsxs("select",{className:"cfg-select",value:z,onChange:Y=>X(Y.target.value),children:[s.jsx("option",{value:"",children:"Ask per repo (remember the first choice)"}),s.jsx("option",{value:"squash",children:"Squash and merge"}),s.jsx("option",{value:"merge",children:"Create a merge commit"}),s.jsx("option",{value:"rebase",children:"Rebase and merge"})]}),s.jsx("div",{className:"muted cfg-note",children:'The method used when merging. A repo can set its own preference (which wins); leave this on "Ask per repo" to be prompted the first time you merge each repo and have that choice remembered for it. Only methods your GitHub repo actually allows are offered.'})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"checkbox",checked:V,onChange:Y=>H(Y.target.checked)})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Auto-remove the merge sandbox once merged"})]}),s.jsx("div",{className:"muted cfg-note",children:'On (default): after a "merge with sandbox" job lands the PR, its one-shot container is torn down automatically. Turn off if you want to inspect how conflicts were resolved before removing it.'})]})]}),s.jsxs("section",{className:"cfg-zone",children:[s.jsxs("h3",{children:["AGENTS.md context ",s.jsx("span",{className:"muted",children:"— when to nag that a repo's agent context is stale"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsx("div",{className:"cfg-label",children:"Flag stale after (days)"}),s.jsxs("div",{className:"cfg-value",children:[s.jsx("input",{className:"cfg-edit dnd-hour-select",type:"number",placeholder:String(t.agent_context_stale_days_default),value:J,onChange:Y=>Q(Y.target.value)}),s.jsxs("div",{className:"muted cfg-note",children:["Blank = default (",t.agent_context_stale_days_default," days ≈ 3 months). A banner then nudges you to regenerate a repo's ",s.jsx("code",{children:"AGENTS.md"})," — on the repo and on any sandbox or PR review derived from it. Set a negative value to turn the check off."]})]})]})]}),s.jsxs("section",{className:"cfg-section",children:[s.jsxs("h3",{children:["Assistant ",s.jsx("span",{className:"muted",children:"— what the app-wide Claude chat can do"})]}),s.jsxs("div",{className:"cfg-field",children:[s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"radio",name:"assistant-cap",checked:re!=="act",onChange:()=>dt("readonly")})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Read-only — look, don't change"})]}),s.jsxs("label",{className:"cfg-ssh-item",children:[s.jsx("input",{type:"radio",name:"assistant-cap",checked:re==="act",onChange:()=>dt("act")})," ",s.jsx("span",{className:"cfg-ssh-name",children:"Can act — run corral api (create issues, start projects, run flows)"})]}),s.jsxs("div",{className:"muted cfg-note",children:['Governs the app-wide chat dock. "Can act" still needs API writes (above) enabled before it can actually change anything.',re===null&&" Not set yet — you'll be asked the first time you open the chat."]})]})]}),s.jsxs("div",{className:"cfg-actions",children:[s.jsx("button",{className:"cfg-btn",disabled:k,onClick:wt,children:k?"Applying…":"Apply"}),n&&s.jsx("span",{className:`cfg-msg ${n.err?"s-4xx":"s-2xx"}`,children:n.text})]})]})]})]})}function Nv(e){var t;try{return((t=JSON.parse(e.spec))==null?void 0:t.script)||""}catch{return""}}function Ev({repoId:e}){const t=!!e,r=t?`?repo=${encodeURIComponent(e)}`:"",[n,i]=C.useState([]),[h,y]=C.useState(null),[o,u]=C.useState(null),[d,m]=C.useState(""),[f,g]=C.useState(""),[w,S]=C.useState(!1),v=C.useCallback(()=>{ee(`/api/actions${r}`).then(_=>i((_.actions||[]).filter(j=>j.kind==="bash"))).catch(_=>y({text:_.message,err:!0}))},[r]);C.useEffect(()=>{v()},[v]);const p=()=>{u(null),m(""),g(Lv),S(!0)},c=_=>{u(_.id),m(_.name),g(Nv(_)),S(!0)},a=async()=>{if(!d.trim()){y({text:"give the script a name",err:!0});return}const _=JSON.stringify({script:f});try{o!=null?await fetch(`/api/actions/${o}`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d,spec:_})}):await oe("/api/actions",{name:d,kind:"bash",spec:_,scope:t?"repo":"global",repoId:t?e:void 0}),y({text:"✓ script saved",err:!1}),S(!1),v()}catch(j){y({text:j.message,err:!0})}},l=async _=>{await fetch(`/api/actions/${_}`,{method:"DELETE",credentials:"same-origin"}).catch(()=>{}),v()};return s.jsxs("div",{className:"scripts-lib",children:[h&&s.jsx("div",{className:`auto-msg${h.err?" err":""}`,children:h.text}),s.jsx("p",{className:"auto-hint",style:{opacity:.85},children:'Reusable bash scripts. Save one here, then pick it from a "run a script" step or add it to a flow. Scripts run on your host machine (see the callout in the editor).'}),n.length===0?s.jsx("p",{className:"auto-empty",children:"No saved scripts yet."}):s.jsxs("table",{className:"auto-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Scope"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:n.map(_=>s.jsxs("tr",{children:[s.jsx("td",{children:_.name}),s.jsx("td",{children:_.scope}),s.jsx("td",{children:(!t||_.scope==="repo")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>c(_),children:"edit"}),s.jsx("button",{type:"button",className:"auto-del",onClick:()=>l(_.id),children:"delete"})]})})]},_.id))})]}),w?s.jsxs("div",{className:"auto-create",children:[s.jsx("h4",{className:"auto-mgr-h",children:o!=null?"Edit script":"New script"}),s.jsx("input",{className:"auto-input",style:{width:"100%",marginBottom:"0.4rem"},placeholder:"script name",value:d,onChange:_=>m(_.target.value)}),s.jsx(Id,{script:f,onChange:g}),o!=null&&s.jsx(Rv,{actionId:o,script:f}),s.jsxs("div",{className:"auto-row",style:{marginTop:"0.5rem"},children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:a,children:"Save script"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:()=>S(!1),children:"Cancel"})]}),o==null&&s.jsx("p",{className:"auto-hint",style:{opacity:.7,marginTop:"0.4rem"},children:"Save the script first, then re-open it to set secrets (API keys, etc.) it needs."})]}):s.jsx("button",{type:"button",className:"auto-btn",onClick:p,style:{marginTop:"0.5rem"},children:"+ New script"})]})}function Rv({actionId:e,script:t}){const[r,n]=C.useState([]),[i,h]=C.useState({}),[y,o]=C.useState(""),[u,d]=C.useState(null),m=C.useCallback(()=>{ee(`/api/actions/${e}/secrets`).then(S=>n(S.secrets||[])).catch(()=>{})},[e]);C.useEffect(()=>{m()},[e,t]);const f=async()=>{const S=Object.entries(i).filter(([,v])=>v!=="").map(([v,p])=>({name:v,value:p}));if(S.length===0){d("nothing to save");return}try{await fetch(`/api/actions/${e}/secrets`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({secrets:S})}),h({}),d("✓ secrets saved (stored in your Keychain, injected at run)"),m()}catch(v){d(v.message)}},g=async S=>{await fetch(`/api/actions/${e}/secrets`,{method:"PUT",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({remove:[S]})}).catch(()=>{}),m()},w=()=>{const S=y.trim().toUpperCase().replace(/[^A-Z0-9_]/g,"_");S&&!r.some(v=>v.name===S)&&(n(v=>[...v,{name:S,set:!1}]),o(""))};return s.jsxs("div",{className:"script-secrets",style:{marginTop:"0.6rem",borderTop:"1px solid var(--con-line, #2a3a36)",paddingTop:"0.5rem"},children:[s.jsx("div",{className:"auto-mgr-h",style:{marginBottom:"0.25rem"},children:"Secrets"}),s.jsx("p",{className:"auto-hint",style:{opacity:.75,marginTop:0},children:"Env vars this script needs (detected from the body). Values are kept in your Keychain, injected into the script's environment when it runs, and stripped from host-Claude conversations."}),r.length===0?s.jsx("p",{className:"auto-empty",style:{opacity:.7},children:"No secrets detected. Add one if the script needs an API key."}):s.jsx("table",{className:"auto-table",children:s.jsx("tbody",{children:r.map(S=>s.jsxs("tr",{children:[s.jsx("td",{style:{fontFamily:"ui-monospace, monospace",whiteSpace:"nowrap"},children:S.name}),s.jsx("td",{style:{width:"100%"},children:s.jsx("input",{className:"auto-input",type:"password",style:{width:"100%"},placeholder:S.set?`set (${S.masked}) — leave blank to keep`:"enter value",value:i[S.name]??"",onChange:v=>h(p=>({...p,[S.name]:v.target.value}))})}),s.jsx("td",{children:S.set&&s.jsx("button",{type:"button",className:"auto-del",onClick:()=>g(S.name),children:"remove"})})]},S.name))})}),s.jsxs("div",{className:"auto-row",style:{marginTop:"0.4rem",gap:"0.4rem"},children:[s.jsx("input",{className:"auto-input",style:{maxWidth:"16rem"},placeholder:"+ add a secret var (e.g. FRESHDESK_API_KEY)",value:y,onChange:S=>o(S.target.value),onKeyDown:S=>S.key==="Enter"&&(S.preventDefault(),w())}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:w,children:"add"}),s.jsx("button",{type:"button",className:"auto-btn",onClick:f,children:"Save secrets"})]}),u&&s.jsx("div",{className:"auto-msg",style:{marginTop:"0.3rem"},children:u})]})}const Lv=`#!/usr/bin/env bash # Runs on the machine hosting this dashboard (NOT the sandbox), with your # shell environment and any CLIs you're already signed in to (gh, aws, …). # Event details arrive as env vars: $CORRAL_PR_NUMBER, $CORRAL_PR_URL, etc. @@ -130,4 +130,4 @@ description: >- Keep the body a short runbook: the exact commands, the failure to watch for, the fix. Only what the model wouldn't already know. -`;function Mv(){const[e,t]=C.useState([]),[r,n]=C.useState(null),[i,h]=C.useState(""),[y,o]=C.useState(""),[u,d]=C.useState(!0),[m,f]=C.useState(null),g=C.useCallback(()=>{ee("/api/skills?scope=global").then(c=>t(c.skills||[])).catch(c=>f({text:c.message,err:!0}))},[]);C.useEffect(()=>g(),[g]);function w(){n("new"),h(""),o(Ov),d(!0)}function S(c){n(c.id),h(c.name),o(c.content),d(c.autoAll)}async function v(){if(!i.trim()||!y.trim()){f({text:"A name and SKILL.md content are required.",err:!0});return}try{r==="new"?await oe("/api/skills",{scope:"global",name:i.trim(),content:y,autoAll:u}):typeof r=="number"&&await Un(`/api/skills/${r}`,{name:i.trim(),content:y,autoAll:u}),n(null),f({text:`Saved "${i.trim()}".`,err:!1}),g()}catch(c){f({text:`Couldn't save: ${c.message}`,err:!0})}}async function p(c){if(confirm(`Delete the global "${c.name}" skill? It will be removed from every repo that uses it.`))try{await St(`/api/skills/${c.id}`),g()}catch(a){f({text:`Couldn't delete: ${a.message}`,err:!0})}}return s.jsxs("section",{className:"auto-section",children:[s.jsxs("div",{className:"reposkills-head",children:[s.jsx("h2",{className:"auto-mgr-h",style:{marginTop:0},children:"Global skills"}),r===null&&s.jsx("button",{type:"button",className:"auto-btn",onClick:w,children:"+ New global skill"})]}),s.jsxs("p",{className:"auto-intro",style:{marginTop:0},children:["Skills shared across all repos. Turn on ",s.jsx("b",{children:"Add to all repos"})," to inject a skill into every sandbox by default; each repo can still toggle it on or off in its own Settings."]}),m&&s.jsx("div",{className:`auto-msg${m.err?" err":""}`,children:m.text}),r!==null?s.jsxs("div",{className:"reposkills-editor",children:[s.jsx("input",{className:"auto-input",placeholder:"skill name (letters, digits, - or _)",value:i,onChange:c=>h(c.target.value)}),s.jsx("textarea",{className:"auto-input reposkills-md",placeholder:"SKILL.md — YAML frontmatter (name, description) then the instructions.",value:y,onChange:c=>o(c.target.value),rows:12}),s.jsxs("p",{className:"auto-hint",children:["The ",s.jsx("code",{children:"description"})," is the one line the model matches to decide whether to load this skill. Say what it does ",s.jsx("b",{children:"and"})," name the situation — “Use this when…”. A topic label loses; a named situation fires."]}),s.jsxs("label",{className:"reposkills-autoall",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:c=>d(c.target.checked)})," ","Add to all repos by default"]}),s.jsxs("div",{className:"reposkills-editor-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:v,children:"Save skill"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>n(null),children:"Cancel"})]})]}):e.length===0?s.jsx("p",{className:"auto-empty",children:"No global skills yet. Add one to share it across every repo."}):s.jsx("ul",{className:"reposkills-list",children:e.map(c=>s.jsxs("li",{className:"reposkills-item",children:[s.jsxs("span",{className:"reposkills-name",children:[c.name,c.autoAll&&s.jsx("span",{className:"reposkills-badge",children:"all repos"})]}),s.jsxs("div",{className:"reposkills-item-actions",children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>S(c),children:"edit"}),s.jsx("button",{type:"button",className:"reposkills-x",title:"Delete",onClick:()=>p(c),children:"×"})]})]},c.id))})]})}function Iv(){ds("console");const[e,t]=C.useState("automations");return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All repos"}),s.jsx("span",{className:"brand-name",children:"Automations"}),s.jsx(be,{to:"/global",className:"brand-sub",children:"global settings →"})]})}),s.jsxs("div",{className:"auto-page",children:[s.jsxs("div",{className:"tabs",style:{marginBottom:"1rem"},children:[s.jsx("button",{type:"button",className:`tab-btn${e==="automations"?" active":""}`,onClick:()=>t("automations"),children:"Automations"}),s.jsx("button",{type:"button",className:`tab-btn${e==="flows"?" active":""}`,onClick:()=>t("flows"),children:"Flows"}),s.jsx("button",{type:"button",className:`tab-btn${e==="scripts"?" active":""}`,onClick:()=>t("scripts"),children:"Scripts"})]}),e==="automations"&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"auto-intro",children:["Turn events into your own units of work. Each card is something Corral already does — add your own steps to run alongside it. These are ",s.jsx("b",{children:"global"})," defaults; per-repo overrides live in a repo's Settings tab."]}),s.jsx(Bd,{}),s.jsx(Mv,{}),s.jsx("section",{className:"auto-section",children:s.jsx(be,{to:"/automations/runs",className:"auto-runs-link",children:"View run history →"})})]}),e==="flows"&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"auto-intro",children:["Wire actions into a multi-step flow. Each step hands its result to the next as"," ",s.jsx("code",{children:"{{steps..output}}"}),"; a step can wait for others with ",s.jsx("b",{children:"after"}),". Run a flow now, or put it on a schedule."]}),s.jsx(Dv,{})]}),e==="scripts"&&s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"auto-mgr-h",style:{marginTop:0},children:"Saved scripts"}),s.jsx(Ev,{})]})]})]})}function Yc(e){switch(e){case"ok":return"run-ok";case"error":return"run-err";case"partial":return"run-partial";default:return"run-running"}}function Bv(e){try{return JSON.parse(e)||[]}catch{return[]}}function $v(){ds("console");const[e,t]=C.useState([]),[r,n]=C.useState({}),[i,h]=C.useState(null),y=C.useCallback(()=>{ee("/api/runs?limit=100").then(o=>t(o.runs||[])).catch(o=>h(o.message))},[]);return C.useEffect(()=>{y()},[y]),s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/automations",className:"back",children:"← Automations"}),s.jsx("span",{className:"brand-name",children:"Run history"}),s.jsx("button",{type:"button",className:"brand-sub auto-btn link",onClick:y,children:"⟳ refresh"})]})}),s.jsxs("div",{className:"auto-page",children:[i&&s.jsx("div",{className:"auto-msg err",children:i}),e.length===0?s.jsx("p",{className:"auto-empty",children:"No runs yet. Actions and hooks record their executions here."}):s.jsx("ul",{className:"run-list",children:e.map(o=>{const u=Bv(o.steps),d=!!r[o.id];return s.jsxs("li",{className:"run-item",children:[s.jsxs("button",{type:"button",className:"run-head",onClick:()=>n(m=>({...m,[o.id]:!m[o.id]})),children:[s.jsx("span",{className:`run-badge ${Yc(o.status)}`,children:o.status}),s.jsxs("span",{className:"run-what",children:[o.event?s.jsx("code",{children:o.event}):o.trigger,s.jsxs("span",{className:"run-meta",children:[o.trigger," · ",u.length," step",u.length===1?"":"s"]})]}),s.jsx("span",{className:"run-time",children:o.startedAt}),s.jsx("span",{className:"run-caret",children:d?"▾":"▸"})]}),d&&s.jsxs("div",{className:"run-steps",children:[u.length===0&&s.jsx("div",{className:"run-empty",children:"no steps recorded"}),u.map((m,f)=>s.jsxs("div",{className:"run-step",children:[s.jsxs("div",{className:"run-step-head",children:[s.jsx("span",{className:`run-dot ${Yc(m.status)}`}),s.jsx("b",{children:m.name||`#${m.actionId}`}),s.jsx("code",{className:"run-step-kind",children:m.kind}),s.jsxs("span",{className:"run-step-dur",children:[m.durationMs,"ms"]})]}),m.output&&s.jsx("pre",{className:"run-out",children:m.output}),m.error&&s.jsx("pre",{className:"run-out run-out-err",children:m.error})]},f)),o.context&&o.context!=="{}"&&s.jsxs("details",{className:"run-ctx",children:[s.jsx("summary",{children:"context"}),s.jsx("pre",{className:"run-out",children:o.context})]})]})]},o.id)})})]})]})}const Hv=["","info","warn","error","debug"];function Xc(e,t){return e==="error"||t==="error"?"log-error":e==="warn"||t==="partial"?"log-warn":"log-ok"}function $d(e){switch(e){case"ai":return"✨";case"pr-action":return"⑃";case"project":return"▤";case"automation":return"⚡";case"script":return"⚙";case"repo":return"◧";case"chat":return"💬";case"http":return"→";default:return"•"}}function Fv(e){const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Uv(){const[e,t]=C.useState([]),[r,n]=C.useState(0),[i,h]=C.useState(!1),[y,o]=C.useState(null),[u,d]=C.useState({}),[m,f]=C.useState(null),[g,w]=C.useState(null),[S,v]=C.useState(!1),p=C.useCallback(P=>{f(U=>U===P?(w(null),null):(w(null),v(!0),ee(`/api/logs/trace/${encodeURIComponent(P)}`).then(Y=>w(Y)).catch(()=>w(null)).finally(()=>v(!1)),P))},[]),[c,a]=C.useState(""),[l,_]=C.useState(""),[j,b]=C.useState(""),[k,x]=C.useState(""),[N,E]=C.useState(!1),[L,T]=C.useState([]),[O,B]=C.useState([]);C.useEffect(()=>{ee("/api/logs/facets").then(P=>{T(P.categories||[]),B(P.projects||[])}).catch(()=>{})},[]);const F=C.useRef(null),[z,K]=C.useState("");C.useEffect(()=>(F.current&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>K(k.trim()),300),()=>{F.current&&window.clearTimeout(F.current)}),[k]);const $=C.useCallback(P=>{const U=new URLSearchParams({limit:"60"});return P&&U.set("before",String(P)),c&&U.set("category",c),l&&U.set("project",l),j&&U.set("level",j),z&&U.set("q",z),U.toString()},[c,l,j,z]),R=C.useCallback(()=>{h(!0),o(null),ee(`/api/logs?${$(0)}`).then(P=>{t(P.logs||[]),n(P.nextCursor||0)}).catch(P=>o(P.message)).finally(()=>h(!1))},[$]);C.useEffect(()=>{R()},[R]);const D=()=>{!r||i||(h(!0),ee(`/api/logs?${$(r)}`).then(P=>{t(U=>[...U,...P.logs||[]]),n(P.nextCursor||0)}).catch(P=>o(P.message)).finally(()=>h(!1)))},M=e.filter(P=>!(N&&!c&&P.category==="http"));return s.jsxs("div",{className:"auto-page",children:[s.jsx("div",{className:"logs-panel-toolbar",children:s.jsx("button",{type:"button",className:"auto-btn link",onClick:R,children:"⟳ refresh"})}),s.jsxs("div",{className:"logs-filters",children:[s.jsx("input",{className:"auto-input logs-search",placeholder:"🔍 search logs…",value:k,onChange:P=>x(P.target.value)}),s.jsxs("select",{className:"auto-input",value:c,onChange:P=>a(P.target.value),children:[s.jsx("option",{value:"",children:"all categories"}),L.map(P=>s.jsx("option",{value:P,children:P},P))]}),O.length>0&&s.jsxs("select",{className:"auto-input",value:l,onChange:P=>_(P.target.value),children:[s.jsx("option",{value:"",children:"all projects"}),O.map(P=>s.jsx("option",{value:P,children:P},P))]}),s.jsx("select",{className:"auto-input",value:j,onChange:P=>b(P.target.value),children:Hv.map(P=>s.jsx("option",{value:P,children:P||"all levels"},P))}),s.jsxs("label",{className:"logs-hidehttp",children:[s.jsx("input",{type:"checkbox",checked:N,onChange:P=>E(P.target.checked),disabled:!!c}),"hide request logs"]})]}),y&&s.jsx("div",{className:"auto-msg err",children:y}),M.length===0&&!i?e.length>0&&N&&!c?s.jsxs("p",{className:"auto-empty",children:["Only request logs so far, and they're hidden."," ",s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>E(!1),children:"Show request logs"})]}):s.jsx("p",{className:"auto-empty",children:"No logs match. Activity is recorded here as it happens."}):s.jsx("ul",{className:"logs-list",children:M.map(P=>{const U=!!u[P.id],Y=P.meta&&P.meta!=="{}"||P.runId||P.traceId;return s.jsxs("li",{className:`logs-row ${Xc(P.level,P.status)}`,children:[s.jsxs("button",{type:"button",className:"logs-row-head",onClick:()=>Y&&d(H=>({...H,[P.id]:!H[P.id]})),children:[s.jsx("span",{className:"logs-time",children:Fv(P.ts)}),s.jsxs("span",{className:"logs-cat",title:P.category,children:[$d(P.category)," ",P.category]}),s.jsx("span",{className:"logs-msg",children:P.message}),P.status&&s.jsx("span",{className:`logs-status ${Xc(P.level,P.status)}`,children:P.status}),typeof P.durationMs=="number"&&P.durationMs>0&&s.jsxs("span",{className:"logs-dur",children:[P.durationMs,"ms"]}),Y&&s.jsx("span",{className:"logs-caret",children:U?"▾":"▸"})]}),U&&s.jsxs("div",{className:"logs-detail",children:[s.jsxs("div",{className:"logs-detail-meta",children:[s.jsx("span",{className:"logs-detail-k",children:"event"})," ",s.jsx("code",{children:P.event}),P.repoId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"logs-detail-k",children:"repo"})," ",s.jsx("code",{children:P.repoId})]}),P.projectId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"logs-detail-k",children:"project"})," ",s.jsx("code",{children:P.projectId})]})]}),P.meta&&P.meta!=="{}"&&s.jsx("pre",{className:"logs-detail-json",children:Wv(P.meta)}),s.jsxs("div",{className:"logs-detail-actions",children:[P.runId?s.jsxs(be,{to:"/automations/runs",className:"auto-btn link",children:["View run #",P.runId," →"]}):null,P.traceId?s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>p(P.traceId),children:m===P.traceId?"Hide trace ▾":"View trace ▸"}):null]}),P.traceId&&m===P.traceId&&s.jsx(Kv,{loading:S,trace:g,highlight:P.spanId})]})]},P.id)})}),s.jsx("div",{className:"logs-more",children:r?s.jsx("button",{type:"button",className:"auto-btn",disabled:i,onClick:D,children:i?"Loading…":"Load older"}):!i&&M.length>0&&s.jsx("span",{className:"auto-empty",children:"— end of logs —"})})]})}function zv(){ds("console");const[e,t]=C.useState("logs");return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All projects"}),s.jsx("span",{className:"brand-name",children:"Logs"})]})}),s.jsx("div",{className:"logs-page-tabs",children:s.jsxs("div",{className:"tabs",children:[s.jsx("button",{type:"button",className:`tab-btn${e==="logs"?" active":""}`,onClick:()=>t("logs"),children:"Activity log"}),s.jsx("button",{type:"button",className:`tab-btn${e==="conversations"?" active":""}`,onClick:()=>t("conversations"),children:"Conversations"})]})}),e==="logs"?s.jsx(Uv,{}):s.jsx(Md,{})]})}function Wv(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Hd(e,t,r){for(const n of e||[])r.push({span:n,depth:t}),Hd(n.children,t+1,r)}function Rn(e){if(!e)return NaN;const t=new Date(e).getTime();return isNaN(t)?NaN:t}function Kv({loading:e,trace:t,highlight:r}){if(e)return s.jsx("div",{className:"trace-view loading",children:"Loading trace…"});if(!t||t.roots.length===0)return s.jsx("div",{className:"trace-view empty",children:"No trace data."});const n=[];Hd(t.roots,0,n);let i=1/0,h=-1/0;for(const{span:o}of n){const u=Rn(o.startTs),d=Rn(o.endTs)||u;isNaN(u)||(i=Math.min(i,u)),isNaN(d)||(h=Math.max(h,d))}(!isFinite(i)||!isFinite(h))&&(i=0,h=1);const y=Math.max(1,h-i);return s.jsxs("div",{className:"trace-view",children:[s.jsxs("div",{className:"trace-view-top",children:[s.jsxs("span",{className:"trace-view-id",children:["trace ",t.traceId.slice(0,8),"…"]}),s.jsxs("span",{className:"trace-view-count",children:[t.spanCount," span",t.spanCount===1?"":"s"," · ",t.rowCount," rows"]})]}),s.jsx("div",{className:"trace-view-rows",children:n.map(({span:o,depth:u},d)=>{const m=Rn(o.startTs),f=Rn(o.endTs)||m,g=isNaN(m)?0:(m-i)/y*100,w=isNaN(m)?100:Math.max(1.5,(f-m)/y*100),S=o.status==="error"||o.level==="error"?"err":o.unterminated?"open":`cat-${o.category}`;return s.jsxs("div",{className:`trace-span${o.spanId===r?" hi":""}`,children:[s.jsxs("div",{className:"trace-label",style:{paddingLeft:`${u*14}px`},title:o.event,children:[s.jsx("span",{className:"trace-glyph",children:$d(o.category)}),s.jsx("span",{className:"trace-event",children:o.event}),s.jsx("span",{className:"trace-message",children:o.message})]}),s.jsx("div",{className:"trace-track",children:s.jsx("div",{className:`trace-bar ${S}`,style:{left:`${g}%`,width:`${Math.min(w,100-g)}%`},children:s.jsx("span",{className:"trace-bar-dur",children:o.unterminated?"…":o.durationMs>0?`${o.durationMs}ms`:""})})})]},o.spanId+d)})})]})}const Vv={personal:"Personal",server:"Server"},qv={personal:"Synced from your claude.ai account",server:"Configured on this host"},Gv={connected:"connected",needs_auth:"needs auth",pending:"pending",unknown:"unknown"};function Jv(){ds("console");const[e,t]=C.useState([]),[r,n]=C.useState(!1),[i,h]=C.useState(null),[y,o]=C.useState(null),[u,d]=C.useState(!1),[m,f]=C.useState(""),[g,w]=C.useState("http"),[S,v]=C.useState(""),[p,c]=C.useState(""),[a,l]=C.useState(!1),[_,j]=C.useState(null),b=C.useCallback(()=>{n(!0),h(null),ee("/api/mcp").then(E=>t(E.servers||[])).catch(E=>h(E.message)).finally(()=>n(!1))},[]);C.useEffect(()=>b(),[b]);async function k(){if(!m.trim()||!S.trim()){h("A name and URL are required.");return}l(!0),h(null);try{await oe("/api/mcp",{name:m.trim(),transport:g,url:S.trim(),header:p.trim()}),o(`Connected ${m.trim()}.`),f(""),v(""),c(""),d(!1),b()}catch(E){h(`Couldn't connect: ${E.message}`)}finally{l(!1)}}async function x(E){h(null);try{await je(`/api/mcp/${encodeURIComponent(E.name)}/login`),j(E.name)}catch(L){h(`Couldn't start login: ${L.message}`)}}async function N(E){if(confirm(`Remove ${E.name}? The host claude will no longer connect to it.`)){h(null);try{await St(`/api/mcp/${encodeURIComponent(E.name)}`),o(`Removed ${E.name}.`),b()}catch(L){h(`Couldn't remove: ${L.message}`)}}}return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All projects"}),s.jsx("span",{className:"brand-name",children:"Integrations"}),s.jsx("button",{type:"button",className:"brand-sub auto-btn link",onClick:b,disabled:r,children:r&&e.length>0?"⟳ refreshing…":"⟳ refresh"})]})}),s.jsxs("div",{className:"auto-page",children:[s.jsxs("p",{className:"auto-intro",children:["Connect MCP servers on the host — the dashboard chat can use them. These live in your host"," ",s.jsx("code",{children:"claude"})," setup and are never reachable from a sandbox."]}),i&&s.jsx("div",{className:"auto-msg err",children:i}),y&&!i&&s.jsx("div",{className:"auto-msg",children:y}),r&&e.length===0?s.jsxs("div",{className:"mcp-loading",children:[s.jsx("span",{className:"mcp-spinner","aria-hidden":"true"})," Checking MCP servers…"]}):e.length===0&&!r?s.jsxs("p",{className:"auto-empty",children:["No MCP servers connected yet."," ",s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>d(!0),children:"Add one"})]}):s.jsx("ul",{className:"mcp-list",children:e.map(E=>s.jsxs("li",{className:"mcp-row",children:[s.jsx("span",{className:`mcp-dot mcp-${E.status}`,title:E.statusText||E.status}),s.jsxs("div",{className:"mcp-id",children:[s.jsxs("div",{className:"mcp-name",children:[E.name,E.kind&&s.jsx("span",{className:`mcp-kind mcp-kind-${E.kind}`,title:qv[E.kind],children:Vv[E.kind]})]}),s.jsxs("div",{className:"mcp-url",children:[E.url,E.transport?s.jsxs("span",{className:"mcp-transport",children:[" · ",E.transport]}):null]})]}),s.jsxs("div",{className:"mcp-right",children:[s.jsx("span",{className:`mcp-status mcp-${E.status}`,children:Gv[E.status]}),E.status==="needs_auth"&&s.jsx("button",{type:"button",className:"mcp-auth-btn",onClick:()=>x(E),children:"authenticate"}),s.jsx("button",{type:"button",className:"mcp-x",title:"Remove",onClick:()=>N(E),children:"×"})]})]},E.name))}),_&&s.jsxs("div",{className:"mcp-login",children:[s.jsxs("div",{className:"mcp-login-head",children:[s.jsxs("span",{children:["Authenticating ",s.jsx("b",{children:_})," — complete the login in the terminal (a browser tab may open)."]}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>{j(null),b()},children:"Done ⟳"})]}),s.jsx("div",{className:"mcp-login-term",children:s.jsx(Zs,{fullPath:"/api/mcp/login/ws"})})]}),u?s.jsxs("div",{className:"mcp-add-form",children:[s.jsx("h3",{className:"mcp-add-h",children:"Add an MCP server"}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"Name"}),s.jsx("input",{className:"auto-input",placeholder:"sentry",value:m,onChange:E=>f(E.target.value)})]}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"Transport"}),s.jsxs("select",{className:"auto-input",value:g,onChange:E=>w(E.target.value),children:[s.jsx("option",{value:"http",children:"http"}),s.jsx("option",{value:"sse",children:"sse"})]})]}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"URL"}),s.jsx("input",{className:"auto-input",placeholder:"https://mcp.sentry.dev/mcp",value:S,onChange:E=>v(E.target.value)})]}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"Authorization"}),s.jsx("input",{className:"auto-input",placeholder:"Bearer … (optional — leave blank to authenticate later)",value:p,onChange:E=>c(E.target.value?Yv(E.target.value):"")})]}),s.jsxs("div",{className:"mcp-add-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",disabled:a,onClick:k,children:a?"Connecting…":"Connect"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>d(!1),children:"Cancel"})]})]}):e.length>0&&s.jsx("button",{type:"button",className:"mcp-add-btn",onClick:()=>d(!0),children:"+ Add MCP server"})]})]})}function Yv(e){const t=e.trim();return t.includes(": ")?t:`Authorization: ${t}`}function Qc({onConvMeta:e,persistKey:t="global",onBusyChange:r}={}){const[n,i]=C.useState(null),[h,y]=C.useState(null),o=C.useCallback(()=>{ee("/api/chat/capability").then(i).catch(()=>i({capability:null,configured:!1})),ee("/global/config").then(y).catch(()=>y({api_writes_enabled:!1,api_writes_configured:!0}))},[]);return C.useEffect(()=>o(),[o]),!n||!h?s.jsx("div",{className:"firstrun-loading",children:"…"}):!n.configured||!h.api_writes_configured?s.jsx(Qv,{cap:n,writes:h,onDone:o}):s.jsx(an,{wsPath:"/chat/ws",getCtx:()=>Xv(window.location.pathname),persistKey:t,canAct:n.capability==="act",onConvMeta:e,onBusyChange:r})}function Xv(e){let t=e.match(/^\/repos\/([^/]+)\/prs\/(\d+)/);return t?`The user is viewing pull request #${t[2]} of repo ${t[1]}.`:(t=e.match(/^\/repos\/([^/]+)/),t?`The user is viewing repo ${t[1]}.`:(t=e.match(/^\/p\/([^/]+)/),t?`The user is viewing project ${t[1]}.`:e.startsWith("/logs")?"The user is viewing the activity logs.":e.startsWith("/integrations")?"The user is viewing the MCP integrations.":e.startsWith("/automations")?"The user is viewing automations and flows.":""))}function Qv({cap:e,writes:t,onDone:r}){const n=!e.configured,i=!t.api_writes_configured,[h,y]=C.useState(e.capability||"readonly"),[o,u]=C.useState(t.api_writes_enabled),[d,m]=C.useState(!1),[f,g]=C.useState(null);async function w(v,p,c){const a=await fetch(v,{method:p,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Error(`HTTP ${a.status}`)}async function S(){m(!0),g(null);try{n&&await w("/api/chat/capability","PUT",{capability:h}),i&&await w("/global/apply","POST",{api_writes_enabled:o}),r()}catch(v){g(`Couldn't save: ${v.message}`)}finally{m(!1)}}return s.jsxs("div",{className:"firstrun",children:[s.jsx("h3",{className:"firstrun-h",children:"Set up the assistant"}),s.jsxs("p",{className:"firstrun-sub",children:["Claude here can help across the whole app. Choose how much it can do — you can change this anytime in"," ","Global settings."]}),n&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:`firstrun-opt${h==="readonly"?" sel":""}`,children:[s.jsx("input",{type:"radio",name:"cap",checked:h==="readonly",onChange:()=>y("readonly")}),s.jsxs("div",{children:[s.jsx("div",{className:"firstrun-opt-title",children:"Read-only"}),s.jsx("div",{className:"firstrun-opt-desc",children:"It can look — read logs, list flows, inspect PRs — but not change anything."})]})]}),s.jsxs("label",{className:`firstrun-opt${h==="act"?" sel":""}`,children:[s.jsx("input",{type:"radio",name:"cap",checked:h==="act",onChange:()=>y("act")}),s.jsxs("div",{children:[s.jsx("div",{className:"firstrun-opt-title",children:"Can act"}),s.jsx("div",{className:"firstrun-opt-desc",children:"It can also run things — create issues, start projects, run flows. Doing so needs API writes (below)."})]})]})]}),i&&s.jsxs("label",{className:`firstrun-opt${o?" sel":""}`,children:[s.jsx("input",{type:"checkbox",checked:o,onChange:v=>u(v.target.checked)}),s.jsxs("div",{children:[s.jsx("div",{className:"firstrun-opt-title",children:"Allow API writes"}),s.jsxs("div",{className:"firstrun-opt-desc",children:["Let the ",s.jsx("code",{children:"corral api"})," CLI and this assistant make changes — create issues, start projects, run flows, create skills & scripts. Leave off to keep them read-only. You stay in control; change it anytime in Global settings."]})]})]}),f&&s.jsx("div",{className:"auto-msg err",children:f}),s.jsx("button",{type:"button",className:"auto-btn firstrun-save",disabled:d,onClick:S,children:d?"Saving…":"Start chatting"})]})}const Zv="corral.conductors",e_="corral.conductorRailWidth",t_=150;function s_(e){let t=0;for(const r of e){const n=parseInt(r.id.replace(/\D/g,""),10);!Number.isNaN(n)&&n>t&&(t=n)}return`c${t+1}`}function r_({onConvMeta:e}){const[t,r]=it(Zv,[{id:"c1",label:"Conductor 1"}]),[n,i]=C.useState(()=>{var S;return((S=t[0])==null?void 0:S.id)||"c1"}),[h,y]=C.useState({}),o=(S,v)=>y(p=>p[S]===v?p:{...p,[S]:v}),[u,d]=it(e_,t_),m=Qs({axis:"x",edge:"end",get:()=>u,min:110,max:()=>Math.round(window.innerWidth*.5),onResize:d}),f=S=>S==="c1"?"global":`global-${S}`;function g(){r(S=>{const v=s_(S),p={id:v,label:`Conductor ${S.length+1}`};return i(v),[...S,p]})}function w(S){try{const v=f(S);localStorage.removeItem(`corral.chat.msgs.${v}`),localStorage.removeItem(`corral.chat.sid.${v}`)}catch{}r(v=>{const p=v.filter(a=>a.id!==S),c=p.length?p:[{id:"c1",label:"Conductor 1"}];return i(a=>a===S?c[0].id:a),c})}if(t.length<=1){const S=t[0]||{id:"c1"};return s.jsxs("div",{className:"conductors",children:[s.jsx("div",{className:"conductors-solo-head",children:s.jsx("button",{type:"button",className:"work-rail-new",title:"Run another global conductor",onClick:g,children:"+ New conductor"})}),s.jsx("div",{className:"conductors-view",children:s.jsx(Qc,{persistKey:f(S.id),onConvMeta:e,onBusyChange:v=>o(S.id,v)})})]})}return s.jsxs("div",{className:"work-tab conductors",children:[s.jsxs("div",{className:"work-rail",style:{flex:`0 0 ${u}px`},children:[s.jsxs("div",{className:"work-rail-head",children:[s.jsx("span",{children:"Conductors"}),s.jsx("button",{type:"button",className:"work-rail-new",title:"Run another global conductor",onClick:g,children:"+ New"})]}),t.map((S,v)=>{const p=!!h[S.id];return s.jsxs("div",{className:`work-rail-item${n===S.id?" active":""}`,children:[s.jsxs("button",{type:"button",className:"work-rail-btn",onClick:()=>i(S.id),children:[s.jsxs("span",{className:"work-rail-label",children:[s.jsx("i",{className:`work-dot ${p?"running":"idle"}`}),S.label||`Conductor ${v+1}`]}),s.jsx("span",{className:"work-rail-status",children:p?"working":"waiting"})]}),s.jsx("button",{type:"button",className:"work-rail-close",title:"Close this conductor (clears its conversation)",onClick:()=>w(S.id),children:"✕"})]},S.id)})]}),s.jsx("div",{className:"work-rail-resize",ref:m,title:"Drag to resize the list"}),s.jsx("div",{className:"work-view",children:t.map(S=>s.jsx("div",{style:{display:n===S.id?"flex":"none",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(Qc,{persistKey:f(S.id),onConvMeta:n===S.id?e:void 0,onBusyChange:v=>o(S.id,v)})},S.id))})]})}const n_="corral.workRailWidth",i_=150,Wn=new Set(["preparing","running","idle"]);function Zc(e){return e.kind==="worker"?e.title||"worker":`${e.repoName} #${e.prNumber}`}function o_(e){return Wn.has(e.status)?e.activity==="idle"?"work-dot idle":"work-dot running":e.status==="failed"||e.status==="canceled"||e.status==="interrupted"?"work-dot err":"work-dot done"}function a_({onCount:e}){const[t,r]=C.useState([]),[n,i]=C.useState(null),h=C.useRef(!1),[y,o]=C.useState(!1),[u,d]=C.useState(""),[m,f]=C.useState(""),[g,w]=C.useState(!1),[S,v]=it(n_,i_),p=Qs({axis:"x",edge:"end",get:()=>S,min:110,max:()=>Math.round(window.innerWidth*.5),onResize:v}),c=C.useCallback(()=>{ee("/merge-jobs").then(b=>{const k=b.jobs||[];r(k),e==null||e(k.length),i(x=>x&&k.some(N=>N.id===x)?x:k.length?k[0].id:null),h.current=!0}).catch(()=>{})},[e]);C.useEffect(()=>{c();const k=t.some(N=>Wn.has(N.status))?2500:8e3,x=setInterval(c,k);return()=>clearInterval(x)},[c,t]);const a=async b=>{if(Wn.has(b.status)){const k=b.kind==="worker"?"still running":"still merging";if(!window.confirm(`"${Zc(b)}" is ${k}. Stop it and remove the job?`))return}try{await St(`/merge-jobs/${encodeURIComponent(b.id)}`)}catch{}i(k=>k===b.id?null:k),c()},l=async()=>{if(m.trim()){w(!0);try{const b=await oe("/api/conductor/workers",{title:u.trim()||void 0,prompt:m});o(!1),d(""),f(""),i(b.jobId),c()}catch{}finally{w(!1)}}},_=t.find(b=>b.id===n)||null,j=s.jsxs("div",{className:"work-compose",children:[s.jsx("input",{className:"work-compose-title",type:"text",placeholder:"Task title (optional)",value:u,onChange:b=>d(b.target.value)}),s.jsx("textarea",{className:"work-compose-prompt",rows:4,placeholder:"What should this worker Claude do? It runs fresh and independent, in the background.",value:m,onChange:b=>f(b.target.value)}),s.jsxs("div",{className:"work-compose-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:g||!m.trim(),onClick:l,children:g?"Starting…":"Start worker"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:"Cancel"})]}),s.jsx("div",{className:"work-compose-note ai-warn",children:"host · not sandboxed · uses your global chat capability"})]});return h.current&&t.length===0?s.jsx("div",{className:"work-tab-empty",children:y?j:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"work-empty",children:["No background jobs yet. Delegate a task to a fresh worker Claude, or start a"," ",s.jsx("b",{children:"Merge with host"})," on a PR — both run here so you can navigate away and come back."]}),s.jsx("button",{type:"button",className:"btn primary work-new-btn",onClick:()=>o(!0),children:"+ New task"})]})}):s.jsxs("div",{className:"work-tab",children:[s.jsxs("div",{className:"work-rail",style:{flex:`0 0 ${S}px`},children:[s.jsxs("div",{className:"work-rail-head",children:[s.jsx("span",{children:"Jobs"}),s.jsx("button",{type:"button",className:"work-rail-new",title:"Delegate a task to a new worker Claude",onClick:()=>o(b=>!b),children:"+ New"})]}),y&&s.jsx("div",{className:"work-rail-compose",children:j}),t.map(b=>s.jsxs("div",{className:`work-rail-item${n===b.id?" active":""}`,children:[s.jsxs("button",{type:"button",className:"work-rail-btn",onClick:()=>i(b.id),title:`${b.status} · ${b.strategy}`,children:[s.jsx("i",{className:o_(b)}),s.jsx("span",{className:"work-rail-label",children:b.kind==="worker"?b.title||"worker":s.jsxs(s.Fragment,{children:[b.repoName," ",s.jsxs("span",{className:"work-rail-pr",children:["#",b.prNumber]})]})}),s.jsx("span",{className:"work-rail-status",children:Wn.has(b.status)&&b.activity?b.activity:b.status})]}),s.jsx("button",{type:"button",className:"work-rail-close",title:"Close job (ends it if running)",onClick:()=>a(b),children:"✕"})]},b.id))]}),s.jsx("div",{className:"work-rail-resize",ref:p,title:"Drag to resize the list"}),s.jsx("div",{className:"work-view",children:_?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"work-view-head",children:[s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude; not sandboxed",children:"host · not sandboxed"}),s.jsxs("span",{className:"work-view-title",children:[Zc(_),_.kind!=="worker"&&_.strategy?` · ${_.strategy}`:""]})]}),_.kind!=="worker"&&s.jsxs("div",{className:"work-view-hint",children:["This runs the editable ",s.jsx("b",{children:"pr.merge"})," prompt — change it in"," ",s.jsx("a",{href:"/automations",children:"Automations → Prompts"}),"."]}),s.jsx("div",{className:"work-view-panel",children:s.jsx(an,{wsPath:`/merge-jobs/${encodeURIComponent(_.id)}/ws`,canAct:!0,persistKey:`merge-job-${_.id}`},_.id)})]}):s.jsx("div",{className:"work-empty",children:"Select a job to view its progress."})})]})}const l_="corral.chatdockWidth",c_=440;function eu(e){let t=e.match(/^\/repos\/([^/]+)\/prs\/(\d+)/);return t?`PR #${t[2]}`:(t=e.match(/^\/repos\/([^/]+)/),t?`repo ${t[1]}`:e.startsWith("/logs")?"logs":e.startsWith("/integrations")?"integrations":e.startsWith("/automations")?"flows":"")}function u_(e,t,r){return e==="project"?r:e==="global"?t:""}function h_(){const{path:e}=ur(),t=_d(e),[r,n]=C.useState(!1),[i,h]=C.useState(!1),[y,o]=it(l_,c_),u=Qs({axis:"x",edge:"start",get:()=>y,min:340,max:()=>Math.round(window.innerWidth*.9),onResize:o}),[d,m]=C.useState("project"),[f,g]=C.useState(0),[w,S]=C.useState(""),[v,p]=C.useState("");C.useEffect(()=>{m(t?"project":"global")},[t]),C.useEffect(()=>{let k=!0;const x=()=>{fetch("/merge-jobs",{credentials:"same-origin"}).then(E=>E.ok?E.json():{jobs:[]}).then(E=>k&&g((E.jobs||[]).length)).catch(()=>{})};x();const N=setInterval(x,5e3);return()=>{k=!1,clearInterval(N)}},[]),C.useEffect(()=>{const k=()=>{g(x=>Math.max(x,1)),m("work"),n(!0),h(!0)};return window.addEventListener("corral:open-work",k),()=>window.removeEventListener("corral:open-work",k)},[]),C.useEffect(()=>{const k=x=>{(x.metaKey||x.ctrlKey)&&(x.key==="k"||x.key==="K")?(x.preventDefault(),n(N=>!N),h(!0)):x.key==="Escape"&&r&&n(!1)};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[r]);function c(){n(k=>!k),h(!0)}const a=!!t,l=f>0,_=d==="project"&&a?"project":d==="work"&&l?"work":"global",j=a||l,b=u_(_,w,v);return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`chatdock-launcher${r?" open":""}`,title:"Ask Claude (⌘K)",onClick:c,children:[s.jsx("span",{className:"chatdock-spark",children:"✦"}),s.jsx("span",{className:"chatdock-launcher-label",children:"Ask Claude"})]}),s.jsxs("aside",{className:`chatdock${r?" open":""}`,"aria-hidden":!r,style:{width:`min(${y}px, 96vw)`},children:[s.jsx("div",{className:"chatdock-resize",ref:u,title:"Drag to resize"}),s.jsxs("header",{className:"chatdock-head",children:[s.jsxs("span",{className:"chatdock-title",children:[s.jsx("span",{className:"chatdock-spark",children:"✦"})," Claude",_==="global"&&eu(e)&&s.jsx("span",{className:"chatdock-ctx",title:"Claude knows what page you're on",children:eu(e)}),(_==="global"||_==="project")&&b&&s.jsx("span",{className:"chatdock-uuid",title:`Conversation ${b} — click to copy`,onClick:()=>{var k;return(k=navigator.clipboard)==null?void 0:k.writeText(b)},children:b.slice(0,8)})]}),s.jsx("button",{type:"button",className:"chatdock-close",title:"Close (Esc)",onClick:()=>n(!1),children:"×"})]}),j&&s.jsxs("div",{className:"chatdock-tabs",children:[a&&s.jsx("button",{type:"button",className:`chatdock-tab${_==="project"?" active":""}`,onClick:()=>m("project"),children:"This project"}),s.jsx("button",{type:"button",className:`chatdock-tab${_==="global"?" active":""}`,onClick:()=>m("global"),children:"Global"}),l&&s.jsxs("button",{type:"button",className:`chatdock-tab${_==="work"?" active":""}`,onClick:()=>m("work"),title:"Host-merge jobs running in the background",children:["Work ",s.jsx("span",{className:"chatdock-tab-count",children:f})]})]}),s.jsx("div",{className:"chatdock-body",children:i&&s.jsxs(s.Fragment,{children:[a&&s.jsx("div",{style:{display:_==="project"?"flex":"none",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(an,{wsPath:`/p/${t}/chat/ws?tools=Read,Grep,Glob`,onConvMeta:k=>p(k.convUuid)})}),s.jsx("div",{style:{display:_==="global"?"flex":"none",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(r_,{onConvMeta:k=>S(k.convUuid)})}),_==="work"&&s.jsx("div",{style:{display:"flex",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(a_,{onCount:g})})]})})]}),r&&s.jsx("div",{className:"chatdock-scrim",onClick:()=>n(!1)})]})}const d_={title:"Projects",blocks:[{img:{src:"/static/app/docs-img/projects.png",alt:"The Projects home screen — one pane per sandboxed project."}},{p:"Every project is a repo checkout running Claude Code in an isolated, network-firewalled Docker sandbox. This is the home screen — one pane per project."},{h:"Start a project"},{p:"Hit **New project** and pick how to seed it:"},{list:["**From repo(s)** — clone one or more repos into a fresh sandbox.","**Blank dir** — an empty workspace.","**Existing dir** — point at a folder you already have."]},{p:"It starts automatically. Click a pane to open the project; the ✕ on a pane stops it."},{h:"What a pane shows"},{p:"Live status per project — whether the container and Claude are up, recent activity, and a peek at the last terminal line. It polls, so it stays fresh on its own."},{p:"Credentials never enter the sandbox — the host proxy injects them. So a project can use `gh`/`git` without a real token ever being inside the container."}],more:"docs/README.md"},f_={title:"Project",blocks:[{p:"One sandboxed project. The right dock is Claude; the tabs on the left are how you inspect and drive the box."},{h:"Tabs"},{list:["**Files** — browse and edit the workspace.","**Diff** — the git diff of what Claude changed.","**Container** — a shell inside the sandbox (`docker exec`).","**Live View** — watch a web app the sandbox is running (see below).","**Mitm Proxy** — inspect the HTTPS traffic the sandbox made.","**Firewall Log** — what the allowlist allowed/blocked.","**Config** — network, DinD, ports, SSH keys, credentials."]},{h:"Talk to Claude"},{p:"The dock on the right is this project's Claude. Type to it; it drives the sandbox. The host shell below it is a plain shell on your machine (not sandboxed)."},{h:"Live View"},{p:"Watch a web app running in the sandbox, embedded here. Pick a detected port or type one, and it loads."},{p:"Running the app inside Docker-in-Docker? Publish its port so it's reachable:"},{code:"docker run -d -p 3000:3000 myapp"},{p:"A bare `EXPOSE` (no `-p`) won't show up. An app in the outer container bound to `0.0.0.0` works without `-p`."},{h:"Change how it runs"},{p:"**Config** holds the restart-required bits: network protection, Docker-in-Docker + published ports, a DinD **data cache** to start from, SSH keys, and per-host credentials. Edits there prompt you to restart the project."}],more:"docs/internal/live-view.md"},p_={title:"Repo",blocks:[{img:{src:"/static/app/docs-img/repo.png",alt:"A repo's page — PR review, projects, forensics, and settings."}},{p:"A repo corral tracks. Spawn sandboxes from it, review its PRs, and attach context that follows every checkout."},{h:"Tabs"},{list:["**PR Review** — corral's read on the repo's open PRs.","**Issues** — issues you can spin a sandbox off of.","**Projects** — sandboxes created from this repo.","**Forensics** — per-file history/churn.","**Settings** — skills & context, automations."]},{h:"Skills & context (Settings)"},{img:{src:"/static/app/docs-img/repo-skills-context.png",alt:"A repo's Skills & context — own skills, inherited global skills, and an AGENTS.md."}},{p:"Attach **skills** (reusable SKILL.md capabilities) and an **AGENTS.md context** (a CLAUDE.md) to this repo. Every sandbox cloned from it carries them in automatically — so the right guidance and tools are always present."},{list:["**This repo's skills** — skills for this repo only. **promote to global** shares one across all repos.","**Global skills** — the shared catalog, each with an inherit / on / off override just for this repo.","**AGENTS.md context** — Corral drafts it with AI when you add the repo; **Regenerate with AI** re-runs it, or edit it inline."]},{p:"When a context goes stale (older than ~3 months by default), a banner nudges you to **Regenerate** it — here, on any sandbox from this repo, and on its PR reviews. Tune the window in **Global settings**."},{h:"Automations (Settings)"},{p:"Repo-scoped prompts, event hooks, and flows. Global ones apply everywhere; repo ones add on top."}],more:"docs/internal/skills-and-context.md"},m_={title:"PR Review",blocks:[{img:{src:"/static/app/docs-img/pr-review.png",alt:"A PR review — corral's AI analysis, risk verdict, and merge options."}},{p:"Corral's analysis of one PR — a fast read before you dive in."},{p:"Spin up a sandbox on the PR branch to verify a change hands-on, or comment/approve straight from here. Actions run as host operations against GitHub (never from inside the sandbox)."},{p:"Ask the Claude dock about the PR — it knows which PR you're looking at."},{h:"Merging"},{p:"The Merge button is a split-button: the ▾ picks how the merge runs."},{list:["**Merge with host** (default) — rebase-and-merge on your host for speed. Runs as a background job in the **Work** tab of the Claude dock (⌘K): it rebases onto the base branch, resolves conflicts, waits for CI, and merges. The job keeps running if you navigate away — come back to it any time from the Work tab. **Not sandboxed** — it runs your host Claude with Bash against a real checkout.","**Merge with sandbox** — the same, but in a one-shot sandbox on the PR branch. Slower to start, but isolated; the sandbox tears itself down once the PR lands (toggle off in Global settings).","**Merge** — a plain `gh pr merge`, no rebase. Fails if GitHub says the PR isn't mergeable."]},{p:"The rebase modes wait for CI: after rebasing they watch the PR's required checks and only merge once they're green — and they merge as a normal user (no admin override), so failing checks or branch protection block the merge rather than being bypassed."},{p:"The **strategy** (squash / merge commit / rebase) is separate from the mode. It resolves per-repo → global → ask: the first time you merge a repo with nothing set, a modal asks and remembers your choice for that repo. Only methods your GitHub repo actually allows are offered."},{p:"Set the default mode + strategy in **Global settings → PR merging**. The rebase-and-merge procedure Claude follows is the editable **pr.merge** prompt in **Automations → Prompts**."}],more:"docs/README.md"},g_={title:"Global settings",blocks:[{img:{src:"/static/app/docs-img/global.png",alt:"Global settings — host-wide defaults, SSH keys, PR merging."}},{p:"Host-wide settings and defaults that apply across all projects."},{list:["Default SSH keys loaded into every sandbox's scoped agent.","Global automations (prompts, hooks, flows) that apply everywhere.","**PR merging** — the default merge mode (sandbox / host / plain), the default strategy, and whether a merge sandbox auto-tears-down.","**AGENTS.md context** — how old a repo's agent context may get before a *regenerate* banner appears (default ~3 months; blank = default, negative = off).","The dashboard's own preferences."]},{p:"Anything set per-repo or per-project layers on top of these."}],more:"docs/skills-and-context.md"},v_={title:"Automations",blocks:[{img:{src:"/static/app/docs-img/automations.png",alt:"Automations — prompts, event hooks, flows, and scripts."}},{p:"Make corral do things on its own — react to events, run multi-step flows, reuse scripts."},{h:"Sub-tabs"},{list:["**Automations** — prompts + trigger cards. Bind an event (PR opened, comment, project start…) to an action.","**Flows** — compose multiple steps into a flow, then run or schedule it.","**Scripts** — your saved bash-script library, callable from flows."]},{h:"A quick flow"},{p:"Add a flow, drop in steps (a prompt, a script, an MCP call), and give it a schedule or run it by hand. See runs in the **Run Log**."},{h:"Global skills"},{img:{src:"/static/app/docs-img/global-skills.png",alt:"The global skills catalog on the Automations tab."}},{p:"A shared catalog of `SKILL.md` capabilities, reusable across every repo. Turn on **Add to all repos** to inject one into every sandbox by default; a repo can still override it on or off in its own **Settings → Skills & context**."}],more:"docs/internal/skills-and-context.md"},__={title:"Run Log",blocks:[{img:{src:"/static/app/docs-img/run-log.png",alt:"The Run Log — a history of automation runs."}},{p:"History of automation + flow runs. Click a run to see its steps, timing, and output."},{p:"Use it to confirm a scheduled flow fired and to debug a step that failed."}],more:"docs/internal/logs.md"},y_={title:"Logs",blocks:[{img:{src:"/static/app/docs-img/logs.png",alt:"Logs — the app-wide searchable activity log and traces."}},{p:"A searchable, host-wide activity log across every project and the dashboard itself."},{p:"Filter by project or category, or search the text. Handy for “what happened around the time X broke?” — spans link related events together."}],more:"docs/internal/logs.md"},x_={title:"Integrations",blocks:[{img:{src:"/static/app/docs-img/integrations.png",alt:"Integrations — connect MCP servers, host-only."}},{p:"Connect MCP servers on the **host**. Once connected, the dashboard chat can use them."},{p:"These live in your host `claude mcp` registry — corral just drives it. Host-only by design: the sandbox never reaches these, keeping the trust one-directional."},{h:"Connect one"},{p:"Add the server, complete any auth it needs, and it shows as **connected**. Remove it to stop the host Claude from using it."}],more:"docs/internal/integrations.md"},Kn=[{key:"projects",page:d_},{key:"project",page:f_},{key:"repo",page:p_},{key:"pr-review",page:m_},{key:"global",page:g_},{key:"automations",page:v_},{key:"run-log",page:__},{key:"logs",page:y_},{key:"integrations",page:x_}];function S_(e){const t=r=>Kn.find(n=>n.key===r);return/^\/p\//.test(e)?t("project"):/^\/repos\/[^/]+\/prs\/\d+/.test(e)?t("pr-review"):/^\/repos\//.test(e)?t("repo"):t(e==="/global"?"global":e==="/logs"||e==="/automations/logs"?"logs":e==="/integrations"?"integrations":e==="/automations/runs"?"run-log":e==="/automations"?"automations":"projects")}function tu(e){return e.split(/(`[^`]+`)/g).map((r,n)=>{if(r.startsWith("`")&&r.endsWith("`"))return s.jsx("code",{children:r.slice(1,-1)},n);const i=r.split(/(\*\*[^*]+\*\*)/g);return s.jsx(C.Fragment,{children:i.map((h,y)=>h.startsWith("**")&&h.endsWith("**")?s.jsx("strong",{children:h.slice(2,-2)},y):s.jsx(C.Fragment,{children:h},y))},n)})}function w_({b:e,onZoom:t}){if(e.h)return s.jsx("h4",{className:"docs-h",children:e.h});if(e.p)return s.jsx("p",{className:"docs-p",children:tu(e.p)});if(e.list)return s.jsx("ul",{className:"docs-list",children:e.list.map((r,n)=>s.jsx("li",{children:tu(r)},n))});if(e.code)return s.jsx("pre",{className:"docs-code",children:e.code});if(e.img){const r=e.img;return s.jsxs("button",{type:"button",className:"docs-shot-wrap",onClick:()=>t==null?void 0:t(r),title:"Click to enlarge",children:[s.jsx("img",{className:"docs-shot",src:r.src,alt:r.alt,loading:"lazy"}),s.jsx("span",{className:"docs-shot-zoom","aria-hidden":"true",children:"⤢ Zoom"})]})}return null}function b_({img:e,onClose:t}){return C.useEffect(()=>{const r=n=>{n.key==="Escape"&&(n.stopPropagation(),t())};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[t]),s.jsxs("div",{className:"docs-lightbox",onClick:t,role:"dialog","aria-modal":"true","aria-label":e.alt,children:[s.jsx("button",{type:"button",className:"docs-lightbox-close",title:"Close (Esc)",onClick:t,children:"×"}),s.jsx("img",{className:"docs-lightbox-img",src:e.src,alt:e.alt,onClick:r=>r.stopPropagation()}),s.jsx("p",{className:"docs-lightbox-cap",children:e.alt})]})}function C_(){const{path:e}=ur(),[t,r]=C.useState(!1),[n,i]=C.useState(null),[h,y]=C.useState(null),o=S_(e).key,u=g=>{const w=typeof g=="function"?g(t):g;w&&i(null),r(w)};C.useEffect(()=>{const g=w=>{(w.metaKey||w.ctrlKey)&&w.key==="/"?(w.preventDefault(),u(S=>!S)):w.key==="Escape"&&t&&r(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]);const d=n??o,f=(Kn.find(g=>g.key===d)??Kn[0]).page;return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`docsdock-launcher${t?" open":""}`,title:"Docs (⌘/)",onClick:()=>u(g=>!g),children:[s.jsx("span",{className:"docsdock-mark",children:"?"}),s.jsx("span",{className:"docsdock-launcher-label",children:"Docs"})]}),s.jsxs("aside",{className:`docsdock${t?" open":""}`,"aria-hidden":!t,children:[s.jsxs("header",{className:"docsdock-head",children:[s.jsxs("span",{className:"docsdock-title",children:[s.jsx("span",{className:"docsdock-mark",children:"?"})," Docs"]}),s.jsx("button",{type:"button",className:"docsdock-close",title:"Close (Esc)",onClick:()=>r(!1),children:"×"})]}),s.jsxs("div",{className:"docsdock-cols",children:[s.jsx("nav",{className:"docsdock-nav","aria-label":"All docs",children:Kn.map(g=>s.jsxs("button",{type:"button",className:`docsdock-navitem${g.key===d?" active":""}${g.key===o?" current":""}`,onClick:()=>i(g.key),title:g.key===o?"The page you're on":void 0,children:[g.page.title,g.key===o&&s.jsx("span",{className:"docsdock-here",children:"•"})]},g.key))}),s.jsxs("div",{className:"docsdock-body",children:[s.jsx("h3",{className:"docsdock-pagetitle",children:f.title}),f.blocks.map((g,w)=>s.jsx(w_,{b:g,onZoom:y},w)),f.more&&s.jsxs("p",{className:"docs-more",children:["Full guide: ",s.jsx("code",{children:f.more})," in the repo."]}),s.jsxs("p",{className:"docs-foot",children:["Press ",s.jsx("kbd",{children:"⌘/"})," anywhere to open docs. Pick any page on the left."]})]})]})]}),t&&s.jsx("div",{className:"docsdock-scrim",onClick:()=>r(!1)}),h&&s.jsx(b_,{img:h,onClose:()=>y(null)})]})}const po="corral.update.unreachableDismissed",su="corral.update.dismissedVersion";function ru(e){try{return localStorage.getItem(e)||""}catch{return""}}function mo(e,t){try{localStorage.setItem(e,t)}catch{}}function k_({status:e}){const[t,r]=C.useState(()=>ru(po)==="1"),[n,i]=C.useState(()=>ru(su)),[h,y]=C.useState(!1);if(!e)return null;if(e.unreachable){if(t)return null;const u=()=>{mo(po,"1"),r(!0)};return s.jsxs("div",{className:"update-banner update-banner-warn",role:"status",children:[s.jsxs("span",{className:"update-banner-text",children:["Couldn't check for updates — the update source"," ",s.jsxs("span",{className:"muted",children:["(",e.repo||"unknown",")"]})," isn't reachable right now."]}),s.jsx("span",{className:"update-banner-actions",children:s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:u,children:"✕"})})]})}if(t&&(mo(po,""),r(!1)),!e.update_available||n&&n===e.latest)return null;const o=()=>{mo(su,e.latest),i(e.latest)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"update-banner",role:"status",children:[s.jsxs("span",{className:"update-banner-text",children:["A new corral release is available — ",s.jsx("strong",{children:e.latest})," ",s.jsxs("span",{className:"muted",children:["(you have ",e.current,")"]})]}),s.jsxs("span",{className:"update-banner-actions",children:[s.jsx("button",{className:"update-banner-btn",onClick:()=>y(!0),children:"Update…"}),s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:o,children:"✕"})]})]}),h&&s.jsxs(hr,{title:`Update corral → ${e.latest}`,onClose:()=>y(!1),children:[s.jsxs("p",{className:"muted",style:{marginTop:0},children:["Running ",s.jsx("code",{children:"corral update"})," on the host. If your binary lives somewhere that needs elevated permissions, follow any printed ",s.jsx("code",{children:"sudo"})," instruction in the terminal. Restart the dashboard afterward to pick up the new build."]}),s.jsxs("div",{className:"populate-term",style:{display:"block",height:380},children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"corral update"]}),s.jsx(Zs,{fullPath:"/update/ws"})]})]})]})}const j_=6*60*60*1e3;function N_(){const[e,t]=C.useState(null);return C.useEffect(()=>{let r=!0;const n=()=>{ee("/update-status").then(h=>{r&&t(h)}).catch(()=>{})};n();const i=window.setInterval(n,j_);return()=>{r=!1,window.clearInterval(i)}},[]),e}function E_(){const{path:e}=ur(),t=_d(e);if(t)return s.jsx(Hg,{id:t});const r=jm(e);if(r)return s.jsx(kv,{repoId:r.repoId,number:r.number});const n=km(e);return n?s.jsx(Qg,{id:n}):e==="/global"?s.jsx(jv,{}):e==="/logs"||e==="/automations/logs"?s.jsx(zv,{}):e==="/integrations"?s.jsx(Jv,{}):e==="/automations/runs"?s.jsx($v,{}):e==="/automations"?s.jsx(Iv,{}):s.jsx(Gm,{})}function R_(){const e=N_();return s.jsx(Im,{children:s.jsxs(Cm,{children:[s.jsx(k_,{status:e}),s.jsx(E_,{}),s.jsx(C_,{}),s.jsx(h_,{})]})})}gd(document.getElementById("root")).render(s.jsx(C.StrictMode,{children:s.jsx(R_,{})})); +`;function Mv(){const[e,t]=C.useState([]),[r,n]=C.useState(null),[i,h]=C.useState(""),[y,o]=C.useState(""),[u,d]=C.useState(!0),[m,f]=C.useState(null),g=C.useCallback(()=>{ee("/api/skills?scope=global").then(c=>t(c.skills||[])).catch(c=>f({text:c.message,err:!0}))},[]);C.useEffect(()=>g(),[g]);function w(){n("new"),h(""),o(Ov),d(!0)}function S(c){n(c.id),h(c.name),o(c.content),d(c.autoAll)}async function v(){if(!i.trim()||!y.trim()){f({text:"A name and SKILL.md content are required.",err:!0});return}try{r==="new"?await oe("/api/skills",{scope:"global",name:i.trim(),content:y,autoAll:u}):typeof r=="number"&&await Un(`/api/skills/${r}`,{name:i.trim(),content:y,autoAll:u}),n(null),f({text:`Saved "${i.trim()}".`,err:!1}),g()}catch(c){f({text:`Couldn't save: ${c.message}`,err:!0})}}async function p(c){if(confirm(`Delete the global "${c.name}" skill? It will be removed from every repo that uses it.`))try{await St(`/api/skills/${c.id}`),g()}catch(a){f({text:`Couldn't delete: ${a.message}`,err:!0})}}return s.jsxs("section",{className:"auto-section",children:[s.jsxs("div",{className:"reposkills-head",children:[s.jsx("h2",{className:"auto-mgr-h",style:{marginTop:0},children:"Global skills"}),r===null&&s.jsx("button",{type:"button",className:"auto-btn",onClick:w,children:"+ New global skill"})]}),s.jsxs("p",{className:"auto-intro",style:{marginTop:0},children:["Skills shared across all repos. Turn on ",s.jsx("b",{children:"Add to all repos"})," to inject a skill into every sandbox by default; each repo can still toggle it on or off in its own Settings."]}),m&&s.jsx("div",{className:`auto-msg${m.err?" err":""}`,children:m.text}),r!==null?s.jsxs("div",{className:"reposkills-editor",children:[s.jsx("input",{className:"auto-input",placeholder:"skill name (letters, digits, - or _)",value:i,onChange:c=>h(c.target.value)}),s.jsx("textarea",{className:"auto-input reposkills-md",placeholder:"SKILL.md — YAML frontmatter (name, description) then the instructions.",value:y,onChange:c=>o(c.target.value),rows:12}),s.jsxs("p",{className:"auto-hint",children:["The ",s.jsx("code",{children:"description"})," is the one line the model matches to decide whether to load this skill. Say what it does ",s.jsx("b",{children:"and"})," name the situation — “Use this when…”. A topic label loses; a named situation fires."]}),s.jsxs("label",{className:"reposkills-autoall",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:c=>d(c.target.checked)})," ","Add to all repos by default"]}),s.jsxs("div",{className:"reposkills-editor-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",onClick:v,children:"Save skill"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>n(null),children:"Cancel"})]})]}):e.length===0?s.jsx("p",{className:"auto-empty",children:"No global skills yet. Add one to share it across every repo."}):s.jsx("ul",{className:"reposkills-list",children:e.map(c=>s.jsxs("li",{className:"reposkills-item",children:[s.jsxs("span",{className:"reposkills-name",children:[c.name,c.autoAll&&s.jsx("span",{className:"reposkills-badge",children:"all repos"})]}),s.jsxs("div",{className:"reposkills-item-actions",children:[s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>S(c),children:"edit"}),s.jsx("button",{type:"button",className:"reposkills-x",title:"Delete",onClick:()=>p(c),children:"×"})]})]},c.id))})]})}function Iv(){ds("console");const[e,t]=C.useState("automations");return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All repos"}),s.jsx("span",{className:"brand-name",children:"Automations"}),s.jsx(be,{to:"/global",className:"brand-sub",children:"global settings →"})]})}),s.jsxs("div",{className:"auto-page",children:[s.jsxs("div",{className:"tabs",style:{marginBottom:"1rem"},children:[s.jsx("button",{type:"button",className:`tab-btn${e==="automations"?" active":""}`,onClick:()=>t("automations"),children:"Automations"}),s.jsx("button",{type:"button",className:`tab-btn${e==="flows"?" active":""}`,onClick:()=>t("flows"),children:"Flows"}),s.jsx("button",{type:"button",className:`tab-btn${e==="scripts"?" active":""}`,onClick:()=>t("scripts"),children:"Scripts"})]}),e==="automations"&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"auto-intro",children:["Turn events into your own units of work. Each card is something Corral already does — add your own steps to run alongside it. These are ",s.jsx("b",{children:"global"})," defaults; per-repo overrides live in a repo's Settings tab."]}),s.jsx(Bd,{}),s.jsx(Mv,{}),s.jsx("section",{className:"auto-section",children:s.jsx(be,{to:"/automations/runs",className:"auto-runs-link",children:"View run history →"})})]}),e==="flows"&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"auto-intro",children:["Wire actions into a multi-step flow. Each step hands its result to the next as"," ",s.jsx("code",{children:"{{steps..output}}"}),"; a step can wait for others with ",s.jsx("b",{children:"after"}),". Run a flow now, or put it on a schedule."]}),s.jsx(Dv,{})]}),e==="scripts"&&s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"auto-mgr-h",style:{marginTop:0},children:"Saved scripts"}),s.jsx(Ev,{})]})]})]})}function Yc(e){switch(e){case"ok":return"run-ok";case"error":return"run-err";case"partial":return"run-partial";default:return"run-running"}}function Bv(e){try{return JSON.parse(e)||[]}catch{return[]}}function $v(){ds("console");const[e,t]=C.useState([]),[r,n]=C.useState({}),[i,h]=C.useState(null),y=C.useCallback(()=>{ee("/api/runs?limit=100").then(o=>t(o.runs||[])).catch(o=>h(o.message))},[]);return C.useEffect(()=>{y()},[y]),s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/automations",className:"back",children:"← Automations"}),s.jsx("span",{className:"brand-name",children:"Run history"}),s.jsx("button",{type:"button",className:"brand-sub auto-btn link",onClick:y,children:"⟳ refresh"})]})}),s.jsxs("div",{className:"auto-page",children:[i&&s.jsx("div",{className:"auto-msg err",children:i}),e.length===0?s.jsx("p",{className:"auto-empty",children:"No runs yet. Actions and hooks record their executions here."}):s.jsx("ul",{className:"run-list",children:e.map(o=>{const u=Bv(o.steps),d=!!r[o.id];return s.jsxs("li",{className:"run-item",children:[s.jsxs("button",{type:"button",className:"run-head",onClick:()=>n(m=>({...m,[o.id]:!m[o.id]})),children:[s.jsx("span",{className:`run-badge ${Yc(o.status)}`,children:o.status}),s.jsxs("span",{className:"run-what",children:[o.event?s.jsx("code",{children:o.event}):o.trigger,s.jsxs("span",{className:"run-meta",children:[o.trigger," · ",u.length," step",u.length===1?"":"s"]})]}),s.jsx("span",{className:"run-time",children:o.startedAt}),s.jsx("span",{className:"run-caret",children:d?"▾":"▸"})]}),d&&s.jsxs("div",{className:"run-steps",children:[u.length===0&&s.jsx("div",{className:"run-empty",children:"no steps recorded"}),u.map((m,f)=>s.jsxs("div",{className:"run-step",children:[s.jsxs("div",{className:"run-step-head",children:[s.jsx("span",{className:`run-dot ${Yc(m.status)}`}),s.jsx("b",{children:m.name||`#${m.actionId}`}),s.jsx("code",{className:"run-step-kind",children:m.kind}),s.jsxs("span",{className:"run-step-dur",children:[m.durationMs,"ms"]})]}),m.output&&s.jsx("pre",{className:"run-out",children:m.output}),m.error&&s.jsx("pre",{className:"run-out run-out-err",children:m.error})]},f)),o.context&&o.context!=="{}"&&s.jsxs("details",{className:"run-ctx",children:[s.jsx("summary",{children:"context"}),s.jsx("pre",{className:"run-out",children:o.context})]})]})]},o.id)})})]})]})}const Hv=["","info","warn","error","debug"];function Xc(e,t){return e==="error"||t==="error"?"log-error":e==="warn"||t==="partial"?"log-warn":"log-ok"}function $d(e){switch(e){case"ai":return"✨";case"pr-action":return"⑃";case"project":return"▤";case"automation":return"⚡";case"script":return"⚙";case"repo":return"◧";case"chat":return"💬";case"http":return"→";default:return"•"}}function Fv(e){const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Uv(){const[e,t]=C.useState([]),[r,n]=C.useState(0),[i,h]=C.useState(!1),[y,o]=C.useState(null),[u,d]=C.useState({}),[m,f]=C.useState(null),[g,w]=C.useState(null),[S,v]=C.useState(!1),p=C.useCallback(O=>{f(W=>W===O?(w(null),null):(w(null),v(!0),ee(`/api/logs/trace/${encodeURIComponent(O)}`).then(F=>w(F)).catch(()=>w(null)).finally(()=>v(!1)),O))},[]),[c,a]=C.useState(""),[l,_]=C.useState(""),[j,b]=C.useState(""),[k,x]=C.useState(""),[N,E]=C.useState(!1),[L,T]=C.useState([]),[P,B]=C.useState([]);C.useEffect(()=>{ee("/api/logs/facets").then(O=>{T(O.categories||[]),B(O.projects||[])}).catch(()=>{})},[]);const U=C.useRef(null),[K,q]=C.useState("");C.useEffect(()=>(U.current&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>q(k.trim()),300),()=>{U.current&&window.clearTimeout(U.current)}),[k]);const $=C.useCallback(O=>{const W=new URLSearchParams({limit:"60"});return O&&W.set("before",String(O)),c&&W.set("category",c),l&&W.set("project",l),j&&W.set("level",j),K&&W.set("q",K),W.toString()},[c,l,j,K]),R=C.useCallback(()=>{h(!0),o(null),ee(`/api/logs?${$(0)}`).then(O=>{t(O.logs||[]),n(O.nextCursor||0)}).catch(O=>o(O.message)).finally(()=>h(!1))},[$]);C.useEffect(()=>{R()},[R]);const A=()=>{!r||i||(h(!0),ee(`/api/logs?${$(r)}`).then(O=>{t(W=>[...W,...O.logs||[]]),n(O.nextCursor||0)}).catch(O=>o(O.message)).finally(()=>h(!1)))},M=e.filter(O=>!(N&&!c&&O.category==="http"));return s.jsxs("div",{className:"auto-page",children:[s.jsx("div",{className:"logs-panel-toolbar",children:s.jsx("button",{type:"button",className:"auto-btn link",onClick:R,children:"⟳ refresh"})}),s.jsxs("div",{className:"logs-filters",children:[s.jsx("input",{className:"auto-input logs-search",placeholder:"🔍 search logs…",value:k,onChange:O=>x(O.target.value)}),s.jsxs("select",{className:"auto-input",value:c,onChange:O=>a(O.target.value),children:[s.jsx("option",{value:"",children:"all categories"}),L.map(O=>s.jsx("option",{value:O,children:O},O))]}),P.length>0&&s.jsxs("select",{className:"auto-input",value:l,onChange:O=>_(O.target.value),children:[s.jsx("option",{value:"",children:"all projects"}),P.map(O=>s.jsx("option",{value:O,children:O},O))]}),s.jsx("select",{className:"auto-input",value:j,onChange:O=>b(O.target.value),children:Hv.map(O=>s.jsx("option",{value:O,children:O||"all levels"},O))}),s.jsxs("label",{className:"logs-hidehttp",children:[s.jsx("input",{type:"checkbox",checked:N,onChange:O=>E(O.target.checked),disabled:!!c}),"hide request logs"]})]}),y&&s.jsx("div",{className:"auto-msg err",children:y}),M.length===0&&!i?e.length>0&&N&&!c?s.jsxs("p",{className:"auto-empty",children:["Only request logs so far, and they're hidden."," ",s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>E(!1),children:"Show request logs"})]}):s.jsx("p",{className:"auto-empty",children:"No logs match. Activity is recorded here as it happens."}):s.jsx("ul",{className:"logs-list",children:M.map(O=>{const W=!!u[O.id],F=O.meta&&O.meta!=="{}"||O.runId||O.traceId;return s.jsxs("li",{className:`logs-row ${Xc(O.level,O.status)}`,children:[s.jsxs("button",{type:"button",className:"logs-row-head",onClick:()=>F&&d(z=>({...z,[O.id]:!z[O.id]})),children:[s.jsx("span",{className:"logs-time",children:Fv(O.ts)}),s.jsxs("span",{className:"logs-cat",title:O.category,children:[$d(O.category)," ",O.category]}),s.jsx("span",{className:"logs-msg",children:O.message}),O.status&&s.jsx("span",{className:`logs-status ${Xc(O.level,O.status)}`,children:O.status}),typeof O.durationMs=="number"&&O.durationMs>0&&s.jsxs("span",{className:"logs-dur",children:[O.durationMs,"ms"]}),F&&s.jsx("span",{className:"logs-caret",children:W?"▾":"▸"})]}),W&&s.jsxs("div",{className:"logs-detail",children:[s.jsxs("div",{className:"logs-detail-meta",children:[s.jsx("span",{className:"logs-detail-k",children:"event"})," ",s.jsx("code",{children:O.event}),O.repoId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"logs-detail-k",children:"repo"})," ",s.jsx("code",{children:O.repoId})]}),O.projectId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"logs-detail-k",children:"project"})," ",s.jsx("code",{children:O.projectId})]})]}),O.meta&&O.meta!=="{}"&&s.jsx("pre",{className:"logs-detail-json",children:Wv(O.meta)}),s.jsxs("div",{className:"logs-detail-actions",children:[O.runId?s.jsxs(be,{to:"/automations/runs",className:"auto-btn link",children:["View run #",O.runId," →"]}):null,O.traceId?s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>p(O.traceId),children:m===O.traceId?"Hide trace ▾":"View trace ▸"}):null]}),O.traceId&&m===O.traceId&&s.jsx(Kv,{loading:S,trace:g,highlight:O.spanId})]})]},O.id)})}),s.jsx("div",{className:"logs-more",children:r?s.jsx("button",{type:"button",className:"auto-btn",disabled:i,onClick:A,children:i?"Loading…":"Load older"}):!i&&M.length>0&&s.jsx("span",{className:"auto-empty",children:"— end of logs —"})})]})}function zv(){ds("console");const[e,t]=C.useState("logs");return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All projects"}),s.jsx("span",{className:"brand-name",children:"Logs"})]})}),s.jsx("div",{className:"logs-page-tabs",children:s.jsxs("div",{className:"tabs",children:[s.jsx("button",{type:"button",className:`tab-btn${e==="logs"?" active":""}`,onClick:()=>t("logs"),children:"Activity log"}),s.jsx("button",{type:"button",className:`tab-btn${e==="conversations"?" active":""}`,onClick:()=>t("conversations"),children:"Conversations"})]})}),e==="logs"?s.jsx(Uv,{}):s.jsx(Md,{})]})}function Wv(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Hd(e,t,r){for(const n of e||[])r.push({span:n,depth:t}),Hd(n.children,t+1,r)}function Rn(e){if(!e)return NaN;const t=new Date(e).getTime();return isNaN(t)?NaN:t}function Kv({loading:e,trace:t,highlight:r}){if(e)return s.jsx("div",{className:"trace-view loading",children:"Loading trace…"});if(!t||t.roots.length===0)return s.jsx("div",{className:"trace-view empty",children:"No trace data."});const n=[];Hd(t.roots,0,n);let i=1/0,h=-1/0;for(const{span:o}of n){const u=Rn(o.startTs),d=Rn(o.endTs)||u;isNaN(u)||(i=Math.min(i,u)),isNaN(d)||(h=Math.max(h,d))}(!isFinite(i)||!isFinite(h))&&(i=0,h=1);const y=Math.max(1,h-i);return s.jsxs("div",{className:"trace-view",children:[s.jsxs("div",{className:"trace-view-top",children:[s.jsxs("span",{className:"trace-view-id",children:["trace ",t.traceId.slice(0,8),"…"]}),s.jsxs("span",{className:"trace-view-count",children:[t.spanCount," span",t.spanCount===1?"":"s"," · ",t.rowCount," rows"]})]}),s.jsx("div",{className:"trace-view-rows",children:n.map(({span:o,depth:u},d)=>{const m=Rn(o.startTs),f=Rn(o.endTs)||m,g=isNaN(m)?0:(m-i)/y*100,w=isNaN(m)?100:Math.max(1.5,(f-m)/y*100),S=o.status==="error"||o.level==="error"?"err":o.unterminated?"open":`cat-${o.category}`;return s.jsxs("div",{className:`trace-span${o.spanId===r?" hi":""}`,children:[s.jsxs("div",{className:"trace-label",style:{paddingLeft:`${u*14}px`},title:o.event,children:[s.jsx("span",{className:"trace-glyph",children:$d(o.category)}),s.jsx("span",{className:"trace-event",children:o.event}),s.jsx("span",{className:"trace-message",children:o.message})]}),s.jsx("div",{className:"trace-track",children:s.jsx("div",{className:`trace-bar ${S}`,style:{left:`${g}%`,width:`${Math.min(w,100-g)}%`},children:s.jsx("span",{className:"trace-bar-dur",children:o.unterminated?"…":o.durationMs>0?`${o.durationMs}ms`:""})})})]},o.spanId+d)})})]})}const Vv={personal:"Personal",server:"Server"},qv={personal:"Synced from your claude.ai account",server:"Configured on this host"},Gv={connected:"connected",needs_auth:"needs auth",pending:"pending",unknown:"unknown"};function Jv(){ds("console");const[e,t]=C.useState([]),[r,n]=C.useState(!1),[i,h]=C.useState(null),[y,o]=C.useState(null),[u,d]=C.useState(!1),[m,f]=C.useState(""),[g,w]=C.useState("http"),[S,v]=C.useState(""),[p,c]=C.useState(""),[a,l]=C.useState(!1),[_,j]=C.useState(null),b=C.useCallback(()=>{n(!0),h(null),ee("/api/mcp").then(E=>t(E.servers||[])).catch(E=>h(E.message)).finally(()=>n(!1))},[]);C.useEffect(()=>b(),[b]);async function k(){if(!m.trim()||!S.trim()){h("A name and URL are required.");return}l(!0),h(null);try{await oe("/api/mcp",{name:m.trim(),transport:g,url:S.trim(),header:p.trim()}),o(`Connected ${m.trim()}.`),f(""),v(""),c(""),d(!1),b()}catch(E){h(`Couldn't connect: ${E.message}`)}finally{l(!1)}}async function x(E){h(null);try{await je(`/api/mcp/${encodeURIComponent(E.name)}/login`),j(E.name)}catch(L){h(`Couldn't start login: ${L.message}`)}}async function N(E){if(confirm(`Remove ${E.name}? The host claude will no longer connect to it.`)){h(null);try{await St(`/api/mcp/${encodeURIComponent(E.name)}`),o(`Removed ${E.name}.`),b()}catch(L){h(`Couldn't remove: ${L.message}`)}}}return s.jsxs(s.Fragment,{children:[s.jsx("header",{className:"console-header",children:s.jsxs("div",{className:"brand",children:[s.jsx(be,{to:"/",className:"back",children:"← All projects"}),s.jsx("span",{className:"brand-name",children:"Integrations"}),s.jsx("button",{type:"button",className:"brand-sub auto-btn link",onClick:b,disabled:r,children:r&&e.length>0?"⟳ refreshing…":"⟳ refresh"})]})}),s.jsxs("div",{className:"auto-page",children:[s.jsxs("p",{className:"auto-intro",children:["Connect MCP servers on the host — the dashboard chat can use them. These live in your host"," ",s.jsx("code",{children:"claude"})," setup and are never reachable from a sandbox."]}),i&&s.jsx("div",{className:"auto-msg err",children:i}),y&&!i&&s.jsx("div",{className:"auto-msg",children:y}),r&&e.length===0?s.jsxs("div",{className:"mcp-loading",children:[s.jsx("span",{className:"mcp-spinner","aria-hidden":"true"})," Checking MCP servers…"]}):e.length===0&&!r?s.jsxs("p",{className:"auto-empty",children:["No MCP servers connected yet."," ",s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>d(!0),children:"Add one"})]}):s.jsx("ul",{className:"mcp-list",children:e.map(E=>s.jsxs("li",{className:"mcp-row",children:[s.jsx("span",{className:`mcp-dot mcp-${E.status}`,title:E.statusText||E.status}),s.jsxs("div",{className:"mcp-id",children:[s.jsxs("div",{className:"mcp-name",children:[E.name,E.kind&&s.jsx("span",{className:`mcp-kind mcp-kind-${E.kind}`,title:qv[E.kind],children:Vv[E.kind]})]}),s.jsxs("div",{className:"mcp-url",children:[E.url,E.transport?s.jsxs("span",{className:"mcp-transport",children:[" · ",E.transport]}):null]})]}),s.jsxs("div",{className:"mcp-right",children:[s.jsx("span",{className:`mcp-status mcp-${E.status}`,children:Gv[E.status]}),E.status==="needs_auth"&&s.jsx("button",{type:"button",className:"mcp-auth-btn",onClick:()=>x(E),children:"authenticate"}),s.jsx("button",{type:"button",className:"mcp-x",title:"Remove",onClick:()=>N(E),children:"×"})]})]},E.name))}),_&&s.jsxs("div",{className:"mcp-login",children:[s.jsxs("div",{className:"mcp-login-head",children:[s.jsxs("span",{children:["Authenticating ",s.jsx("b",{children:_})," — complete the login in the terminal (a browser tab may open)."]}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>{j(null),b()},children:"Done ⟳"})]}),s.jsx("div",{className:"mcp-login-term",children:s.jsx(Zs,{fullPath:"/api/mcp/login/ws"})})]}),u?s.jsxs("div",{className:"mcp-add-form",children:[s.jsx("h3",{className:"mcp-add-h",children:"Add an MCP server"}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"Name"}),s.jsx("input",{className:"auto-input",placeholder:"sentry",value:m,onChange:E=>f(E.target.value)})]}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"Transport"}),s.jsxs("select",{className:"auto-input",value:g,onChange:E=>w(E.target.value),children:[s.jsx("option",{value:"http",children:"http"}),s.jsx("option",{value:"sse",children:"sse"})]})]}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"URL"}),s.jsx("input",{className:"auto-input",placeholder:"https://mcp.sentry.dev/mcp",value:S,onChange:E=>v(E.target.value)})]}),s.jsxs("div",{className:"mcp-field",children:[s.jsx("label",{children:"Authorization"}),s.jsx("input",{className:"auto-input",placeholder:"Bearer … (optional — leave blank to authenticate later)",value:p,onChange:E=>c(E.target.value?Yv(E.target.value):"")})]}),s.jsxs("div",{className:"mcp-add-actions",children:[s.jsx("button",{type:"button",className:"auto-btn",disabled:a,onClick:k,children:a?"Connecting…":"Connect"}),s.jsx("button",{type:"button",className:"auto-btn link",onClick:()=>d(!1),children:"Cancel"})]})]}):e.length>0&&s.jsx("button",{type:"button",className:"mcp-add-btn",onClick:()=>d(!0),children:"+ Add MCP server"})]})]})}function Yv(e){const t=e.trim();return t.includes(": ")?t:`Authorization: ${t}`}function Qc({onConvMeta:e,persistKey:t="global",onBusyChange:r}={}){const[n,i]=C.useState(null),[h,y]=C.useState(null),o=C.useCallback(()=>{ee("/api/chat/capability").then(i).catch(()=>i({capability:null,configured:!1})),ee("/global/config").then(y).catch(()=>y({api_writes_enabled:!1,api_writes_configured:!0}))},[]);return C.useEffect(()=>o(),[o]),!n||!h?s.jsx("div",{className:"firstrun-loading",children:"…"}):!n.configured||!h.api_writes_configured?s.jsx(Qv,{cap:n,writes:h,onDone:o}):s.jsx(an,{wsPath:"/chat/ws",getCtx:()=>Xv(window.location.pathname),persistKey:t,canAct:n.capability==="act",onConvMeta:e,onBusyChange:r})}function Xv(e){let t=e.match(/^\/repos\/([^/]+)\/prs\/(\d+)/);return t?`The user is viewing pull request #${t[2]} of repo ${t[1]}.`:(t=e.match(/^\/repos\/([^/]+)/),t?`The user is viewing repo ${t[1]}.`:(t=e.match(/^\/p\/([^/]+)/),t?`The user is viewing project ${t[1]}.`:e.startsWith("/logs")?"The user is viewing the activity logs.":e.startsWith("/integrations")?"The user is viewing the MCP integrations.":e.startsWith("/automations")?"The user is viewing automations and flows.":""))}function Qv({cap:e,writes:t,onDone:r}){const n=!e.configured,i=!t.api_writes_configured,[h,y]=C.useState(e.capability||"readonly"),[o,u]=C.useState(t.api_writes_enabled),[d,m]=C.useState(!1),[f,g]=C.useState(null);async function w(v,p,c){const a=await fetch(v,{method:p,credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Error(`HTTP ${a.status}`)}async function S(){m(!0),g(null);try{n&&await w("/api/chat/capability","PUT",{capability:h}),i&&await w("/global/apply","POST",{api_writes_enabled:o}),r()}catch(v){g(`Couldn't save: ${v.message}`)}finally{m(!1)}}return s.jsxs("div",{className:"firstrun",children:[s.jsx("h3",{className:"firstrun-h",children:"Set up the assistant"}),s.jsxs("p",{className:"firstrun-sub",children:["Claude here can help across the whole app. Choose how much it can do — you can change this anytime in"," ","Global settings."]}),n&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:`firstrun-opt${h==="readonly"?" sel":""}`,children:[s.jsx("input",{type:"radio",name:"cap",checked:h==="readonly",onChange:()=>y("readonly")}),s.jsxs("div",{children:[s.jsx("div",{className:"firstrun-opt-title",children:"Read-only"}),s.jsx("div",{className:"firstrun-opt-desc",children:"It can look — read logs, list flows, inspect PRs — but not change anything."})]})]}),s.jsxs("label",{className:`firstrun-opt${h==="act"?" sel":""}`,children:[s.jsx("input",{type:"radio",name:"cap",checked:h==="act",onChange:()=>y("act")}),s.jsxs("div",{children:[s.jsx("div",{className:"firstrun-opt-title",children:"Can act"}),s.jsx("div",{className:"firstrun-opt-desc",children:"It can also run things — create issues, start projects, run flows. Doing so needs API writes (below)."})]})]})]}),i&&s.jsxs("label",{className:`firstrun-opt${o?" sel":""}`,children:[s.jsx("input",{type:"checkbox",checked:o,onChange:v=>u(v.target.checked)}),s.jsxs("div",{children:[s.jsx("div",{className:"firstrun-opt-title",children:"Allow API writes"}),s.jsxs("div",{className:"firstrun-opt-desc",children:["Let the ",s.jsx("code",{children:"corral api"})," CLI and this assistant make changes — create issues, start projects, run flows, create skills & scripts. Leave off to keep them read-only. You stay in control; change it anytime in Global settings."]})]})]}),f&&s.jsx("div",{className:"auto-msg err",children:f}),s.jsx("button",{type:"button",className:"auto-btn firstrun-save",disabled:d,onClick:S,children:d?"Saving…":"Start chatting"})]})}const Zv="corral.conductors",e_="corral.conductorRailWidth",t_=150;function s_(e){let t=0;for(const r of e){const n=parseInt(r.id.replace(/\D/g,""),10);!Number.isNaN(n)&&n>t&&(t=n)}return`c${t+1}`}function r_({onConvMeta:e}){const[t,r]=it(Zv,[{id:"c1",label:"Conductor 1"}]),[n,i]=C.useState(()=>{var S;return((S=t[0])==null?void 0:S.id)||"c1"}),[h,y]=C.useState({}),o=(S,v)=>y(p=>p[S]===v?p:{...p,[S]:v}),[u,d]=it(e_,t_),m=Qs({axis:"x",edge:"end",get:()=>u,min:110,max:()=>Math.round(window.innerWidth*.5),onResize:d}),f=S=>S==="c1"?"global":`global-${S}`;function g(){r(S=>{const v=s_(S),p={id:v,label:`Conductor ${S.length+1}`};return i(v),[...S,p]})}function w(S){try{const v=f(S);localStorage.removeItem(`corral.chat.msgs.${v}`),localStorage.removeItem(`corral.chat.sid.${v}`)}catch{}r(v=>{const p=v.filter(a=>a.id!==S),c=p.length?p:[{id:"c1",label:"Conductor 1"}];return i(a=>a===S?c[0].id:a),c})}if(t.length<=1){const S=t[0]||{id:"c1"};return s.jsxs("div",{className:"conductors",children:[s.jsx("div",{className:"conductors-solo-head",children:s.jsx("button",{type:"button",className:"work-rail-new",title:"Run another global conductor",onClick:g,children:"+ New conductor"})}),s.jsx("div",{className:"conductors-view",children:s.jsx(Qc,{persistKey:f(S.id),onConvMeta:e,onBusyChange:v=>o(S.id,v)})})]})}return s.jsxs("div",{className:"work-tab conductors",children:[s.jsxs("div",{className:"work-rail",style:{flex:`0 0 ${u}px`},children:[s.jsxs("div",{className:"work-rail-head",children:[s.jsx("span",{children:"Conductors"}),s.jsx("button",{type:"button",className:"work-rail-new",title:"Run another global conductor",onClick:g,children:"+ New"})]}),t.map((S,v)=>{const p=!!h[S.id];return s.jsxs("div",{className:`work-rail-item${n===S.id?" active":""}`,children:[s.jsxs("button",{type:"button",className:"work-rail-btn",onClick:()=>i(S.id),children:[s.jsxs("span",{className:"work-rail-label",children:[s.jsx("i",{className:`work-dot ${p?"running":"idle"}`}),S.label||`Conductor ${v+1}`]}),s.jsx("span",{className:"work-rail-status",children:p?"working":"waiting"})]}),s.jsx("button",{type:"button",className:"work-rail-close",title:"Close this conductor (clears its conversation)",onClick:()=>w(S.id),children:"✕"})]},S.id)})]}),s.jsx("div",{className:"work-rail-resize",ref:m,title:"Drag to resize the list"}),s.jsx("div",{className:"work-view",children:t.map(S=>s.jsx("div",{style:{display:n===S.id?"flex":"none",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(Qc,{persistKey:f(S.id),onConvMeta:n===S.id?e:void 0,onBusyChange:v=>o(S.id,v)})},S.id))})]})}const n_="corral.workRailWidth",i_=150,Wn=new Set(["preparing","running","idle"]);function Zc(e){return e.kind==="worker"?e.title||"worker":`${e.repoName} #${e.prNumber}`}function o_(e){return Wn.has(e.status)?e.activity==="idle"?"work-dot idle":"work-dot running":e.status==="failed"||e.status==="canceled"||e.status==="interrupted"?"work-dot err":"work-dot done"}function a_({onCount:e}){const[t,r]=C.useState([]),[n,i]=C.useState(null),h=C.useRef(!1),[y,o]=C.useState(!1),[u,d]=C.useState(""),[m,f]=C.useState(""),[g,w]=C.useState(!1),[S,v]=it(n_,i_),p=Qs({axis:"x",edge:"end",get:()=>S,min:110,max:()=>Math.round(window.innerWidth*.5),onResize:v}),c=C.useCallback(()=>{ee("/merge-jobs").then(b=>{const k=b.jobs||[];r(k),e==null||e(k.length),i(x=>x&&k.some(N=>N.id===x)?x:k.length?k[0].id:null),h.current=!0}).catch(()=>{})},[e]);C.useEffect(()=>{c();const k=t.some(N=>Wn.has(N.status))?2500:8e3,x=setInterval(c,k);return()=>clearInterval(x)},[c,t]);const a=async b=>{if(Wn.has(b.status)){const k=b.kind==="worker"?"still running":"still merging";if(!window.confirm(`"${Zc(b)}" is ${k}. Stop it and remove the job?`))return}try{await St(`/merge-jobs/${encodeURIComponent(b.id)}`)}catch{}i(k=>k===b.id?null:k),c()},l=async()=>{if(m.trim()){w(!0);try{const b=await oe("/api/conductor/workers",{title:u.trim()||void 0,prompt:m});o(!1),d(""),f(""),i(b.jobId),c()}catch{}finally{w(!1)}}},_=t.find(b=>b.id===n)||null,j=s.jsxs("div",{className:"work-compose",children:[s.jsx("input",{className:"work-compose-title",type:"text",placeholder:"Task title (optional)",value:u,onChange:b=>d(b.target.value)}),s.jsx("textarea",{className:"work-compose-prompt",rows:4,placeholder:"What should this worker Claude do? It runs fresh and independent, in the background.",value:m,onChange:b=>f(b.target.value)}),s.jsxs("div",{className:"work-compose-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:g||!m.trim(),onClick:l,children:g?"Starting…":"Start worker"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:"Cancel"})]}),s.jsx("div",{className:"work-compose-note ai-warn",children:"host · not sandboxed · uses your global chat capability"})]});return h.current&&t.length===0?s.jsx("div",{className:"work-tab-empty",children:y?j:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"work-empty",children:["No background jobs yet. Delegate a task to a fresh worker Claude, or start a"," ",s.jsx("b",{children:"Merge with host"})," on a PR — both run here so you can navigate away and come back."]}),s.jsx("button",{type:"button",className:"btn primary work-new-btn",onClick:()=>o(!0),children:"+ New task"})]})}):s.jsxs("div",{className:"work-tab",children:[s.jsxs("div",{className:"work-rail",style:{flex:`0 0 ${S}px`},children:[s.jsxs("div",{className:"work-rail-head",children:[s.jsx("span",{children:"Jobs"}),s.jsx("button",{type:"button",className:"work-rail-new",title:"Delegate a task to a new worker Claude",onClick:()=>o(b=>!b),children:"+ New"})]}),y&&s.jsx("div",{className:"work-rail-compose",children:j}),t.map(b=>s.jsxs("div",{className:`work-rail-item${n===b.id?" active":""}`,children:[s.jsxs("button",{type:"button",className:"work-rail-btn",onClick:()=>i(b.id),title:`${b.status} · ${b.strategy}`,children:[s.jsx("i",{className:o_(b)}),s.jsx("span",{className:"work-rail-label",children:b.kind==="worker"?b.title||"worker":s.jsxs(s.Fragment,{children:[b.repoName," ",s.jsxs("span",{className:"work-rail-pr",children:["#",b.prNumber]})]})}),s.jsx("span",{className:"work-rail-status",children:Wn.has(b.status)&&b.activity?b.activity:b.status})]}),s.jsx("button",{type:"button",className:"work-rail-close",title:"Close job (ends it if running)",onClick:()=>a(b),children:"✕"})]},b.id))]}),s.jsx("div",{className:"work-rail-resize",ref:p,title:"Drag to resize the list"}),s.jsx("div",{className:"work-view",children:_?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"work-view-head",children:[s.jsx("span",{className:"ai-warn",title:"Runs your host machine's Claude; not sandboxed",children:"host · not sandboxed"}),s.jsxs("span",{className:"work-view-title",children:[Zc(_),_.kind!=="worker"&&_.strategy?` · ${_.strategy}`:""]})]}),_.kind!=="worker"&&s.jsxs("div",{className:"work-view-hint",children:["This runs the editable ",s.jsx("b",{children:"pr.merge"})," prompt — change it in"," ",s.jsx("a",{href:"/automations",children:"Automations → Prompts"}),"."]}),s.jsx("div",{className:"work-view-panel",children:s.jsx(an,{wsPath:`/merge-jobs/${encodeURIComponent(_.id)}/ws`,canAct:!0,persistKey:`merge-job-${_.id}`},_.id)})]}):s.jsx("div",{className:"work-empty",children:"Select a job to view its progress."})})]})}const l_="corral.chatdockWidth",c_=440;function eu(e){let t=e.match(/^\/repos\/([^/]+)\/prs\/(\d+)/);return t?`PR #${t[2]}`:(t=e.match(/^\/repos\/([^/]+)/),t?`repo ${t[1]}`:e.startsWith("/logs")?"logs":e.startsWith("/integrations")?"integrations":e.startsWith("/automations")?"flows":"")}function u_(e,t,r){return e==="project"?r:e==="global"?t:""}function h_(){const{path:e}=ur(),t=_d(e),[r,n]=C.useState(!1),[i,h]=C.useState(!1),[y,o]=it(l_,c_),u=Qs({axis:"x",edge:"start",get:()=>y,min:340,max:()=>Math.round(window.innerWidth*.9),onResize:o}),[d,m]=C.useState("project"),[f,g]=C.useState(0),[w,S]=C.useState(""),[v,p]=C.useState("");C.useEffect(()=>{m(t?"project":"global")},[t]),C.useEffect(()=>{let k=!0;const x=()=>{fetch("/merge-jobs",{credentials:"same-origin"}).then(E=>E.ok?E.json():{jobs:[]}).then(E=>k&&g((E.jobs||[]).length)).catch(()=>{})};x();const N=setInterval(x,5e3);return()=>{k=!1,clearInterval(N)}},[]),C.useEffect(()=>{const k=()=>{g(x=>Math.max(x,1)),m("work"),n(!0),h(!0)};return window.addEventListener("corral:open-work",k),()=>window.removeEventListener("corral:open-work",k)},[]),C.useEffect(()=>{const k=x=>{(x.metaKey||x.ctrlKey)&&(x.key==="k"||x.key==="K")?(x.preventDefault(),n(N=>!N),h(!0)):x.key==="Escape"&&r&&n(!1)};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[r]);function c(){n(k=>!k),h(!0)}const a=!!t,l=f>0,_=d==="project"&&a?"project":d==="work"&&l?"work":"global",j=a||l,b=u_(_,w,v);return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`chatdock-launcher${r?" open":""}`,title:"Ask Claude (⌘K)",onClick:c,children:[s.jsx("span",{className:"chatdock-spark",children:"✦"}),s.jsx("span",{className:"chatdock-launcher-label",children:"Ask Claude"})]}),s.jsxs("aside",{className:`chatdock${r?" open":""}`,"aria-hidden":!r,style:{width:`min(${y}px, 96vw)`},children:[s.jsx("div",{className:"chatdock-resize",ref:u,title:"Drag to resize"}),s.jsxs("header",{className:"chatdock-head",children:[s.jsxs("span",{className:"chatdock-title",children:[s.jsx("span",{className:"chatdock-spark",children:"✦"})," Claude",_==="global"&&eu(e)&&s.jsx("span",{className:"chatdock-ctx",title:"Claude knows what page you're on",children:eu(e)}),(_==="global"||_==="project")&&b&&s.jsx("span",{className:"chatdock-uuid",title:`Conversation ${b} — click to copy`,onClick:()=>{var k;return(k=navigator.clipboard)==null?void 0:k.writeText(b)},children:b.slice(0,8)})]}),s.jsx("button",{type:"button",className:"chatdock-close",title:"Close (Esc)",onClick:()=>n(!1),children:"×"})]}),j&&s.jsxs("div",{className:"chatdock-tabs",children:[a&&s.jsx("button",{type:"button",className:`chatdock-tab${_==="project"?" active":""}`,onClick:()=>m("project"),children:"This project"}),s.jsx("button",{type:"button",className:`chatdock-tab${_==="global"?" active":""}`,onClick:()=>m("global"),children:"Global"}),l&&s.jsxs("button",{type:"button",className:`chatdock-tab${_==="work"?" active":""}`,onClick:()=>m("work"),title:"Host-merge jobs running in the background",children:["Work ",s.jsx("span",{className:"chatdock-tab-count",children:f})]})]}),s.jsx("div",{className:"chatdock-body",children:i&&s.jsxs(s.Fragment,{children:[a&&s.jsx("div",{style:{display:_==="project"?"flex":"none",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(an,{wsPath:`/p/${t}/chat/ws?tools=Read,Grep,Glob`,onConvMeta:k=>p(k.convUuid)})}),s.jsx("div",{style:{display:_==="global"?"flex":"none",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(r_,{onConvMeta:k=>S(k.convUuid)})}),_==="work"&&s.jsx("div",{style:{display:"flex",flex:1,minHeight:0,flexDirection:"column"},children:s.jsx(a_,{onCount:g})})]})})]}),r&&s.jsx("div",{className:"chatdock-scrim",onClick:()=>n(!1)})]})}const d_={title:"Projects",blocks:[{img:{src:"/static/app/docs-img/projects.png",alt:"The Projects home screen — one pane per sandboxed project."}},{p:"Every project is a repo checkout running Claude Code in an isolated, network-firewalled Docker sandbox. This is the home screen — one pane per project."},{h:"Start a project"},{p:"Hit **New project** and pick how to seed it:"},{list:["**From repo(s)** — clone one or more repos into a fresh sandbox.","**Blank dir** — an empty workspace.","**Existing dir** — point at a folder you already have."]},{p:"It starts automatically. Click a pane to open the project; the ✕ on a pane stops it."},{h:"What a pane shows"},{p:"Live status per project — whether the container and Claude are up, recent activity, and a peek at the last terminal line. It polls, so it stays fresh on its own."},{p:"Credentials never enter the sandbox — the host proxy injects them. So a project can use `gh`/`git` without a real token ever being inside the container."}],more:"docs/README.md"},f_={title:"Project",blocks:[{p:"One sandboxed project. The right dock is Claude; the tabs on the left are how you inspect and drive the box."},{h:"Tabs"},{list:["**Files** — browse and edit the workspace.","**Diff** — the git diff of what Claude changed.","**Container** — a shell inside the sandbox (`docker exec`).","**Live View** — watch a web app the sandbox is running (see below).","**Mitm Proxy** — inspect the HTTPS traffic the sandbox made.","**Firewall Log** — what the allowlist allowed/blocked.","**Config** — network, DinD, ports, SSH keys, credentials."]},{h:"Talk to Claude"},{p:"The dock on the right is this project's Claude. Type to it; it drives the sandbox. The host shell below it is a plain shell on your machine (not sandboxed)."},{h:"Live View"},{p:"Watch a web app running in the sandbox, embedded here. Pick a detected port or type one, and it loads."},{p:"Running the app inside Docker-in-Docker? Publish its port so it's reachable:"},{code:"docker run -d -p 3000:3000 myapp"},{p:"A bare `EXPOSE` (no `-p`) won't show up. An app in the outer container bound to `0.0.0.0` works without `-p`."},{h:"Change how it runs"},{p:"**Config** holds the restart-required bits: network protection, Docker-in-Docker + published ports, a DinD **data cache** to start from, SSH keys, and per-host credentials. Edits there prompt you to restart the project."}],more:"docs/internal/live-view.md"},p_={title:"Repo",blocks:[{img:{src:"/static/app/docs-img/repo.png",alt:"A repo's page — PR review, projects, forensics, and settings."}},{p:"A repo corral tracks. Spawn sandboxes from it, review its PRs, and attach context that follows every checkout."},{h:"Tabs"},{list:["**PR Review** — corral's read on the repo's open PRs.","**Issues** — issues you can spin a sandbox off of.","**Projects** — sandboxes created from this repo.","**Forensics** — per-file history/churn.","**Settings** — skills & context, automations."]},{h:"Skills & context (Settings)"},{img:{src:"/static/app/docs-img/repo-skills-context.png",alt:"A repo's Skills & context — own skills, inherited global skills, and an AGENTS.md."}},{p:"Attach **skills** (reusable SKILL.md capabilities) and an **AGENTS.md context** (a CLAUDE.md) to this repo. Every sandbox cloned from it carries them in automatically — so the right guidance and tools are always present."},{list:["**This repo's skills** — skills for this repo only. **promote to global** shares one across all repos.","**Global skills** — the shared catalog, each with an inherit / on / off override just for this repo.","**AGENTS.md context** — Corral drafts it with AI when you add the repo; **Regenerate with AI** re-runs it, or edit it inline."]},{p:"When a context goes stale (older than ~3 months by default), a banner nudges you to **Regenerate** it — here, on any sandbox from this repo, and on its PR reviews. Tune the window in **Global settings**."},{h:"Automations (Settings)"},{p:"Repo-scoped prompts, event hooks, and flows. Global ones apply everywhere; repo ones add on top."}],more:"docs/internal/skills-and-context.md"},m_={title:"PR Review",blocks:[{img:{src:"/static/app/docs-img/pr-review.png",alt:"A PR review — corral's AI analysis, risk verdict, and merge options."}},{p:"Corral's analysis of one PR — a fast read before you dive in."},{p:"Spin up a sandbox on the PR branch to verify a change hands-on, or comment/approve straight from here. Actions run as host operations against GitHub (never from inside the sandbox)."},{p:"Ask the Claude dock about the PR — it knows which PR you're looking at."},{h:"Merging"},{p:"The Merge button is a split-button: the ▾ picks how the merge runs."},{list:["**Merge with host** (default) — rebase-and-merge on your host for speed. Runs as a background job in the **Work** tab of the Claude dock (⌘K): it rebases onto the base branch, resolves conflicts, waits for CI, and merges. The job keeps running if you navigate away — come back to it any time from the Work tab. **Not sandboxed** — it runs your host Claude with Bash against a real checkout.","**Merge with sandbox** — the same, but in a one-shot sandbox on the PR branch. Slower to start, but isolated; the sandbox tears itself down once the PR lands (toggle off in Global settings).","**Merge** — a plain `gh pr merge`, no rebase. Fails if GitHub says the PR isn't mergeable."]},{p:"The rebase modes wait for CI: after rebasing they watch the PR's required checks and only merge once they're green — and they merge as a normal user (no admin override), so failing checks or branch protection block the merge rather than being bypassed."},{p:"The **strategy** (squash / merge commit / rebase) is separate from the mode. It resolves per-repo → global → ask: the first time you merge a repo with nothing set, a modal asks and remembers your choice for that repo. Only methods your GitHub repo actually allows are offered."},{p:"Set the default mode + strategy in **Global settings → PR merging**. The rebase-and-merge procedure Claude follows is the editable **pr.merge** prompt in **Automations → Prompts**."}],more:"docs/README.md"},g_={title:"Global settings",blocks:[{img:{src:"/static/app/docs-img/global.png",alt:"Global settings — host-wide defaults, SSH keys, PR merging."}},{p:"Host-wide settings and defaults that apply across all projects."},{list:["Default SSH keys loaded into every sandbox's scoped agent.","Global automations (prompts, hooks, flows) that apply everywhere.","**PR merging** — the default merge mode (sandbox / host / plain), the default strategy, and whether a merge sandbox auto-tears-down.","**AGENTS.md context** — how old a repo's agent context may get before a *regenerate* banner appears (default ~3 months; blank = default, negative = off).","The dashboard's own preferences."]},{p:"Anything set per-repo or per-project layers on top of these."}],more:"docs/skills-and-context.md"},v_={title:"Automations",blocks:[{img:{src:"/static/app/docs-img/automations.png",alt:"Automations — prompts, event hooks, flows, and scripts."}},{p:"Make corral do things on its own — react to events, run multi-step flows, reuse scripts."},{h:"Sub-tabs"},{list:["**Automations** — prompts + trigger cards. Bind an event (PR opened, comment, project start…) to an action.","**Flows** — compose multiple steps into a flow, then run or schedule it.","**Scripts** — your saved bash-script library, callable from flows."]},{h:"A quick flow"},{p:"Add a flow, drop in steps (a prompt, a script, an MCP call), and give it a schedule or run it by hand. See runs in the **Run Log**."},{h:"Global skills"},{img:{src:"/static/app/docs-img/global-skills.png",alt:"The global skills catalog on the Automations tab."}},{p:"A shared catalog of `SKILL.md` capabilities, reusable across every repo. Turn on **Add to all repos** to inject one into every sandbox by default; a repo can still override it on or off in its own **Settings → Skills & context**."}],more:"docs/internal/skills-and-context.md"},__={title:"Run Log",blocks:[{img:{src:"/static/app/docs-img/run-log.png",alt:"The Run Log — a history of automation runs."}},{p:"History of automation + flow runs. Click a run to see its steps, timing, and output."},{p:"Use it to confirm a scheduled flow fired and to debug a step that failed."}],more:"docs/internal/logs.md"},y_={title:"Logs",blocks:[{img:{src:"/static/app/docs-img/logs.png",alt:"Logs — the app-wide searchable activity log and traces."}},{p:"A searchable, host-wide activity log across every project and the dashboard itself."},{p:"Filter by project or category, or search the text. Handy for “what happened around the time X broke?” — spans link related events together."}],more:"docs/internal/logs.md"},x_={title:"Integrations",blocks:[{img:{src:"/static/app/docs-img/integrations.png",alt:"Integrations — connect MCP servers, host-only."}},{p:"Connect MCP servers on the **host**. Once connected, the dashboard chat can use them."},{p:"These live in your host `claude mcp` registry — corral just drives it. Host-only by design: the sandbox never reaches these, keeping the trust one-directional."},{h:"Connect one"},{p:"Add the server, complete any auth it needs, and it shows as **connected**. Remove it to stop the host Claude from using it."}],more:"docs/internal/integrations.md"},Kn=[{key:"projects",page:d_},{key:"project",page:f_},{key:"repo",page:p_},{key:"pr-review",page:m_},{key:"global",page:g_},{key:"automations",page:v_},{key:"run-log",page:__},{key:"logs",page:y_},{key:"integrations",page:x_}];function S_(e){const t=r=>Kn.find(n=>n.key===r);return/^\/p\//.test(e)?t("project"):/^\/repos\/[^/]+\/prs\/\d+/.test(e)?t("pr-review"):/^\/repos\//.test(e)?t("repo"):t(e==="/global"?"global":e==="/logs"||e==="/automations/logs"?"logs":e==="/integrations"?"integrations":e==="/automations/runs"?"run-log":e==="/automations"?"automations":"projects")}function tu(e){return e.split(/(`[^`]+`)/g).map((r,n)=>{if(r.startsWith("`")&&r.endsWith("`"))return s.jsx("code",{children:r.slice(1,-1)},n);const i=r.split(/(\*\*[^*]+\*\*)/g);return s.jsx(C.Fragment,{children:i.map((h,y)=>h.startsWith("**")&&h.endsWith("**")?s.jsx("strong",{children:h.slice(2,-2)},y):s.jsx(C.Fragment,{children:h},y))},n)})}function w_({b:e,onZoom:t}){if(e.h)return s.jsx("h4",{className:"docs-h",children:e.h});if(e.p)return s.jsx("p",{className:"docs-p",children:tu(e.p)});if(e.list)return s.jsx("ul",{className:"docs-list",children:e.list.map((r,n)=>s.jsx("li",{children:tu(r)},n))});if(e.code)return s.jsx("pre",{className:"docs-code",children:e.code});if(e.img){const r=e.img;return s.jsxs("button",{type:"button",className:"docs-shot-wrap",onClick:()=>t==null?void 0:t(r),title:"Click to enlarge",children:[s.jsx("img",{className:"docs-shot",src:r.src,alt:r.alt,loading:"lazy"}),s.jsx("span",{className:"docs-shot-zoom","aria-hidden":"true",children:"⤢ Zoom"})]})}return null}function b_({img:e,onClose:t}){return C.useEffect(()=>{const r=n=>{n.key==="Escape"&&(n.stopPropagation(),t())};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[t]),s.jsxs("div",{className:"docs-lightbox",onClick:t,role:"dialog","aria-modal":"true","aria-label":e.alt,children:[s.jsx("button",{type:"button",className:"docs-lightbox-close",title:"Close (Esc)",onClick:t,children:"×"}),s.jsx("img",{className:"docs-lightbox-img",src:e.src,alt:e.alt,onClick:r=>r.stopPropagation()}),s.jsx("p",{className:"docs-lightbox-cap",children:e.alt})]})}function C_(){const{path:e}=ur(),[t,r]=C.useState(!1),[n,i]=C.useState(null),[h,y]=C.useState(null),o=S_(e).key,u=g=>{const w=typeof g=="function"?g(t):g;w&&i(null),r(w)};C.useEffect(()=>{const g=w=>{(w.metaKey||w.ctrlKey)&&w.key==="/"?(w.preventDefault(),u(S=>!S)):w.key==="Escape"&&t&&r(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]);const d=n??o,f=(Kn.find(g=>g.key===d)??Kn[0]).page;return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`docsdock-launcher${t?" open":""}`,title:"Docs (⌘/)",onClick:()=>u(g=>!g),children:[s.jsx("span",{className:"docsdock-mark",children:"?"}),s.jsx("span",{className:"docsdock-launcher-label",children:"Docs"})]}),s.jsxs("aside",{className:`docsdock${t?" open":""}`,"aria-hidden":!t,children:[s.jsxs("header",{className:"docsdock-head",children:[s.jsxs("span",{className:"docsdock-title",children:[s.jsx("span",{className:"docsdock-mark",children:"?"})," Docs"]}),s.jsx("button",{type:"button",className:"docsdock-close",title:"Close (Esc)",onClick:()=>r(!1),children:"×"})]}),s.jsxs("div",{className:"docsdock-cols",children:[s.jsx("nav",{className:"docsdock-nav","aria-label":"All docs",children:Kn.map(g=>s.jsxs("button",{type:"button",className:`docsdock-navitem${g.key===d?" active":""}${g.key===o?" current":""}`,onClick:()=>i(g.key),title:g.key===o?"The page you're on":void 0,children:[g.page.title,g.key===o&&s.jsx("span",{className:"docsdock-here",children:"•"})]},g.key))}),s.jsxs("div",{className:"docsdock-body",children:[s.jsx("h3",{className:"docsdock-pagetitle",children:f.title}),f.blocks.map((g,w)=>s.jsx(w_,{b:g,onZoom:y},w)),f.more&&s.jsxs("p",{className:"docs-more",children:["Full guide: ",s.jsx("code",{children:f.more})," in the repo."]}),s.jsxs("p",{className:"docs-foot",children:["Press ",s.jsx("kbd",{children:"⌘/"})," anywhere to open docs. Pick any page on the left."]})]})]})]}),t&&s.jsx("div",{className:"docsdock-scrim",onClick:()=>r(!1)}),h&&s.jsx(b_,{img:h,onClose:()=>y(null)})]})}const po="corral.update.unreachableDismissed",su="corral.update.dismissedVersion";function ru(e){try{return localStorage.getItem(e)||""}catch{return""}}function mo(e,t){try{localStorage.setItem(e,t)}catch{}}function k_({status:e}){const[t,r]=C.useState(()=>ru(po)==="1"),[n,i]=C.useState(()=>ru(su)),[h,y]=C.useState(!1);if(!e)return null;if(e.unreachable){if(t)return null;const u=()=>{mo(po,"1"),r(!0)};return s.jsxs("div",{className:"update-banner update-banner-warn",role:"status",children:[s.jsxs("span",{className:"update-banner-text",children:["Couldn't check for updates — the update source"," ",s.jsxs("span",{className:"muted",children:["(",e.repo||"unknown",")"]})," isn't reachable right now."]}),s.jsx("span",{className:"update-banner-actions",children:s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:u,children:"✕"})})]})}if(t&&(mo(po,""),r(!1)),!e.update_available||n&&n===e.latest)return null;const o=()=>{mo(su,e.latest),i(e.latest)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"update-banner",role:"status",children:[s.jsxs("span",{className:"update-banner-text",children:["A new corral release is available — ",s.jsx("strong",{children:e.latest})," ",s.jsxs("span",{className:"muted",children:["(you have ",e.current,")"]})]}),s.jsxs("span",{className:"update-banner-actions",children:[s.jsx("button",{className:"update-banner-btn",onClick:()=>y(!0),children:"Update…"}),s.jsx("button",{className:"update-banner-dismiss",title:"Dismiss",onClick:o,children:"✕"})]})]}),h&&s.jsxs(hr,{title:`Update corral → ${e.latest}`,onClose:()=>y(!1),children:[s.jsxs("p",{className:"muted",style:{marginTop:0},children:["Running ",s.jsx("code",{children:"corral update"})," on the host. If your binary lives somewhere that needs elevated permissions, follow any printed ",s.jsx("code",{children:"sudo"})," instruction in the terminal. Restart the dashboard afterward to pick up the new build."]}),s.jsxs("div",{className:"populate-term",style:{display:"block",height:380},children:[s.jsxs("div",{className:"screen-bar",children:[s.jsx("i",{className:"screen-dot"}),"corral update"]}),s.jsx(Zs,{fullPath:"/update/ws"})]})]})]})}const j_=6*60*60*1e3;function N_(){const[e,t]=C.useState(null);return C.useEffect(()=>{let r=!0;const n=()=>{ee("/update-status").then(h=>{r&&t(h)}).catch(()=>{})};n();const i=window.setInterval(n,j_);return()=>{r=!1,window.clearInterval(i)}},[]),e}function E_(){const{path:e}=ur(),t=_d(e);if(t)return s.jsx(Hg,{id:t});const r=jm(e);if(r)return s.jsx(kv,{repoId:r.repoId,number:r.number});const n=km(e);return n?s.jsx(Qg,{id:n}):e==="/global"?s.jsx(jv,{}):e==="/logs"||e==="/automations/logs"?s.jsx(zv,{}):e==="/integrations"?s.jsx(Jv,{}):e==="/automations/runs"?s.jsx($v,{}):e==="/automations"?s.jsx(Iv,{}):s.jsx(Gm,{})}function R_(){const e=N_();return s.jsx(Im,{children:s.jsxs(Cm,{children:[s.jsx(k_,{status:e}),s.jsx(E_,{}),s.jsx(C_,{}),s.jsx(h_,{})]})})}gd(document.getElementById("root")).render(s.jsx(C.StrictMode,{children:s.jsx(R_,{})})); diff --git a/internal/dashboard/webui/static/app/index.html b/internal/dashboard/webui/static/app/index.html index 8b62a22..e9df418 100644 --- a/internal/dashboard/webui/static/app/index.html +++ b/internal/dashboard/webui/static/app/index.html @@ -5,7 +5,7 @@ corral — control - + From 20d426c9f9e62805e819898b758fc9a77f692230 Mon Sep 17 00:00:00 2001 From: Jack Rothrock Date: Fri, 4 Sep 2026 17:01:15 -0600 Subject: [PATCH 2/2] fix(conductor): put the sandbox-routing rule in the global chat's context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The global chat still did repo code work inline on the host — e.g. it `cd`'d into ~/core-agent, ran cargo test, committed, and pushed, instead of creating a sandbox project. Root cause (from the logs): the "code tasks run in a sandbox" rule lives in the corral-api SKILL.md, which loads via --plugin-dir but is only READ when the model invokes the skill — for a "run the tests on repo X" ask it often never does. Move the rule into the always-on first-turn context (chatConductorGuidance in withContextHint), GLOBAL chat only (workspace=="" — a project chat already runs inside a sandbox). Now the model sees "you're a conductor on the host; route code work to POST /projects/create" from turn one, regardless of whether it loads the skill. The skill keeps the full API detail. Co-Authored-By: Claude Opus 4.8 (1M context) --- internal/dashboard/chat.go | 32 +++++++++++++++++++++---- internal/dashboard/chat_context_test.go | 30 ++++++++++++++++------- 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/internal/dashboard/chat.go b/internal/dashboard/chat.go index 14db7ed..769bae7 100644 --- a/internal/dashboard/chat.go +++ b/internal/dashboard/chat.go @@ -33,14 +33,38 @@ const chatQuestionGuidance = "When a choice is genuinely ambiguous and a quick d "```corral-question\nquestion: \n-